예제 #1
0
def main():
    try:
        app = QApplication(sys.argv)
        #app.setStyle('cleanlooks')
        app.setStyleSheet(qdarkstyle.load_stylesheet())
        db = Database('sample.db')

        icon = QIcon('app.ico')
        app.setWindowIcon(icon)

    #   set the default font for the app
        app.setFont(MEDIUM_FONT)
        app.setStyle(BUTTON_STYLE)

        main_view = MainView()
        main_view.showMaximized()
 
        main_view.show()
        app.exec_()

    #   clean up and exit code
        for model in main_view.models:
            model.submitAll() # commit all pending changes to all models
        db.close()
        app.quit()
        sys.exit(0)
        #os._exit(0)
    except SystemExit:
        print("Closing Window...")
    except Exception as e:
        print(str(e))
예제 #2
0
class Game:
    # 运行状态
    running = True
    GAME_START = 0
    GAME_OVER = 1
    # 屏幕状态
    screen = None
    # 显示界面
    view = None
    # 运行时钟
    clock = None

    def __init__(self):
        pygame.init()
        # 初始化基础界面
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((300, 150), 0, 32)
        self.view = MainView(self)

    def run(self):
        while self.running:
            for event in pygame.event.get():
                # 分发界面事件
                self.view.on_event(event)
                if event.type == QUIT:
                    self.running = False
            self.screen.fill((0xff, 0xff, 0xff))
            # 调用界面显示
            self.view.on_draw()
            pygame.display.flip()
            self.clock.tick(60)
예제 #3
0
 def index(self, searchquery):
     sm = SearchModel()
     mv = MainView()
     try:
         sm.search_in_database(searchquery)
     except xapian.DatabaseModifiedError:
         return mv.try_again
     return mv.get_search_results(sm.matches)
예제 #4
0
 def index(self, myFile=None):
     um = UploadModel()
     mv = MainView()
     try:
         filename = um.upload_file(myFile)
         return mv.get_file_added(filename)
     except AttributeError:
         return mv.no_file_selected()
예제 #5
0
 def __init__(self, username):
     mixer.init()
     self.username = username
     self.id = uuid.uuid1().time_low
     self.difficulty = 1
     self.setup()
     self.MainView = MainView(self)
     self.muted = False
     self.create_sound()
     self.database = Database(self)
예제 #6
0
 def __init__(self, root):
     self.model = MainModel()
     self.main_view = MainView(root)
     self.main_view.money_ctrl.config(textvariable=self.model.my_money_var)
     self.changer_view = ChangerView(self.main_view)
     self.changer_view.add_button.config(command=self.add_money)
     self.changer_view.remove_button.config(command=self.remove_money)
예제 #7
0
    def start_game(questions):
        results = list(MainRouter().play_quiz(questions).values())
        answers = [question['answer'] for question in questions]

        response = MainView().evaluate_result((results, answers))

        print(f"RESULTS: {response['scores']}/{response['total']}")
        print(response['message'])
예제 #8
0
def main():
    evt_mgr = Mediator()
    clock = CPUSpinnerController(evt_mgr) # controller 1
    # controller = KeyboardController(evt_mgr) # controller 2
    controller = KeyboardController2(evt_mgr) # controller 2
    view = MainView(evt_mgr) # view
    model = Game(evt_mgr) # model
    clock.run()
예제 #9
0
class MainController(BaseController):
    def __init__(self, router, payload):
        super().__init__(router, payload)

        self.__view = MainView(self)
        self.__view.render(payload)

    '''
		Handle the user's choice and redirect
		them to the appropriate view.
		
		@param choice {int} Number corresponding to
		the view in the ordered list menu.
	'''

    def on_choice_selection(self, choice, meta):
        if choice == 1:
            self.dispatch(LOGIN_ROUTE)
        elif choice == 2:
            self.dispatch(ABOUT_ROUTE)
    def __init__(self, in_model):
        """
        """
        self.logger = logging.getLogger("MAIN." + __name__)
        self.model = in_model

        self.view = MainView(self, in_model=self.model)
        self.view.show()

        if self.model.developing:
            self.open_clicked()
예제 #11
0
def demo(screen, scene):
    scenes = [
        Scene([MainView(screen, parts)], -1, name="Main"),
        Scene([RackView(screen, parts, "A")], -1, name="RackA"),
        Scene([RackView(screen, parts, "B")], -1, name="RackB"),
        Scene([RackView(screen, parts, "C")], -1, name="RackC"),
        Scene([RackView(screen, parts, "D")], -1, name="RackD"),
        Scene([RackView(screen, parts, "E")], -1, name="RackE"),
        Scene([BoxListView(screen, parts)], -1, name="Box"),
        #Scene([ListAllView(screen, parts)], -1, name="List"),
        Scene([PartView(screen, parts)], -1, name="Part")
    ]

    screen.play(scenes, stop_on_resize=True, start_scene=scene, allow_int=True)
예제 #12
0
파일: __init__.py 프로젝트: rackeric/test1
def create_app():
    app = Flask(__name__)
    app.config.from_object(config)
    celery = make_celery(app)

    # old API routes
    # url(r"^ansible_jeneric/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<job_id>-.*-*.*)", 'destinyCelery.ansible_jeneric_view'),
    # url(r"^ansible_playbook/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<playbook_id>-.*-*.*)", 'destinyCelery.ansible_playbook_view'),
    # url(r"^ansible_playbook_manual/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<playbook_id>-.*-*.*)", 'destinyCelery.ansible_playbook_manual_view'),
    # url(r"^rax_create_server/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<job_id>-.*-*.*)", 'destinyCelery.rax_create_server_view'),

    app.add_url_rule('/', view_func=MainView.as_view('main_view'))

    app.add_url_rule('/api/v1/ansible_jeneric/<string:user_id>/<string:project_id>/<string:job_id>',
                     view_func=AnsibleJeneric.as_view('ansible_jeneric'))


    return app
예제 #13
0
    def __init__(self):
        super(PianoApp, self).__init__()

        self.SerialConnection = SerialConnection()

        self.window = MainWindow()
        self.window.setWindowTitle("Piano Sensor")

        self.window.show()
        signal.signal(signal.SIGINT, self.window.quit)
        self.window.closeSignal.connect(self.quit)

        self.toolbar = QtWidgets.QToolBar()
        self.window.addToolBar(self.toolbar)
        self.mainView = MainView(self.toolbar,
                                 self.SerialConnection.getDropdownWidget())
        self.window.setCentralWidget(self.mainView)

        self.mainView.refresh.connect(self.SerialConnection.refresh)

        self.mainView.resetEncoders.connect(
            lambda: self.SerialConnection.sendCmd('reset'))
        self.mainView.resetSystem.connect(
            lambda: self.SerialConnection.sendCmd('sysreset'))
        self.mainView.getPositions.connect(
            lambda: self.SerialConnection.sendCmd('pos'))

        self.parser = SerialParser()
        self.SerialConnection.textStream.connect(self.parser.parse_line)
        # self.SerialConnection.textStream.connect(self.mainView.textOutputView.addText)

        self.parser.comment.connect(self.mainView.textOutputView.addComment)

        self.parser.newDataSet.connect(
            lambda i, t, p: self.mainView.resultsView.new_results(
                KeyPress(i, t, p)))
        self.parser.newDataSet.connect(
            lambda i, t, p: self.mainView.textOutputView.new_results(
                KeyPress(i, t, p)))

        status.set_status_logger(self.set_status_message)
        status.set_status('Piano Sensor Ready..')
예제 #14
0
from views import MainView
from seed_data import initialize_seed_data

initialize_seed_data()

view = MainView()
view.prepare_view()

view.render()
예제 #15
0
from views import MainView
from utils.data import classes
import tkinter as tk


root = tk.Tk()
root.geometry("800x800")
window = MainView(master = root, classes= classes)
window.master.title("Clasificador Bayersiano")
window.mainloop()
window.mainloop()
예제 #16
0
# -*- coding: utf-8 -*-
from django.conf.urls import patterns

from views import MainView

urlpatterns = patterns(
    '',
    (r'^', MainView.as_view()),
)
예제 #17
0
 def __init__(self):
     pygame.init()
     # 初始化基础界面
     self.clock = pygame.time.Clock()
     self.screen = pygame.display.set_mode((300, 150), 0, 32)
     self.view = MainView(self)
예제 #18
0
 def __init__(self, pathToDb):
     self.model = MainModel.MainModel(pathToDb)
     self.view = view.View()
     self.mainView = MainView.MainView()
     self.pathToDb = pathToDb
예제 #19
0
파일: urls.py 프로젝트: it-columbo/royalty
from django.conf.urls import patterns, include, url
from views import MainView, WaitedPortsView, CreatePort, CreateNewContentId


urlpatterns = patterns('',

    url(r'^$', MainView.as_view()),
    url(r'^init/$', WaitedPortsView.as_view()),
    url(r'^create/$', CreatePort.as_view()),
    url(r'^newcontentid/$', CreateNewContentId.as_view())

)
예제 #20
0
파일: main.py 프로젝트: meeron/pyrecords
cnt = 0
pw = getpass()
while not Storage.load(args.db, pw):
    cnt = cnt + 1
    if cnt >= 3:
        print("Access Denied")
        exit()
    pw = getpass()

# repeat password for new db file
if Storage.is_new:
    rep_pass = getpass(prompt="Repeat Password: "******"Password do to match. ")
        exit()

views = {"MainView": MainView(), "ListView": ListView(), "AddView": AddView()}
current_view = views["MainView"]

while (True):
    os.system("clear")

    current_view.render()
    new_view = current_view.action(input("\nChoose: "))
    if not new_view:
        continue

    if type(new_view) is BaseView:
        break

    current_view = new_view
예제 #21
0
 def index(self):
     return MainView.get_index(MainView())
예제 #22
0
 def setUp(self):
     self.app = QtGui.QApplication(sys.argv)
     self.view = MainView()
     self.view.show()
예제 #23
0
#!/usr/bin/python3
import services
from views import MainView

if __name__ == '__main__':
    MainView(services)
    
예제 #24
0
class MainViewTest(unittest.TestCase):
    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)
        self.view = MainView()
        self.view.show()

    def tearDown(self):
        self.view.close()
        del self.view
        del self.app

    def test_adding_experiments(self):
        self.view.add_experiment_setup(-333, -100, -90, 0.5, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.2, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.3, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.8, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 3, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 2, 0.4)

    def test_deleting_experiments(self):
        self.view.add_experiment_setup(-333, -100, -90, 0.5, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.2, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.3, 0.4)
        self.view.add_experiment_setup(-333, -100, -90, 0.8, 0.4)

        self.view.del_experiment_setup(3)
        self.view.del_experiment_setup(1)
        self.view.del_experiment_setup(0)
예제 #25
0
from LFSRGenerator import LFSR
# from SSCGenerator import SSC
# from CAutokey import CAutokey
#
# lfsr = LFSR()
# lfsr_blocks = lfsr.generate_blocks("1001", "1101")
# #print(lfsr_blocks)
#
# #
# # ssc = SSC()
# # encrypted = ssc.encrypt(lfsr_blocks, 'test.bin', 'out.bin')
# # decrypted = ssc.decrypt(lfsr_blocks, 'out.bin', 'test1.bin')
# #
# #
# cauto = CAutokey()
# encrypted = cauto.encrypt("1001", "1101",'test.bin', 'out.bin')
# decrypted = cauto.decrypt("1001", "1101",'out.bin', 'test11.bin')
from PyQt5.QtWidgets import QApplication
from views import CAutoKeyView, LFSRView, MainView, SSCView
import sys

app = QApplication(sys.argv)
# window = LFSRView()
#window = CAutoKeyView()
# window = SSCView()
window = MainView()
window.show()
sys.exit(app.exec_())
class MainController():
    """
    Class MainController is a controller
    which coordinates work between
    MainView and MainModel
    """

    def __init__(self, in_model):
        """
        """
        self.logger = logging.getLogger("MAIN." + __name__)
        self.model = in_model

        self.view = MainView(self, in_model=self.model)
        self.view.show()

        if self.model.developing:
            self.open_clicked()

    def help_clicked(self):
        QMessageBox.information(self.view,
                                'Help',
                                """For any help contact:\n
                                Dr. Sergey A. Denisov\n
                                [email protected]""")

    def author_clicked(self):
        QMessageBox.information(self.view,
                                'Author information',
                                """Author: Dr. Sergey A. Denisov\n
                                e-mail: [email protected]\n
                                telephone: +33625252159""")

    def quit_clicked(self, event):
        if not self.model.developing:
            reply = QMessageBox.question(self.view, 'Message',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)

            if reply == QMessageBox.Yes:
                self.logger.info('Closing')
                self.model.kill_observes()
                QApplication.quit()
            else:
                event.ignore()
        else:
            self.logger.info('Closing')
            self.model.remove_tables()
            QApplication.quit()

    def open_clicked(self):
        try:
            if self.model.developing:
                file_name = 'C:\\Users\\saldenisov\\Dropbox\\Python\\QY\\test-excel.xlsx'
            else:
                file_name = QFileDialog.getOpenFileName(self.view,
                                                   'Open file', '')[0]
                if not file_name:
                    raise MyException('FileNotFoundError')
                self.logger.info('Loading file:' + str(file_name))

            modeltable = QYModel(app_folder=self.model.app_folder,
                                 developing=self.model.developing)

            tablecontroller = TableController(in_model=modeltable,
                                              mainmodel=self.model,
                                              name=file_name)
            tablecontroller.model.set_data(file_name)
            datastatus = tablecontroller.model.check_datastatus()
            tablecontroller.model.set_datastatus(datastatus)
            self.model.add_table(table=tablecontroller, name=file_name)
        except (MyException, FileNotFoundError) as e:
            self.empty_clicked()
            self.logger.info('Could not load file')
            self.logger.error(str(e))




    def empty_clicked(self):
        try:
            modeltable = QYModel(app_folder=self.model.app_folder,
                                 developing=self.model.developing)
            name = 'Empty' + str(self.model.emptyfiles)
            self.model.emptyfiles += 1
            tablecontroller = TableController(in_model=modeltable,
                                              mainmodel=self.model,
                                              name=name)
            tablecontroller.model.set_correction()
            datastatus = tablecontroller.model.check_datastatus()
            tablecontroller.model.set_datastatus(datastatus)
            self.model.add_table(table=tablecontroller, name=name)
        except MyException as e:
            self.logger.info('Could not open empty table')
            self.logger.error(str(e))
예제 #27
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from base import Base
from controllers import MainController
from views import MainView

from settings import DB_CONNECTION


engine = create_engine(DB_CONNECTION)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

main_controller = MainController(session)
main_view = MainView(main_controller)

main_view.render()
예제 #28
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from base import Base
from controller import *
from views import MainView

from settings import DB_CONNECTION_STRING

engine = create_engine(DB_CONNECTION_STRING)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

auth_controller = AuthenticationController(session)
transaction_controller = TransactionController(session)
main_view = MainView(auth_controller, transaction_controller)

main_view.render()
예제 #29
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required
from django.views.i18n import javascript_catalog

from devilry_settings.i18n import get_javascript_catalog_packages
from restful import examiner_restful
from views import MainView, AssignmentGroupView, AssignmentView, CompressedFileDownloadView

i18n_packages = get_javascript_catalog_packages(
    "devilry.apps.examiner", "devilry.apps.extjshelpers", "devilry_header", "devilry_extjsextras", "devilry.apps.core"
)

urlpatterns = patterns(
    "devilry.apps.examiner",
    url(r"^$", login_required(MainView.as_view()), name="examiner"),
    url(
        r"^assignmentgroup/(?P<assignmentgroupid>\d+)$",
        login_required(AssignmentGroupView.as_view()),
        name="examiner-agroup-view",
    ),
    url(
        r"^assignment/(?P<assignmentid>\d+)$", login_required(AssignmentView.as_view()), name="examiner-assignment-view"
    ),
    url(
        r"^assignment/compressedfiledownload/(?P<assignmentid>\d+)$",
        login_required(CompressedFileDownloadView.as_view()),
    ),
    url("^i18n.js$", javascript_catalog, kwargs={"packages": i18n_packages}, name="devilry_examiner_i18n"),
)

urlpatterns += examiner_restful
예제 #30
0
from django.conf.urls import *
from views import MainView

urlpatterns = patterns('',
    url(r"^$", MainView.as_view()),
)
예제 #31
0
    def __init__(self, router, payload):
        super().__init__(router, payload)

        self.__view = MainView(self)
        self.__view.render(payload)
예제 #32
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from restful import administrator_restful
from views import (MainView, RestfulSimplifiedView,
                   RestfulSimplifiedAssignmentGroupView)
import editorviews

urlpatterns = patterns('devilry.apps.administrator',
                       url(r'^$',
                           login_required(MainView.as_view()),
                           name='administrator'),
                       editorviews.NodeEditor.create_url(),
                       editorviews.SubjectEditor.create_url(),
                       editorviews.PeriodEditor.create_url(),
                       editorviews.AssignmentEditor.create_url(),
                       RestfulSimplifiedView.as_url('node',
                                                    'administrator/node.django.html'),
                       RestfulSimplifiedView.as_url('subject',
                                                    'administrator/subject.django.html'),
                       RestfulSimplifiedView.as_url('period',
                                                    'administrator/period.django.html'),
                       RestfulSimplifiedView.as_url('assignment',
                                                    'administrator/assignment.django.html'),
                       RestfulSimplifiedAssignmentGroupView.as_url('assignmentgroup',
                                                                   'administrator/assignmentgroupview.django.html')
                      )
urlpatterns += administrator_restful
예제 #33
0
파일: bench-gui.py 프로젝트: kkapitan/bench
from views.MainView import *

if __name__ == '__main__':
    root = Tkinter.Tk()

    MainView(root).pack()

    root.title("Bench by Krzysztof Kapitan & Jan Badura")
    root.resizable(0, 0)
    root.geometry("1200x900")

    root.mainloop()
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from base import Base
from controller import *
from views import MainView

from settings import DB_CONNECTION_STRING


engine = create_engine(DB_CONNECTION_STRING)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

# main_controller = MainController(session)
reg_controller = RegisterController(session)
log_controller = LoginController(session)
main_view = MainView(reg_controller, log_controller)

main_view.main_menu()
예제 #35
0
class GameController(PygameController):

    ###------- game setup ----------------------------------

    def __init__(self, username):
        mixer.init()
        self.username = username
        self.id = uuid.uuid1().time_low
        self.difficulty = 1
        self.setup()
        self.MainView = MainView(self)
        self.muted = False
        self.create_sound()
        self.database = Database(self)

    def create_sound(self):
        self.plant_sound = mixer.Sound("./sounds/plant.wav")
        self.day_sound = mixer.Sound("./sounds/day.mp3")
        self.night_sound = mixer.Sound("./sounds/night.mp3")
        self.background_sound = mixer.Sound("./sounds/background.mp3")
        self.credit_sound = mixer.Sound("./sounds/credit.mp3")
        self.end_sound = mixer.Sound("./sounds/end.mp3")
        self.button_sound = mixer.Sound("./sounds/mode.mp3")
        pygame.mixer.Sound.set_volume(self.button_sound, 0.1)
        pygame.mixer.Sound.set_volume(self.plant_sound, 0.1)
        pygame.mixer.Sound.set_volume(self.background_sound, 0.08)
        pygame.mixer.Sound.set_volume(self.day_sound, 0.1)
        pygame.mixer.Sound.set_volume(self.night_sound, 0.1)
        pygame.mixer.Sound.set_volume(self.credit_sound, 0.1)
        pygame.mixer.Sound.set_volume(self.end_sound, 0.1)

    def setup(self):
        """default game settings"""
        self.cord_list = []
        self.grid_list = []
        self.level = 1
        self.score = 0
        self.remnant_score = 100
        self.money = 200
        self.plants_list = []
        self.peabullet_list = []
        self.icebullet_list = []
        self.explosion_list = []
        self.lycheespike_list = []
        self.jug_list = []
        self.zombie_list = []
        self.count_zombie = 0
        self.count_jug = 0
        self.produce_zombie = 300
        self.produce_jug = 4
        self.GAMEOVER = False
        if self.difficulty == 0:
            self.money = 400
            self.produce_zombie = 200
        elif self.difficulty == 2:
            self.money = 200
            self.produce_zombie = 100

    def init_plant_points(self):
        """Create coordination"""
        for y in range(1, 7):
            points = []
            for x in range(12):
                point = (x, y)
                points.append(point)
            self.cord_list.append(points)

    def init_grid(self):
        """Create map list with nest loop"""
        for points in self.cord_list:
            column_grid_list = []
            for point in points:
                grid = Map(point[0] * 80, point[1] * 80)
                column_grid_list.append(grid)
            self.grid_list.append(column_grid_list)

    def init_juggernut(self):
        i = random.randint(2, 5)
        juggernaut = Juggernaut(1500, i * 80, self, self.MainView)
        self.zombie_list.append(juggernaut)

    def init_zombies(self):
        """Spawn zombies"""
        for i in range(1, 7):
            distance = random.randint(1, 60) * 10
            normalzombie = Norzombie(1000 + distance, i * 80, self,
                                     self.MainView)
            buckethead = Buckethead(1000 + distance, i * 80, self,
                                    self.MainView)
            conehead = Conehead(1000 + distance, i * 80, self, self.MainView)
            screen = Screenzombie(1000 + distance, i * 80, self, self.MainView)
            newspaper = Newspaper(1000 + distance, i * 80, self, self.MainView)
            zombie_type = [
                normalzombie, buckethead, newspaper, conehead, screen
            ]
            self.zombie_list.append(random.choice(zombie_type))

###------- load game unit ------------------------------

    def load_plants(self):
        """Check plants live then check type, then take action. if it is dead, remove from plant list"""
        for plant in self.plants_list:
            if plant.live:
                if isinstance(plant, Sunflower):
                    plant.produce_money()
                elif isinstance(plant, PeaShooter):
                    plant.shot()
                elif isinstance(plant, SnowPea):
                    plant.shot()
                elif isinstance(plant, LycheeBomb):
                    plant.explode()
                elif isinstance(plant, Wallnut):
                    plant.crack()
                elif isinstance(plant, Chomper):
                    plant.eat()
            else:
                self.plants_list.remove(plant)

    def load_zombies(self):
        """Check zombie status, then take action, if it is dead, remove from zombies list"""
        for zombie in self.zombie_list:
            if zombie.live:
                if isinstance(zombie, Buckethead):
                    zombie.losehead()
                if isinstance(zombie, Newspaper):
                    zombie.losepaper()
                if isinstance(zombie, Conehead):
                    zombie.losecone()
                if isinstance(zombie, Screenzombie):
                    zombie.dropdoor()
                zombie.move_zombie()
                zombie.hit_plant()
            else:
                if isinstance(zombie, Juggernaut):
                    self.count_jug = 0
                    self.zombie_list.remove(zombie)
                else:
                    self.zombie_list.remove(zombie)

    def load_jug(self):
        for jug in self.jug_list:
            if jug.live:
                jug.move_zombie()
                jug.hit_plant()

    def load_bullets(self):
        """check bullet status, then take action. if it is dead, remove from bullet list."""
        for b in self.peabullet_list:
            if b.live:
                b.move_bullet()
                b.hit_zombie()
            else:
                self.peabullet_list.remove(b)

        for i in self.icebullet_list:
            if i.live:
                i.move_bullet()
                i.hit_zombie()
            else:
                self.icebullet_list.remove(i)

        for spike in self.lycheespike_list:
            if spike.live:
                spike.move_spike()
                spike.hit_zombie()
            else:
                self.lycheespike_list.remove(spike)

    def load_explosions(self):
        """ Checks explosion status and takes action. Since explosion is instant, it is removed quickly """
        for explosion in self.explosion_list:
            if explosion.live:
                explosion.hit_zombie()
            else:
                self.explosion_list.remove(explosion)

###------- Game menu setup -----------------------------

    def main_menu(self):
        """load game menu and track user actions on main menu"""
        self.MainView.display_menu()
        if not self.muted:
            self.background_sound.play(-1)
        waiting = True
        while waiting:
            for event in pygame.event.get():
                x, y = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if 89 < x < 287 and 267 < y < 362:
                        self.GAMEOVER = False
                        self.button_sound.play()
                        self.background_sound.stop()
                        self.load_game()
                    elif 306 < x < 447 and 314 < y < 401:  # scoreboard
                        self.button_sound.play()
                        webbrowser.open_new(
                            "https://acit-2911-agile-project-g2.herokuapp.com/scoreboard"
                        )
                    elif 539 < x < 583 and 385 < y < 428:
                        self.background_sound.stop()
                        self.muted = True
                    elif 117 < x < 287 and 372 < y < 443:
                        self.button_sound.play()
                        self.background_sound.stop()
                        self.hard_mode()
                    elif 492 < x < 532 and 434 < y < 477:
                        self.button_sound.play()
                        self.background_sound.stop()
                        self.help()
                    elif 647 < x < 758 and 373 < y < 409:
                        self.button_sound.play()
                        exit()
                    elif 595 < x < 646 and 431 < y < 481:
                        self.button_sound.play()
                        self.background_sound.stop()
                        self.aboutus()
                    elif 452 < x < 498 and 383 < y < 426:
                        self.muted = False
                        self.background_sound.play()
                elif event.type == pygame.QUIT:
                    pygame.quit()

    def hard_mode(self):
        """alow players change difficulty level of the game"""
        waiting = True
        while waiting:
            self.MainView.display_mode()
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = pygame.mouse.get_pos()
                    if 373 < x < 523 and 240 < y < 282:
                        self.button_sound.play()
                        self.difficulty = 0
                        self.MainView.display_mode()
                    elif 373 < x < 523 and 303 < y < 337:
                        self.button_sound.play()
                        self.difficulty = 1
                        self.MainView.display_mode()
                    elif 373 < x < 523 and 366 < y < 403:
                        self.button_sound.play()
                        self.difficulty = 2
                        self.MainView.display_mode()
                    elif 611 < x < 712 and 483 < y < 509:
                        self.button_sound.play()
                        self.main_menu()
                elif event.type == pygame.QUIT:
                    waiting = False
                    self.main_menu()

    def help(self):
        """show game instruction"""
        runing = True
        while runing:
            self.MainView.display_help()
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = pygame.mouse.get_pos()
                    if 531 < x < 687 and 491 < y < 521:
                        self.button_sound.play()
                        runing = False
                        self.main_menu()

    def aboutus(self):
        """show project team members in rolling credits"""
        x = self.MainView.window.get_rect().centerx + 60
        y = self.MainView.window.get_rect().centery
        startpos = y + 50
        running = True
        if not self.muted:
            self.credit_sound.play()
        while running:
            self.MainView.display_background()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    self.credit_sound.stop()
                    self.main_menu()
            startpos -= 2
            i = 0
            name_list = []
            position_list = []

            with open('./About_us.txt') as f:
                lines = f.read().splitlines()
            for content in lines:
                pygame.font.init()
                font = pygame.font.SysFont("comicsansms", 60)
                name = font.render(content, True, (250, 244, 237))
                name_list.append(name)
                position = name.get_rect(center=(x, y + startpos + 60 * i))
                position_list.append(position)
                i += 1

            for j in range(i):
                self.MainView.window.blit(name_list[j], position_list[j])
            pygame.display.update()

###------- Main game event -----------------------------

    def load_game(self):
        """load game interface, game start"""
        self.window = pygame.display.set_mode([1400, 560])
        self.setup()
        self.init_plant_points()
        self.init_grid()
        self.init_zombies()
        if self.difficulty == 2 and not self.muted:
            self.night_sound.play()
        elif self.difficulty == 1 and not self.muted:
            self.day_sound.play()
        elif self.difficulty == 0 and not self.muted:
            self.day_sound.play()
        pygame.display.flip()

        while not self.GAMEOVER:
            self.load_plants()
            self.load_bullets()
            self.load_explosions()
            self.events_handler()
            self.load_zombies()
            self.load_jug()
            self.count_zombie += 1

            if self.count_zombie == self.produce_zombie:
                self.init_zombies()
                self.count_zombie = 0
            if self.difficulty == 2 and self.level > 1 and self.level % 2 == 0 and self.count_jug != 1:
                self.init_juggernut()
                self.count_jug = 1

            self.MainView.display()
            self.MainView.display_update()
        self.endgame()

    def events_handler(self):
        """check user actions in game interface"""
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                self.GAMEOVER = True
                self.endgame()

            elif e.type == pygame.KEYDOWN:
                #trasnfer cordinate to position mark here,
                x, y = pygame.mouse.get_pos()
                if 255 < x < 960 and 60 < y < 580:
                    x = x // 80
                    y = y // 80
                    #locate which piece of map that plyer mouse clicks
                    grid = self.grid_list[y - 1][x]

                    if e.key == pygame.K_1:  #create sunflower
                        condition = grid.can_grow and self.money >= 50
                        if condition:
                            self.plant_sound.play()
                            sunflower = Sunflower(grid.position[0],
                                                  grid.position[1], self,
                                                  self.MainView)
                            self.plants_list.append(sunflower)
                            grid.can_grow = False
                            self.money -= 50

                    if e.key == pygame.K_2:  #create peashooter
                        condition = grid.can_grow and self.money >= 50
                        if condition:
                            self.plant_sound.play()
                            peashooter = PeaShooter(grid.position[0],
                                                    grid.position[1], self,
                                                    self.MainView)
                            self.plants_list.append(peashooter)
                            grid.can_grow = False
                            self.money -= 50

                    if e.key == pygame.K_3:  #create snowpea
                        condition = grid.can_grow and self.money >= 60
                        if condition:
                            self.plant_sound.play()
                            snowpea = SnowPea(grid.position[0],
                                              grid.position[1], self,
                                              self.MainView)
                            self.plants_list.append(snowpea)
                            grid.can_grow = False
                            self.money -= 60

                    if e.key == pygame.K_4:  #create walnut
                        condition = grid.can_grow and self.money >= 50
                        if condition:
                            self.plant_sound.play()
                            wallnut = Wallnut(grid.position[0],
                                              grid.position[1], self,
                                              self.MainView)
                            self.plants_list.append(wallnut)
                            grid.can_grow = False
                            self.money -= 50

                    if e.key == pygame.K_5:  #create Lychee Bomb
                        condition = grid.can_grow and self.money >= 150
                        if condition:
                            self.plant_sound.play()
                            lychee = LycheeBomb(grid.position[0],
                                                grid.position[1], self,
                                                self.MainView)
                            self.plants_list.append(lychee)
                            grid.can_grow = False
                            self.money -= 150

                    if e.key == pygame.K_6:  #create Lychee Bomb
                        condition = grid.can_grow and self.money >= 60
                        if condition:
                            self.plant_sound.play()
                            chomper = Chomper(grid.position[0],
                                              grid.position[1], self,
                                              self.MainView)
                            self.plants_list.append(chomper)
                            grid.can_grow = False
                            self.money -= 60

    def endgame(self):
        """show game over screen and track players actions"""
        self.GAMEOVER = True
        self.database.savescore()
        self.night_sound.stop()
        self.day_sound.stop()
        self.end_sound.play(0)
        waiting = True
        self.MainView.display_endscreen()
        while waiting:
            for event in pygame.event.get():
                x, y = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if 436 < x < 511 and 466 < y < 497:
                        self.button_sound.play()
                        waiting = False  # restart
                        self.GAMEOVER = False
                        self.load_game()
                    elif 285 < x < 386 and 466 < y < 497:
                        self.button_sound.play()
                        waiting = False
                        self.GAMEOVER = False
                        self.main_menu()  # main menu
                elif event.type == pygame.QUIT:
                    self.main_menu()
예제 #36
0
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import RoomView, UserView, LobbyView, MessageView, MainView

urlpatterns = patterns(
    '',
    url(r'^room/(?P<id>\d+)/$', RoomView.as_view()),
    url(r'^room/(?P<id>\d+)/(?P<page>\d+)/$', RoomView.as_view()),
    url(r'^user$', UserView.as_view()),
    url(r'^lobby$', LobbyView.as_view()),
    url(r'^main$', MainView.as_view()),
    url(r'^message$', MessageView.as_view()),
)
예제 #37
0
파일: urls.py 프로젝트: vistacan/django-rt
from django.conf.urls import patterns, include, url
from views import MainView
from django.views.decorators.csrf import ensure_csrf_cookie


urlpatterns = patterns(
    '',
    url(r'.*', ensure_csrf_cookie(MainView.as_view()), name='main'),
)
예제 #38
0
파일: urls.py 프로젝트: jzmiller1/lakedata
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainView

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^$', MainView.as_view(), name='main_page'),
)
예제 #39
0
	def __init__(self, port):
		self.model = MainModel.MainModel(port)
		self.view = view.View()
		self.mainView = MainView.MainView()
		self.port = port
		self.postsController = PostsController.PostsController(port)
예제 #40
0
from django.urls import path

from views import MainView
from views import product_sets_detail
from views import product_sets_list
from views import recipients_detail
from views import recipients_list

urlpatterns = [
    path('', MainView.as_view()),
    path('recipients/', recipients_list, name='recipients_list'),
    path('recipients/<int:pk>', recipients_detail, name='recipients_detail'),
    path('product-sets/', product_sets_list, name='product-sets_list'),
    path('product-sets/<int:pk>',
         product_sets_detail,
         name='product-sets_detail'),
]
예제 #41
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from restful import examiner_restful
from views import MainView, AssignmentGroupView

urlpatterns = patterns('devilry.apps.examiner',
                       url(r'^$', login_required(MainView.as_view()), name='examiner'),
                       url(r'^assignmentgroup/(?P<assignmentgroupid>\d+)$',
                           login_required(AssignmentGroupView.as_view()))
                      )

urlpatterns += examiner_restful
예제 #42
0
"""MySite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from views import MainView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', MainView.as_view(), name='index'),
    #url(r'^ece311/', include('ECE311.urls')),
    #url(r'^ece472/', include('ECE472.urls')),  
]
예제 #43
0
파일: urls.py 프로젝트: juslop/angular-chat
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import RoomView, UserView, LobbyView, MessageView, MainView

urlpatterns = patterns('',
    url(r'^room/(?P<id>\d+)/$', RoomView.as_view()),
    url(r'^room/(?P<id>\d+)/(?P<page>\d+)/$', RoomView.as_view()),
    url(r'^user$', UserView.as_view()),
    url(r'^lobby$', LobbyView.as_view()),
    url(r'^main$', MainView.as_view()),
    url(r'^message$', MessageView.as_view()),
)
예제 #44
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from restful import student_restful
from views import MainView, AddDeliveryView, FileUploadView, AssignmentGroupView

urlpatterns = patterns(
    "devilry.apps.student",
    url(r"^$", login_required(MainView.as_view()), name="student"),
    url(r"^add-delivery/(?P<deliveryid>\d+)$", login_required(AddDeliveryView.as_view()), name="add-delivery"),
    url(r"^add-delivery/fileupload/(?P<deadlineid>\d+)$", login_required(FileUploadView.as_view()), name="file-upload"),
    url(r"^assignmentgroup/(?P<assignmentgroupid>\d+)$", login_required(AssignmentGroupView.as_view())),
)

urlpatterns += student_restful
예제 #45
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from restful import student_restful
from views import (MainView, AddDeliveryView, 
                   FileUploadView, AssignmentGroupView,
                   FileDownloadView, ShowDeliveryView,
                   CompressedFileDownloadView, TarFileDownloadView)

urlpatterns = patterns('devilry.apps.student',
                       url(r'^$', login_required(MainView.as_view()), name='student'),
                       url(r'^add-delivery/(?P<assignmentgroupid>\d+)$', 
                           login_required(AddDeliveryView.as_view()), 
                           name='add-delivery'),
                       url(r'^add-delivery/fileupload/(?P<assignmentgroupid>\d+)$',
                           login_required(FileUploadView.as_view()),
                           name='file-upload-id'),
                       url(r'^add-delivery/fileupload/(?P<assignmentgroupid>\d+)$',
                           login_required(FileUploadView.as_view()),
                           name='file-upload'),
                       url(r'^assignmentgroup/(?P<assignmentgroupid>\d+)$',
                           login_required(AssignmentGroupView.as_view()),
                           name='student-show-assignmentgroup'),
                       url(r'^show-delivery/(?P<deliveryid>\d+)$',
                           login_required(ShowDeliveryView.as_view()),
                           name='show-delivery'),
                       url(r'^show-delivery/filedownload/(?P<filemetaid>\d+)$',
                           login_required(FileDownloadView.as_view()),
                           name='file-download'),
                       url(r'^show-delivery/compressedfiledownload/(?P<deliveryid>\d+)$',
                           login_required(CompressedFileDownloadView.as_view()),
예제 #46
0
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

#def create_app():
app = Flask(__name__)
app.config.from_object(config)
celery = make_celery(app)

# old API routes
# url(r"^ansible_jeneric/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<job_id>-.*-*.*)", 'destinyCelery.ansible_jeneric_view'),
# url(r"^ansible_playbook/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<playbook_id>-.*-*.*)", 'destinyCelery.ansible_playbook_view'),
# url(r"^ansible_playbook_manual/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<playbook_id>-.*-*.*)", 'destinyCelery.ansible_playbook_manual_view'),
# url(r"^rax_create_server/(?P<user_id>\d+)/(?P<project_id>-.*-*.*)/(?P<job_id>-.*-*.*)", 'destinyCelery.rax_create_server_view'),

app.add_url_rule('/', view_func=MainView.as_view('main_view'))

#app.add_url_rule('/api/v1/ansible_jeneric/<string:user_id>/<string:project_id>/<string:job_id>', view_func=task(AnsibleJeneric.as_view('ansible_jeneric1')))
app.add_url_rule('/api/v1/ansible_jeneric/<string:user_id>/<string:project_id>/<string:job_id>',
                 view_func=AnsibleJeneric.as_view('ansible_jeneric'))

app.add_url_rule('/api/v1/ansible_playbook/<string:user_id>/<string:project_id>/<string:playbook_id>',
                 view_func=AnsiblePlaybook.as_view('ansible_playbook'))

app.add_url_rule('/api/v1/ansible_playbook_manual/<string:user_id>/<string:project_id>/<string:playbook_id>',
                 view_func=AnsiblePlaybookManual.as_view('ansible_playbook_manual'))

app.add_url_rule('/api/v1/rax_create_server/<string:user_id>/<string:project_id>/<string:job_id>',
                 view_func=RaxCreateServer.as_view('rax_create_server'))
# api route for populating playbooks from git repo
app.add_url_rule('/api/v1/populate_playbooks/<string:user_id>/<string:project_id>/<string:playbook_id>',
예제 #47
0
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from restful import administrator_restful
from views import (MainView, RestfulSimplifiedView,
                   RestfulSimplifiedViewWithGradeEditors,
                   AdminCompressedFileDownloadView)

urlpatterns = patterns(
    'devilry.apps.administrator',
    url(r'^$', login_required(MainView.as_view()), name='administrator'),
    RestfulSimplifiedView.as_url('node', 'administrator/node.django.js'),
    RestfulSimplifiedView.as_url('subject', 'administrator/subject.django.js'),
    RestfulSimplifiedView.as_url('period', 'administrator/period.django.js'),
    RestfulSimplifiedViewWithGradeEditors.as_url(
        'assignment', 'administrator/assignment.django.js'),
    RestfulSimplifiedViewWithGradeEditors.as_url(
        'assignmentgroup', 'administrator/assignmentgroupview.django.js'),
    url(r'^assignment/compressedfiledownload/(?P<assignmentid>\d+)$',
        login_required(AdminCompressedFileDownloadView.as_view())))
urlpatterns += administrator_restful
예제 #48
0
def play_app() -> None:
    def start_game(questions):
        results = list(MainRouter().play_quiz(questions).values())
        answers = [question['answer'] for question in questions]

        response = MainView().evaluate_result((results, answers))

        print(f"RESULTS: {response['scores']}/{response['total']}")
        print(response['message'])

    play = MainRouter().play()['play']

    if not play:
        print("Exiting, no Play option selected.")
        return

    option = play[0].split(" - ")[0].strip()

    if "CATEGORY" == option:
        rows = MainView().category()
        cat = MainRouter().category(rows)['id']

        if not cat:
            print("No Category selected")
            return

        cat_id = cat[0].split(" - ")[0]
        quizzes = MainView().quiz()

        questions = [quiz for quiz in quizzes if quiz['cat_id'] == int(cat_id)]

        if not questions:
            print("Question is not selected.")
            return

        start_game(questions)

    elif "QUIZ" == option:
        rows = MainView().quiz()
        row_ids = MainRouter().quiz(rows)['id']

        if not row_ids:
            print("row selection ERROR")
            return

        quizzes = MainView().quiz()
        questions = [
            quizzes[int(row_id.split(' - ')[0].strip())] for row_id in row_ids
        ]

        if not questions:
            print("Question is not selected.")
            return

        start_game(questions)

    elif "RANDOM" == option:
        questions = MainView().random()

        if not questions:
            print("Question is not selected.")
            return

        start_game(questions)

    return
예제 #49
0
from django.conf.urls import url
from . import views
from views import MainView
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login/$',
        auth_views.login, {'template_name': 'main/login.html'},
        name='login'),
    url(r'^logout/$',
        auth_views.logout, {'template_name': 'main/login.html'},
        name='logout'),
    url(r'^$', MainView.as_view(),
        name='MainView'),  #Stud Main Page (Landing Page)
]
예제 #50
0
# -*- coding: utf-8 -*-
from django.conf.urls import patterns

from views import MainView


urlpatterns = patterns("", (r"^", MainView.as_view()))
예제 #51
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from base import Base
from controllers import MainController
from views import MainView

from settings import DB_CONNECTION_STRING

engine = create_engine(DB_CONNECTION_STRING)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

main_controller = MainController(session)
main_view = MainView(main_controller)

main_view.render()
예제 #52
0
파일: urls.py 프로젝트: laperlej/geec_web
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static

from views import MainView, DataView

urlpatterns = [
    url(r'^$', MainView.as_view(), name='main_table'),
    url(r'^data/$', DataView.as_view(), name='download_page'),
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)