Example #1
0
def main():
    # 初期化
    pygame.init()
    pygame.mixer.init()

    # 画面生成
    pygame.display.set_mode((w, h), 0, 32)
    screen = pygame.display.get_surface()
    pygame.display.set_caption('Dangomushi')

    title = None
    gs = None
    scene = SC_Title

    # ゲームループ
    while True:
        # タイトル
        if scene == SC_Title:
            if title == None:
                title = Title(screen)
            title.Update()
            title.Draw()
            if title.finished:
                scene = SC_GetStar
                title = None

        # 星集め
        elif scene == SC_GetStar:
            if gs == None:
                gs = GetStar(screen)
            gs.Update()
            gs.Draw()
            if gs.finished:
                scene = SC_Title
                gs = None
Example #2
0
class DetailFrame(QWidget):
    def __init__(self, parent):
        super(DetailFrame, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 20)

        self.title = Title('', 23)
        titleLayout = QHBoxLayout()
        titleLayout.setAlignment(Qt.AlignTop)
        titleLayout.addWidget(QLabel(' ' * 5))
        titleLayout.addWidget(self.title, 1)
        layout.addLayout(titleLayout, 0)

        detailLayout = QGridLayout()
        detailLayout.setColumnStretch(0, self.width() * 0.618)
        detailLayout.setColumnStretch(1, self.width() * (1 - 0.618))

        self.preview = Preview()
        self.info = Info()
        detailLayout.addWidget(self.preview, 0, 0)
        detailLayout.addWidget(self.info, 0, 1)

        layout.addLayout(detailLayout, 1)

    def setTitle(self, title):
        self.title.setText(title)
Example #3
0
class DetailFrame(QWidget):
        def __init__(self, parent):
                super(DetailFrame, self).__init__(parent)
                layout = QVBoxLayout(self)
                layout.setContentsMargins(20, 15, 20, 20)
                
                self.title = Title('', 23)
                titleLayout = QHBoxLayout()
                titleLayout.setAlignment(Qt.AlignTop)
                titleLayout.addWidget(QLabel(' ' * 5))
                titleLayout.addWidget(self.title, 1)
                layout.addLayout(titleLayout, 0)

                detailLayout = QGridLayout()
                detailLayout.setColumnStretch(0, self.width() * 0.618)
                detailLayout.setColumnStretch(1, self.width() * (1 - 0.618))

                self.preview = Preview()
                self.info = Info()
                detailLayout.addWidget(self.preview, 0, 0)
                detailLayout.addWidget(self.info, 0, 1)

                layout.addLayout(detailLayout, 1)

        def setTitle(self, title):
                self.title.setText(title)
Example #4
0
def screen_update(screen, my_settings, ship, bullets, aliens, stats,
                  play_button, sb, bg, pause_btn, end_title, support,
                  score_display):
    # 关于背景图片
    screen.fill(0)
    screen.blit(bg, (0, 0))
    pause_btn.draw_pause_btn()

    ship.draw_ship()

    for bullet in bullets.sprites():  #很多的在这个编组里的子弹需要被一个个打印出来
        if stats.game_bullet_active:
            bullet.draw_bullet_up()
        else:
            bullet.draw_bullet()

    aliens.draw(screen)  #将某一个编组绘制出来的函数
    sb.show_score()
    if not stats.game_active and not stats.game_paused:
        screen.fill(0)
        screen.blit(bg, (0, 0))
        play_button.draw_replay_button()  #函数写在最后可以把按钮绘制在最上层
        end_title.draw_title()
        score_display.draw_score_title()
        h_score = Title(str(stats.high_score), screen)
        h_score.draw_high_score()

    support.draw_support()

    pygame.display.flip()  #让绘制出来的函数可见
Example #5
0
    def __init__(self):
        pyxel.init(160, 120, caption="Kotonoha Run")
        pyxel.load(os.getcwd() + "/my_resource.pyxel")

        self.gama_state = GamaState.Title
        self.title = Title()
        self.gama_main = GamaMain()
        self.gama_result = GamaResult()

        pyxel.run(self.Update, self.Draw)
Example #6
0
    def __init__(self, game, gameView):
        super(GameWindow, self).__init__()

        stretchA = (1000 - 618) * (1000 - 618)
        stretchB = 1000000 - stretchA

        layout = QGridLayout(self)
        layout.setColumnStretch(0, stretchB)
        layout.setColumnStretch(1, stretchA)

        leftLayout = QGridLayout()
        leftLayout.setRowStretch(0, stretchB)
        leftLayout.setRowStretch(1, stretchA)
        rightLayout = QGridLayout()
        rightLayout.setRowStretch(0, stretchA)
        rightLayout.setRowStretch(1, stretchB)
        layout.addLayout(leftLayout, 0, 0)
        layout.addLayout(rightLayout, 0, 1)

        self.game = game
        self.game.playersUpdated.connect(self._onPlayersUpdated)

        gameView.player = game.connectionManager.player
        gameView.attackInitiated.connect(self.game._onAttackInitiated)

        self.gameView = GameViewWrapper(gameView)
        self.eventBox = EventBox()
        self.countryBox = CountryInfoBox(self)
        self.statBox = StatBox(gameView)

        self.lose = Title('YOU LOSE', 100)
        self.win = Title('YOU WIN', 100)
        self.lose.setParent(self)
        self.win.setParent(self)
        self.lose.raise_()
        self.win.raise_()
        self.lose.hide()
        self.win.hide()

        self.eventBox.setColor(QColor(Qt.black))
        self.countryBox.setColor(QColor(Qt.gray))
        self.statBox.setColor(QColor(Qt.gray))

        leftLayout.addWidget(self.gameView, 0, 0)
        leftLayout.addWidget(self.eventBox, 1, 0)
        rightLayout.addWidget(self.statBox, 0, 0)
        rightLayout.addWidget(self.countryBox, 1, 0)

        gameView.hoverCountry.connect(self.countryBox.updateCountry)
        gameView.ownerChanged.connect(self.statBox.refresh)

        game.gameEvent.connect(self.eventBox.addEvent)
        game.gameLose.connect(self._triggerLose)
        game.gameWin.connect(self._triggerWin)
Example #7
0
        def __init__(self, game, gameView):
                super(GameWindow, self).__init__()

                stretchA = (1000 - 618) * (1000 - 618)
                stretchB = 1000000 - stretchA

                layout = QGridLayout(self)
                layout.setColumnStretch(0, stretchB)
                layout.setColumnStretch(1, stretchA)

                leftLayout = QGridLayout()
                leftLayout.setRowStretch(0, stretchB)
                leftLayout.setRowStretch(1, stretchA)
                rightLayout = QGridLayout()
                rightLayout.setRowStretch(0, stretchA)
                rightLayout.setRowStretch(1, stretchB)
                layout.addLayout(leftLayout, 0, 0)
                layout.addLayout(rightLayout, 0, 1)

                self.game = game
                self.game.playersUpdated.connect(self._onPlayersUpdated)

                gameView.player = game.connectionManager.player
                gameView.attackInitiated.connect(self.game._onAttackInitiated)

                self.gameView = GameViewWrapper(gameView)
                self.eventBox = EventBox()
                self.countryBox = CountryInfoBox(self)
                self.statBox = StatBox(gameView)

                self.lose = Title('YOU LOSE', 100)
                self.win = Title('YOU WIN', 100)
                self.lose.setParent(self)
                self.win.setParent(self)
                self.lose.raise_()
                self.win.raise_()
                self.lose.hide()
                self.win.hide()

                self.eventBox.setColor(QColor(Qt.black))
                self.countryBox.setColor(QColor(Qt.gray))
                self.statBox.setColor(QColor(Qt.gray))

                leftLayout.addWidget(self.gameView, 0, 0)
                leftLayout.addWidget(self.eventBox, 1, 0)
                rightLayout.addWidget(self.statBox, 0, 0)
                rightLayout.addWidget(self.countryBox, 1, 0)

                gameView.hoverCountry.connect(self.countryBox.updateCountry)
                gameView.ownerChanged.connect(self.statBox.refresh)

                game.gameEvent.connect(self.eventBox.addEvent)
                game.gameLose.connect(self._triggerLose)
                game.gameWin.connect(self._triggerWin)
Example #8
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setFixedSize(MainWindow.WIDTH, MainWindow.HEIGHT)

        self.mainTitle = Title('Distributed Real-time Risk', 36)
        self.subTitle = Title(' ' * 36 + 'Team 23', 20)

        layout = QGridLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        assert LeftPanel.OFFSET_Y == MainFrame.OFFSET_Y
        assert LeftPanel.HEIGHT == MainFrame.HEIGHT
        assert LeftPanel.OFFSET_Y + LeftPanel.HEIGHT == BottomPanel.OFFSET_Y
        assert BottomPanel.OFFSET_Y + BottomPanel.HEIGHT == MainWindow.HEIGHT
        layout.setRowStretch(0, LeftPanel.OFFSET_Y)
        layout.setRowStretch(1, LeftPanel.HEIGHT)
        layout.setRowStretch(2, BottomPanel.HEIGHT)

        assert LeftPanel.WIDTH + MainFrame.WIDTH == MainWindow.WIDTH
        layout.setColumnStretch(0, LeftPanel.WIDTH)
        layout.setColumnStretch(1, MainFrame.WIDTH)

        self.leftPanel = LeftPanel()
        self.bottomPanel = BottomPanel()
        self.mainFrame = MainFrame()
        layout.addWidget(self.leftPanel, 1, 0)
        layout.addWidget(self.bottomPanel, 2, 0, 1, -1)
        layout.addWidget(self.mainFrame, 1, 1)

        self.bottomPanel.gameHallControl.backButtonClicked.connect(
            self._onBackButtonClicked)
        self.bottomPanel.gameHallControl.createButtonClicked.connect(
            self._onCreateButtonClicked)
        self.bottomPanel.gameHallControl.joinButtonClicked.connect(
            self._onJoinButtonClicked)
        self.bottomPanel.gameRoomControl.backButtonClicked.connect(
            self._onBackButtonClicked)
        self.bottomPanel.gameRoomControl.startButtonClicked.connect(
            self._onStartButtonClicked)
        self.leftPanel.gameHallPanel.mapList.mapSelected.connect(
            self._onMapSelected)
        self.leftPanel.gameHallPanel.gameList.gameSelected.connect(
            self._onGameSelected)

        self.selectedMap = None
        self.selectedGameLoader = None
        self.selectedGame = None

        self.state = MainWindow.STATE_NONE
        self.initialAnimationStarted = False
        QMetaObject.invokeMethod(self, '_startAnimation', Qt.QueuedConnection)
Example #9
0
def main():
    pygame.init()
    display.init()
    controller = Controller()
    scene = Title()
    while True:
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        if not controller.poll():
            if hasattr(scene, 'server'):
                print 'shutdown'
                scene.server.shutdown()
            return
        scene.draw()
        pygame.display.flip()
        scene = scene.action(controller)
Example #10
0
    def __init__(self, parent):
        super(IntroFrame, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 20)

        self.title = Title('', 23)
        titleLayout = QHBoxLayout()
        titleLayout.setAlignment(Qt.AlignTop)
        titleLayout.addWidget(QLabel(' ' * 5))
        titleLayout.addWidget(self.title, 1)
        layout.addLayout(titleLayout, 0)

        self.loading = Loading(200)
        self.loading.hide()
        layout.addWidget(self.loading, 1, Qt.AlignCenter)
Example #11
0
 def get_titles(self, **kwargs) -> List[Title]:
   """
   Get data for multiple titles by searching by partial title and/or director matches.
   """
   results = []
   query_addon = []
   query_params = []
   for key, val in kwargs.items():
     if val:
       query_addon.append(f"{key} LIKE ?")
       query_params += ['%'+val+'%']
   if query_addon:
     query_addon = " WHERE " + " AND ".join(query_addon)
   else:
     query_addon = ""
   db_conn = sqlite3.connect(self.db_file)
   with db_conn:
     cur = db_conn.cursor()
     query = cur.execute("SELECT * FROM titles" + query_addon, query_params)
     colnames = [des[0] for des in query.description]
     for row in cur.fetchall():
       title = {}
       for i in range(len(colnames)):
         title[colnames[i]] = row[i] or ""
       try:
         results.append(Title(**title))
       except ValidationError as ve:
         self.logger.error(ve.errors())
   return results
Example #12
0
    def game_over(self):
        """Go to intermediate screen then return to title
        """

        title_screen = Title(self)
        info_screen = InfoScreen(self, self.score, '', title_screen)
        self.change_state(info_screen)
Example #13
0
class IntroFrame(QWidget):
        def __init__(self, parent):
                super(IntroFrame, self).__init__(parent)
                layout = QVBoxLayout(self)
                layout.setContentsMargins(20, 15, 20, 20)
                
                self.title = Title('', 23)
                titleLayout = QHBoxLayout()
                titleLayout.setAlignment(Qt.AlignTop)
                titleLayout.addWidget(QLabel(' ' * 5))
                titleLayout.addWidget(self.title, 1)
                layout.addLayout(titleLayout, 0)

                self.loading = Loading(200)
                self.loading.hide()
                layout.addWidget(self.loading, 1, Qt.AlignCenter)

        def setTitle(self, title):
                self.title.setText(title)
Example #14
0
class App:
    def __init__(self):
        pyxel.init(160, 120, caption="Kotonoha Run")
        pyxel.load(os.getcwd() + "/my_resource.pyxel")

        self.gama_state = GamaState.Title
        self.title = Title()
        self.gama_main = GamaMain()
        self.gama_result = GamaResult()

        pyxel.run(self.Update, self.Draw)

    def Update(self):
        prev_gama_state = self.gama_state
        if self.gama_state == GamaState.Title:
            self.gama_state = self.title.Update()
        elif self.gama_state == GamaState.GamaMain:
            self.gama_state = self.gama_main.Update()
        elif self.gama_state == GamaState.GamaResult:
            self.gama_state = self.gama_result.Update()
        elif self.gama_state == GamaState.Exit:
            pyxel.quit()
        else:
            raise Exception("updateで存在しないGamaStateが選択されました。")

        if prev_gama_state != self.gama_state:
            if self.gama_state == GamaState.GamaMain:
                self.gama_main = GamaMain()
            if self.gama_state == GamaState.GamaResult:
                self.gama_result.SetResutl(self.gama_main)

    def Draw(self):
        pyxel.cls(0)
        if self.gama_state == GamaState.Title:
            self.title.Draw()
        elif self.gama_state == GamaState.GamaMain:
            self.gama_main.Draw()
        elif self.gama_state == GamaState.GamaResult:
            self.gama_result.Draw()
        elif self.gama_state == GamaState.Exit:
            pass
        else:
            raise Exception("drowで存在しないGamaStateが選択されました。")
Example #15
0
class GameViewFrame(QWidget):
    def __init__(self, parent):
        super(GameViewFrame, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 15, 20, 20)

        self.title = Title('', 23)
        titleLayout = QHBoxLayout()
        titleLayout.setAlignment(Qt.AlignTop)
        titleLayout.addWidget(QLabel(' ' * 5))
        titleLayout.addWidget(self.title, 1)
        layout.addLayout(titleLayout, 0)

        self.loading = Loading(200)
        self.loading.hide()
        layout.addWidget(self.loading, 1, Qt.AlignCenter)

        self.countDown = CountDown(200, self)
        self.countDown.hide()

        self.gameView = None

    def setTitle(self, title):
        self.title.setText(title)

    def showLoading(self):
        if self.gameView is not None:
            self.gameView.hide()
        self.loading.show()

    def showCountDown(self, quick=False):
        center = self.gameView.pos() + QPoint(self.gameView.width() / 2,
                                              self.gameView.height() / 2)
        self.countDown.move(center - QPoint(self.countDown.width() / 2,
                                            self.countDown.height() / 2))
        self.countDown.show()
        self.countDown.raise_()
        self.countDown.start(5 if not quick else 0)

    def showGameView(self, gameMap):
        self.loading.hide()
        self.gameView = GameView(gameMap)
        self.layout().addWidget(self.gameView, 1, Qt.AlignCenter)
Example #16
0
    def __init__(self, textSource):
        self.textSource = textSource
        self.speedLimit = 70
        self.clock = pygame.time.Clock()
        self.screenRect = Rect(0, 0, 640, 480)
        self.screen = pygame.display.set_mode(self.screenRect.size)
        self.background = pygame.Surface(self.screenRect.size).convert()
        self.elements = pygame.sprite.RenderUpdates()
        self.inputData = InputData(textSource)
        self.music = RunMusic()
        self.title = Title()
        self.game_over = True
        self.elements.add(self.title)
        self.background.fill((255, 255, 255))
        self.screen.blit(self.background, (0, 0))

        self.coverText = self.inputData.getWelcomeWords()
        pygame.display.set_caption('王者打字游戏')
        pygame.display.update()
Example #17
0
class GameViewFrame(QWidget):
        def __init__(self, parent):
                super(GameViewFrame, self).__init__(parent)
                layout = QVBoxLayout(self)
                layout.setContentsMargins(20, 15, 20, 20)
                
                self.title = Title('', 23)
                titleLayout = QHBoxLayout()
                titleLayout.setAlignment(Qt.AlignTop)
                titleLayout.addWidget(QLabel(' ' * 5))
                titleLayout.addWidget(self.title, 1)
                layout.addLayout(titleLayout, 0)

                self.loading = Loading(200)
                self.loading.hide()
                layout.addWidget(self.loading, 1, Qt.AlignCenter)

                self.countDown = CountDown(200, self)
                self.countDown.hide()

                self.gameView = None

        def setTitle(self, title):
                self.title.setText(title)


        def showLoading(self):
                if self.gameView is not None:
                        self.gameView.hide()
                self.loading.show()

        def showCountDown(self, quick = False):
                center = self.gameView.pos() + QPoint(self.gameView.width() / 2, self.gameView.height() / 2)
                self.countDown.move(center - QPoint(self.countDown.width() / 2, self.countDown.height() / 2))
                self.countDown.show()
                self.countDown.raise_()
                self.countDown.start(5 if not quick else 0)

        def showGameView(self, gameMap):
                self.loading.hide()
                self.gameView = GameView(gameMap)
                self.layout().addWidget(self.gameView, 1, Qt.AlignCenter)
Example #18
0
    def make_first_city(self, models):
        self.active = True
        r = lambda: random.randint(0, 255)
        self.color = '#%02X%02X%02X' % (r(), r(), r())
        new_culture = False
        self.food_limit = 750
        if self.culture == None:
            self.culture = Culture(self.color)
            new_culture = True
        self.name = self.culture.generate_name(models, "t")
        while len(self.name) < 6 or len(
                self.name
        ) > 10 or ' ' in self.name or '-' in self.name or ')' in self.name:
            self.name = self.culture.generate_name(models, "t")
        if new_culture:
            self.culture.name = self.name + "ian"
        self.leader = Character(models, self.culture, self, 40)
        ### CREATE TITLE
        self.title = Title(self.name, None, [], [self], 1)
        self.title.setGovFormGameStart(self.leader.focus)
        self.leader.titles.append(self.title)
        self.leader.refresh_fullname()
        self.chars.append(self.leader)
        for f in self.field.field_neighbor(10):
            if f.city is not None:
                if f.city.culture == None:
                    f.city.culture = self.culture
        for f in self.field.field_neighbor(1):
            if f.owner is not None:
                if not f.owner.active:
                    f.owner = self
                    self.territory.append(f)
            else:
                f.owner = self
                self.territory.append(f)

        self.calculate_values()
        self.detect_resources()
        self.pop = self.wealth * 10 + random.randint(-100, 100)
        self.wpc = self.wealth / self.pop
Example #19
0
 def __init__(self):
     State.__init__(self)
     self.next_state = Title()
     self.screen.fill((125, 125, 125))
     self.timer = timer.Timer(2)
     self.image = image_handling.get_image('img/splashscreen/splash.png')
     self.alpha = 0
     self.image.set_alpha(0)
     self.image = pygame.transform.scale(self.image, self.screen.get_size())
     self.img_pos = image_handling.center(self.image.get_size(),
                                          self.screen.get_size())
     self.fade = False
     self.upscreen = True
Example #20
0
def main():
    determineOS()
    if glob.platform == Platform.UNDEFINED:
        print "Your operating system is not supported.\n"
        return -1

    glob.orig_shell_x, glob.orig_shell_y = term_size.getTerminalSize()

    #atexit.register(clean_screen)

    resizeTerminal(True)

    initCurses()

    #Run the title screen
    title_screen = Title()

    #Get world parameters
    #Breaks when world is smaller than screen (min size: 34x34)
    world_size = title_screen.getWorldSize()
    if world_size == "Small":
        glob.N_HEX_ROWS = 34
        glob.N_HEX_COLS = 34
    elif world_size == "Average":
        glob.N_HEX_ROWS = 50
        glob.N_HEX_COLS = 50
    elif world_size == "Large":
        glob.N_HEX_ROWS = 120
        glob.N_HEX_COLS = 100
    else:
        print "Error getting world size."
        sys.exit()

    #Run the game.
    Game()

    #Close unicurses
    uc.endwin()
Example #21
0
def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    # start_game = False
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Super Pong 64")

    start_game = False

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats, "")
    title = Title(ai_settings, screen, "")

    # make the left paddle
    left_paddle = Left_Paddle(ai_settings, screen)
    right_paddle = Right_Paddle(ai_settings, screen)
    bottom_paddle = Bottom_Paddle(ai_settings, screen)
    top_paddle = Top_Paddle(ai_settings, screen)
    top_left = Top_Left(ai_settings, screen)
    center_line = Center_Line(ai_settings, screen)
    bottom_right = Bottom_Right(ai_settings, screen)
    balls = Group()

    play_button = Button(ai_settings, screen, "Play")

    # Start the main loop for the game
    while True:
        title.prep_title("")
        title.prep_rules("")
        gf.check_events(ai_settings, screen, stats, sb, play_button,
                        left_paddle, top_left, bottom_paddle, balls)

        if stats.game_active:

            left_paddle.update(ai_settings)
            right_paddle.update(ai_settings, balls)
            bottom_paddle.update(ai_settings)
            top_paddle.update(ai_settings, balls)
            bottom_right.update(ai_settings, balls)
            top_left.update(ai_settings)

            gf.update_balls(ai_settings, stats, screen, sb, left_paddle,
                            right_paddle, bottom_paddle, top_paddle, top_left,
                            bottom_right, balls)

            gf.update_top_paddle(ai_settings, top_paddle)
            gf.update_bottom_right(ai_settings, bottom_right)
            gf.update_right_paddle(ai_settings, right_paddle)

        gf.update_screen(ai_settings, screen, stats, sb, title, left_paddle,
                         right_paddle, bottom_paddle, center_line, top_paddle,
                         top_left, bottom_right, balls, play_button)
Example #22
0
 def __init__(self):
     self.img = None
     self.legend = Legend()
     self.title = Title()
     self.autosize = App.cfg['image']['autosize']
     self.autosize_minpx = App.cfg['image']['autosize_minpx']
     self.basewidth = App.cfg['image']['basewidth']
     self.baseheight = App.cfg['image']['baseheight']
     self.padding = App.cfg['image']['padding']
     self.showborder = App.cfg['image']['border']
     self.showtitle = App.cfg['title']['show']
     self.showlegend = App.cfg['legend']['show']
     self.showgrid = App.cfg['axis']['grid']
     self.showaxis = App.cfg['axis']['show']
     self.showflat = App.cfg['image']['flatline']
     self.showtimestamp = App.cfg['image']['timestamp']
     self.timestampcolor = App.cfg['image']['timestampcolor']
     self.bordercolor = App.cfg['image']['bordercolor']
     self.streetcolor = App.cfg['image']['streetcolor']
     self.flatcolor = App.cfg['image']['flatcolor']
     self.gridcolor = App.cfg['axis']['gridcolor']
     self.axiscolor = App.cfg['axis']['color']
     self.axisfont = App.cfg['axis']['font']
     self.bgcolor = App.cfg['image']['bgcolor']
def run_game():
    #Initialize pygame, settings, and screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    pygame.mixer.music.load('sounds/background.mp3')
    pygame.mixer.music.play(-1)

    #Make the play button
    play_button = Button(ai_settings, screen, "Play Game")
    hs_button = Button2(ai_settings, screen, "High Scores")
    title = Title(ai_settings, screen)
    title2 = Title2(ai_settings, screen)

    #Create an instance to store game stats and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #Make a ship, a group of bullets, a group of bunkers, and a group of aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    abullets = Group()
    aliens = Group()
    bunkers = Group()

    #Create the fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #Create the bunkers
    gf.create_bunker_rows(ai_settings, screen, bunkers)

    #Start the main loop for the game
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, hs_button,
                        ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, bunkers)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, hs_button, title, title2, bunkers)
Example #24
0
    def __init__(self):
        self.system = platform.system()

        pygame.init()
        pygame.display.set_caption('Flappy Bird')

        self.FPS = 55

        self.SCREEN_WIDTH = 1000
        self.SCREEN_HEIGHT = 563
        self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))

        self.sliding_background = SlidingBackground(self.screen)

        if self.system == 'Linux':
            self.flappy_bird_title = Title(self.screen, r'images/title2.0.png', 466, 137, 50)
        else:
            self.flappy_bird_title = Title(self.screen, r'images\title2.0.png', 466, 137, 50)

        if self.system == 'Linux':
            self.game_over_title = Title(self.screen, r'images/game_over2.0.png', 383, 90, 50)
        else:
            self.game_over_title = Title(self.screen, r'images\game_over2.0.png', 383, 90, 50)

        if self.system == 'Linux':
            self.start_image_button = ImageButton(self.screen, r'images/start_button3.0.png', 183, 109, 400)
        else:
            self.start_image_button = ImageButton(self.screen, r'images\start_button3.0.png', 183, 109, 400)

        self.scoreboard = ScoreBoard(self.screen)

        self.retry_button = Button(self.screen, 425, 'Retry')

        self.bird = Bird(self.screen)

        # True until reset in pressed
        self.game_active = False

        # True until obstacle was hit
        self.game_lost = False

        self.score = 0
        self.create_best_score_file()
        self.get_best_score()
Example #25
0
def _generate_title_morphs(path, title_name):
    title = Title(title_name)

    if os.path.isfile(path):
        title.find_morphs_from_file(path)
    else:
        for filename in os.listdir(path):
            if os.path.isfile(os.path.join(path, filename)):
                title.find_morphs_from_file(os.path.join(path, filename))

    return title
Example #26
0
def init():
    global titles

    loaded_titles = None

    try:
        try:
            with open(file_name, 'rb') as f:
                loaded_titles = pickle.load(f)
        except FileNotFoundError:
            open(file_name, 'wb+')
        if loaded_titles is not None:
            print("Loaded from cache")
            titles = loaded_titles
            return
    except ValueError:
        print("Cannot read json")

    print("Start generating:", strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    print("Fetching popular started...:",
          strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    imdb_manager.fetch_popular_titles()
    print("Fetching popular ended...:",
          strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
    popular_titles = imdb_manager.title_id_list

    total_images_count = 0
    movies_count = 0

    for title in popular_titles:
        images_list = get_canonical_images(
            imdb.get_title_images(title.title_id))
        total_images_count += len(images_list)
        movies_count += 1
        if len(images_list) > 0:
            titles.append(Title(title.name, title.year, images_list))

    with open(file_name, 'wb') as f:
        pickle.dump(titles, f, pickle.HIGHEST_PROTOCOL)

    print("Movies with images:", str(len(titles)))
    print("Total images:", str(total_images_count))
    print("End generating:", strftime("%a, %d %b %Y %H:%M:%S", gmtime()))
Example #27
0
 def get_title(self, id: str) -> Title:
   """
   Get title data by id, which is matched to id in the titles table
   """
   db_conn = sqlite3.connect(self.db_file)
   with db_conn:
     cursor = db_conn.cursor()
     query = cursor.execute("SELECT * FROM titles WHERE id = ?", [id])
     colnames = [des[0] for des in query.description]
     result = cursor.fetchone()
     if not result:
       return None
     title = {}
     for i in range(len(colnames)):
       title[colnames[i]] = result[i] or ""
   try:
     return Title(**title)
   except ValidationError as ve:
     self.logger.error(ve.errors())
Example #28
0
        def __init__(self, parent):
                super(GameViewFrame, self).__init__(parent)
                layout = QVBoxLayout(self)
                layout.setContentsMargins(20, 15, 20, 20)
                
                self.title = Title('', 23)
                titleLayout = QHBoxLayout()
                titleLayout.setAlignment(Qt.AlignTop)
                titleLayout.addWidget(QLabel(' ' * 5))
                titleLayout.addWidget(self.title, 1)
                layout.addLayout(titleLayout, 0)

                self.loading = Loading(200)
                self.loading.hide()
                layout.addWidget(self.loading, 1, Qt.AlignCenter)

                self.countDown = CountDown(200, self)
                self.countDown.hide()

                self.gameView = None
Example #29
0
def run_game():
    #Initialize the game and create a screen object
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption('Letters Killer')

    #Intialize the statistics
    stats = Stats(game_settings)

    #Initialize all the sounds in need
    sounds = Sound(game_settings)

    #Initialize the falling targets
    targets = Group()

    #Initialize an aim
    aim = Aim(screen, game_settings)

    #Initialize a button
    button = Button(screen, game_settings)

    #Initialize the title
    title = Title(screen, game_settings)

    #Initialize the big man
    man = Man(screen, game_settings)
    while True:

        #Create a target with random value
        gf.create_targets(screen, game_settings, targets)

        #Check the events and responds
        gf.check_events(targets, game_settings, stats, button, aim, sounds,
                        title)

        #Update the screen
        gf.update_screen(screen, game_settings, stats, button, targets, aim,
                         title)
Example #30
0
    def search_title_data(self, data):
        """
        Sort of a sub-method of add_title
        Scrapes pre-chosen websites for info about a title with
        the given details (name, year, type)
        :param data: (Title's name, Title's year, Title's Type)
                      Name: Name of the title
                      Year: Release year of the title (minimum search year)
                      Type: Type of the title

        Success:
            :returns: A title with all the data scraped online
            :rtype: Title
        Failure:
            :returns: Error message (Reason for failure)
            :rtype: str
        """
        data = Database.injection_arr(data)
        print("Adding title\n\tName: {}\n\tYear: {}\n\tType: {}".format(*data))
        data[0] = data[0].lower()
        title_type = data[2]
        titles = dict(
            self.cursor.execute("""SELECT name,
        date FROM {}""".format(TYPE_TO_TABLE[title_type])))
        for title, year in titles.items():
            if data[0] == title.lower() and data[1] == year.split("-")[0]:
                return "Exists"
        title = Title(*data)
        if title.error_flag:
            return "Error"
        links = list(
            self.cursor.execute("""SELECT
        imdb FROM {}""".format(TYPE_TO_TABLE[title_type])))
        links = [link[0] for link in links]  # That's just how it gets stuff
        print("LINKS:", repr(links))
        print("IMDB:", repr(title.imdb_page))
        if title.imdb_page in links:
            return "Exists"
        return title
Example #31
0
    def fetch_popular_titles(cls):
        while cls.start_page < cls.max_pages_count:
            print("\n\npage =", cls.start_page)
            print("offset =", cls.offset)
            url = cls.update_url()

            http = urllib3.PoolManager()
            r = http.request('GET', url, headers=cls._headers)

            soup = BeautifulSoup(r.data, 'html.parser')
            results_table = soup.find('table', {'class': 'results'})
            tr_list = results_table.find_all('tr')
            tr_list.pop(0)
            cls.offset += cls._offset_increment_step
            cls.start_page += cls._page_increment_step
            for tr in tr_list:
                title_id = tr.find('span').attrs['data-tconst']
                title_year = tr.find('span', {
                    'class': 'year_type'
                }).text.replace('(', '').replace(')', '')
                title_name = tr.find_all('a')[1].text
                cls.title_id_list.append(
                    Title(title_id=title_id, name=title_name, year=title_year))
Example #32
0
 def __init__(self):
     GameManager.__init__(self, Title(self))
Example #33
0
class FlappyBird:

    def __init__(self):
        self.system = platform.system()

        pygame.init()
        pygame.display.set_caption('Flappy Bird')

        self.FPS = 55

        self.SCREEN_WIDTH = 1000
        self.SCREEN_HEIGHT = 563
        self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))

        self.sliding_background = SlidingBackground(self.screen)

        if self.system == 'Linux':
            self.flappy_bird_title = Title(self.screen, r'images/title2.0.png', 466, 137, 50)
        else:
            self.flappy_bird_title = Title(self.screen, r'images\title2.0.png', 466, 137, 50)

        if self.system == 'Linux':
            self.game_over_title = Title(self.screen, r'images/game_over2.0.png', 383, 90, 50)
        else:
            self.game_over_title = Title(self.screen, r'images\game_over2.0.png', 383, 90, 50)

        if self.system == 'Linux':
            self.start_image_button = ImageButton(self.screen, r'images/start_button3.0.png', 183, 109, 400)
        else:
            self.start_image_button = ImageButton(self.screen, r'images\start_button3.0.png', 183, 109, 400)

        self.scoreboard = ScoreBoard(self.screen)

        self.retry_button = Button(self.screen, 425, 'Retry')

        self.bird = Bird(self.screen)

        # True until reset in pressed
        self.game_active = False

        # True until obstacle was hit
        self.game_lost = False

        self.score = 0
        self.create_best_score_file()
        self.get_best_score()


    def create_best_score_file(self):
        fd = open('best_score.txt', 'a')
        fd.close()

    def get_best_score(self):
        with open('best_score.txt', 'r') as fd:
            self.best_score = fd.readline()

        if not self.best_score:
            self.best_score = 0
            with open('best_score.txt', 'w') as fd:
                fd.write('0')

        self.best_score = int(self.best_score)

    def replace_best_score(self, score):
        if score > self.best_score:
            self.best_score = score
            with open('best_score.txt', 'w') as fd:
                fd.write(str(self.best_score))


    def mouse_over(self, rect):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if rect.collidepoint(mouse_x, mouse_y):
            return True
        return False

    def get_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT:
                if self.game_active == False:
                    if self.mouse_over(self.start_image_button.rect):
                        self.bird.jump()
                        self.game_active = True
                        self.sliding_background.__init__(self.screen)
                else:
                    if self.game_lost == False:
                        self.bird.jump()
                    elif self.mouse_over(self.retry_button.button_rect):
                        self.game_active = False
                        self.game_lost = False
                        self.bird.__init__(self.screen)
                        self.score = 0


        if self.game_active == True and self.bird.killed(self.sliding_background):
            self.game_lost = True
            self.sliding_background.pipes.empty()

            self.score = self.bird.get_score()
            self.replace_best_score(self.score)


    def update_screen(self):
        self.sliding_background.show(self.game_lost, self.game_active)

        if self.game_active == False and self.game_lost == False:
            self.start_image_button.show()
            self.flappy_bird_title.show()
            self.bird.pendle()

        elif self.game_active == True and self.game_lost == False:
            self.bird.update_bird_position()

        else: # obstacle was hit
            self.game_over_title.show()
            self.scoreboard.show(self.score, self.best_score)
            self.retry_button.show()

        if not(self.game_active == True and self.game_lost == True):
            self.bird.show_bird()

        pygame.display.update()

    def start(self):

        self.clock = pygame.time.Clock()

        while True:
            self.clock.tick(self.FPS)
            self.get_events()
            self.update_screen()
Example #34
0
 def titles(self):
     from title import Title
     return Title.objects(holder=self)
Example #35
0
def run_game():
    #初始化
    pygame.init()

    #设置类的对象
    my_settings = Setting()
    screen = pygame.display.set_mode(
        (my_settings.screen_width, my_settings.screen_height))
    pygame.display.set_caption("the first of my game")

    #对象的创建

    play_button = Button('play', screen)  #按钮
    pause_btn = PauseBtn(screen)

    ship = Ship(my_settings, screen)
    aliens = Group()
    bullets = Group()
    stats = GameStats(my_settings)
    sb = ScoreBoard(screen, my_settings, stats)
    bg = pygame.image.load("./image/back4.png")
    sp = StartPage(screen)
    start_bg = pygame.image.load("./image/back4.png")
    title = Title("Maybe Our Game", screen)
    end_title = Title("HAAAAAAA YOU LOSE", screen)
    score_display = Title("YOUR SCORE:", screen)
    support = Support(screen, my_settings)

    # bgm 的创建
    pygame.mixer.init()
    bg_sound = pygame.mixer.Sound('./music/开头.mp3')
    bg_sound.play()

    gf.create_fleet(screen, my_settings, aliens, ship)

    SUPPLY_TIME = pygame.USEREVENT
    pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)

    while True:
        if stats.game_first_page:
            gf.check_events(ship, my_settings, screen, bullets, stats,
                            play_button, aliens, sb, bg_sound, pause_btn, sp,
                            SUPPLY_TIME, support)
            gf.first_page_show(screen, sp, start_bg, title)
        else:
            gf.check_events(ship, my_settings, screen, bullets, stats,
                            play_button, aliens, sb, bg_sound, pause_btn, sp,
                            SUPPLY_TIME, support)
            if stats.game_active and not stats.game_paused:
                ship.update()
                gf.update_aliens(
                    aliens,
                    my_settings,
                    ship,
                    stats,
                    bullets,
                    screen,
                    sb,
                )
                gf.bullet_update(bullets, aliens, screen, my_settings, ship,
                                 stats, sb)
                gf.support_upate(support, my_settings, ship, stats)
            gf.screen_update(screen, my_settings, ship, bullets, aliens, stats,
                             play_button, sb, bg, pause_btn, end_title,
                             support, score_display)
Example #36
0
class GameWindow(QWidget):

        ANIMATION_SHOW_RESULT_DURATION_PHASE_ONE = 2000
        ANIMATION_SHOW_RESULT_DURATION_PHASE_TWO = 5000

        def __init__(self, game, gameView):
                super(GameWindow, self).__init__()

                stretchA = (1000 - 618) * (1000 - 618)
                stretchB = 1000000 - stretchA

                layout = QGridLayout(self)
                layout.setColumnStretch(0, stretchB)
                layout.setColumnStretch(1, stretchA)

                leftLayout = QGridLayout()
                leftLayout.setRowStretch(0, stretchB)
                leftLayout.setRowStretch(1, stretchA)
                rightLayout = QGridLayout()
                rightLayout.setRowStretch(0, stretchA)
                rightLayout.setRowStretch(1, stretchB)
                layout.addLayout(leftLayout, 0, 0)
                layout.addLayout(rightLayout, 0, 1)

                self.game = game
                self.game.playersUpdated.connect(self._onPlayersUpdated)

                gameView.player = game.connectionManager.player
                gameView.attackInitiated.connect(self.game._onAttackInitiated)

                self.gameView = GameViewWrapper(gameView)
                self.eventBox = EventBox()
                self.countryBox = CountryInfoBox(self)
                self.statBox = StatBox(gameView)

                self.lose = Title('YOU LOSE', 100)
                self.win = Title('YOU WIN', 100)
                self.lose.setParent(self)
                self.win.setParent(self)
                self.lose.raise_()
                self.win.raise_()
                self.lose.hide()
                self.win.hide()

                self.eventBox.setColor(QColor(Qt.black))
                self.countryBox.setColor(QColor(Qt.gray))
                self.statBox.setColor(QColor(Qt.gray))

                leftLayout.addWidget(self.gameView, 0, 0)
                leftLayout.addWidget(self.eventBox, 1, 0)
                rightLayout.addWidget(self.statBox, 0, 0)
                rightLayout.addWidget(self.countryBox, 1, 0)

                gameView.hoverCountry.connect(self.countryBox.updateCountry)
                gameView.ownerChanged.connect(self.statBox.refresh)

                game.gameEvent.connect(self.eventBox.addEvent)
                game.gameLose.connect(self._triggerLose)
                game.gameWin.connect(self._triggerWin)

        closed = Signal()

        @Slot()
        def _unfreezeSize(self):
                self.setFixedSize(QSize(16777215, 16777215))

        def _triggerResult(self, result):
                result.changeSize(int(100 * self.gameView.width() / 677))
                rect = QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, result.titleImage().size(), self.gameView.rect())
                result.move(rect.x(), rect.y())
                result.show()
                result.raise_()

                self.setFixedSize(self.size())

                self.showResultAnimationGroup = QSequentialAnimationGroup()

                showResultAnimationPhaseOne = QPropertyAnimation(result, 'pos')
                showResultAnimationPhaseOne.setDuration(GameWindow.ANIMATION_SHOW_RESULT_DURATION_PHASE_ONE)
                showResultAnimationPhaseOne.setStartValue(QPoint(result.x(), -result.height()))
                showResultAnimationPhaseOne.setEndValue(result.pos())
                showResultAnimationPhaseOne.setEasingCurve(QEasingCurve.OutBounce)
                self.showResultAnimationGroup.addAnimation(showResultAnimationPhaseOne)

                showResultAnimationPhaseTwo = QPauseAnimation()
                showResultAnimationPhaseTwo.setDuration(GameWindow.ANIMATION_SHOW_RESULT_DURATION_PHASE_TWO)
                self.showResultAnimationGroup.addAnimation(showResultAnimationPhaseTwo)

                self.showResultAnimationGroup.finished.connect(result.hide)
                self.showResultAnimationGroup.finished.connect(self._unfreezeSize)
                self.showResultAnimationGroup.start(QAbstractAnimation.DeleteWhenStopped)

        @Slot()
        def _triggerLose(self):
                self.game.gameLose.disconnect()
                self._triggerResult(self.lose)

        @Slot()
        def _triggerWin(self):
                self.game.gameWin.disconnect()
                self._triggerResult(self.win)

        def _onPlayersUpdated(self):
                self.statBox.setPlayers(self.game.players)

        def closeEvent(self, event):
                self.closed.emit()
                super(GameWindow, self).closeEvent(event)

        def paintEvent(self, event):
                painter = QPainter()
                painter.begin(self)

                # background
                image = QImage(QDir.currentPath() + '/gui/images/background.png')
                image = image.copy(MainFrame.OFFSET_X, MainFrame.OFFSET_Y, MainFrame.WIDTH, MainFrame.HEIGHT)
                image = image.scaled(self.width(), self.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation);
                painter.drawImage(0, 0, image)

                painter.end()

        def show(self):
                super(GameWindow, self).show()
                rect = QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, self.size(),
                                          QApplication.desktop().availableGeometry())
                self.move(rect.x(), rect.y())
Example #37
0
 def title(self, text):
     self._title = Title(text)
Example #38
0
def doit():
    return Title.get(1)
Example #39
0
class GameWindow(QWidget):

    ANIMATION_SHOW_RESULT_DURATION_PHASE_ONE = 2000
    ANIMATION_SHOW_RESULT_DURATION_PHASE_TWO = 5000

    def __init__(self, game, gameView):
        super(GameWindow, self).__init__()

        stretchA = (1000 - 618) * (1000 - 618)
        stretchB = 1000000 - stretchA

        layout = QGridLayout(self)
        layout.setColumnStretch(0, stretchB)
        layout.setColumnStretch(1, stretchA)

        leftLayout = QGridLayout()
        leftLayout.setRowStretch(0, stretchB)
        leftLayout.setRowStretch(1, stretchA)
        rightLayout = QGridLayout()
        rightLayout.setRowStretch(0, stretchA)
        rightLayout.setRowStretch(1, stretchB)
        layout.addLayout(leftLayout, 0, 0)
        layout.addLayout(rightLayout, 0, 1)

        self.game = game
        self.game.playersUpdated.connect(self._onPlayersUpdated)

        gameView.player = game.connectionManager.player
        gameView.attackInitiated.connect(self.game._onAttackInitiated)

        self.gameView = GameViewWrapper(gameView)
        self.eventBox = EventBox()
        self.countryBox = CountryInfoBox(self)
        self.statBox = StatBox(gameView)

        self.lose = Title('YOU LOSE', 100)
        self.win = Title('YOU WIN', 100)
        self.lose.setParent(self)
        self.win.setParent(self)
        self.lose.raise_()
        self.win.raise_()
        self.lose.hide()
        self.win.hide()

        self.eventBox.setColor(QColor(Qt.black))
        self.countryBox.setColor(QColor(Qt.gray))
        self.statBox.setColor(QColor(Qt.gray))

        leftLayout.addWidget(self.gameView, 0, 0)
        leftLayout.addWidget(self.eventBox, 1, 0)
        rightLayout.addWidget(self.statBox, 0, 0)
        rightLayout.addWidget(self.countryBox, 1, 0)

        gameView.hoverCountry.connect(self.countryBox.updateCountry)
        gameView.ownerChanged.connect(self.statBox.refresh)

        game.gameEvent.connect(self.eventBox.addEvent)
        game.gameLose.connect(self._triggerLose)
        game.gameWin.connect(self._triggerWin)

    closed = Signal()

    @Slot()
    def _unfreezeSize(self):
        self.setFixedSize(QSize(16777215, 16777215))

    def _triggerResult(self, result):
        result.changeSize(int(100 * self.gameView.width() / 677))
        rect = QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter,
                                  result.titleImage().size(),
                                  self.gameView.rect())
        result.move(rect.x(), rect.y())
        result.show()
        result.raise_()

        self.setFixedSize(self.size())

        self.showResultAnimationGroup = QSequentialAnimationGroup()

        showResultAnimationPhaseOne = QPropertyAnimation(result, 'pos')
        showResultAnimationPhaseOne.setDuration(
            GameWindow.ANIMATION_SHOW_RESULT_DURATION_PHASE_ONE)
        showResultAnimationPhaseOne.setStartValue(
            QPoint(result.x(), -result.height()))
        showResultAnimationPhaseOne.setEndValue(result.pos())
        showResultAnimationPhaseOne.setEasingCurve(QEasingCurve.OutBounce)
        self.showResultAnimationGroup.addAnimation(showResultAnimationPhaseOne)

        showResultAnimationPhaseTwo = QPauseAnimation()
        showResultAnimationPhaseTwo.setDuration(
            GameWindow.ANIMATION_SHOW_RESULT_DURATION_PHASE_TWO)
        self.showResultAnimationGroup.addAnimation(showResultAnimationPhaseTwo)

        self.showResultAnimationGroup.finished.connect(result.hide)
        self.showResultAnimationGroup.finished.connect(self._unfreezeSize)
        self.showResultAnimationGroup.start(
            QAbstractAnimation.DeleteWhenStopped)

    @Slot()
    def _triggerLose(self):
        self.game.gameLose.disconnect()
        self._triggerResult(self.lose)

    @Slot()
    def _triggerWin(self):
        self.game.gameWin.disconnect()
        self._triggerResult(self.win)

    def _onPlayersUpdated(self):
        self.statBox.setPlayers(self.game.players)

    def closeEvent(self, event):
        self.closed.emit()
        super(GameWindow, self).closeEvent(event)

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)

        # background
        image = QImage(QDir.currentPath() + '/gui/images/background.png')
        image = image.copy(MainFrame.OFFSET_X, MainFrame.OFFSET_Y,
                           MainFrame.WIDTH, MainFrame.HEIGHT)
        image = image.scaled(self.width(), self.height(), Qt.IgnoreAspectRatio,
                             Qt.SmoothTransformation)
        painter.drawImage(0, 0, image)

        painter.end()

    def show(self):
        super(GameWindow, self).show()
        rect = QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, self.size(),
                                  QApplication.desktop().availableGeometry())
        self.move(rect.x(), rect.y())
Example #40
0
class WaferMap:
 
    def __init__(self):
        self.img = None
        self.legend = Legend()
        self.title = Title()
        self.autosize = App.cfg['image']['autosize']
        self.autosize_minpx = App.cfg['image']['autosize_minpx']
        self.basewidth = App.cfg['image']['basewidth']
        self.baseheight = App.cfg['image']['baseheight']
        self.padding = App.cfg['image']['padding']
        self.showborder = App.cfg['image']['border']
        self.showtitle = App.cfg['title']['show']
        self.showlegend = App.cfg['legend']['show']
        self.showgrid = App.cfg['axis']['grid']
        self.showaxis = App.cfg['axis']['show']
        self.showflat = App.cfg['image']['flatline']
        self.showtimestamp = App.cfg['image']['timestamp']
        self.timestampcolor = App.cfg['image']['timestampcolor']
        self.bordercolor = App.cfg['image']['bordercolor']
        self.streetcolor = App.cfg['image']['streetcolor']
        self.flatcolor = App.cfg['image']['flatcolor']
        self.gridcolor = App.cfg['axis']['gridcolor']
        self.axiscolor = App.cfg['axis']['color']
        self.axisfont = App.cfg['axis']['font']
        self.bgcolor = App.cfg['image']['bgcolor']
      
    def buildmap(self, lot, wfr, testset):
    
        #---------------------------------------------------------------------------
        # Get actual extents... that is number of rows & cols in the wafermap, 
        # If the demodata routine was used, a random number of rows/cols were
        # generated.
        #--------------------------------------------------------------------------- 
        
        min_Y = min(d.Y for d in wfr.dielist)
        max_Y = max(d.Y for d in wfr.dielist)
        min_X = min(d.X for d in wfr.dielist)
        max_X = max(d.X for d in wfr.dielist)
        
        col_count = max_X - min_X+1
        row_count = max_Y - min_Y+1
        
        log.debug('Die Extents: X = {} to {}  Y = {} to {}'.format(min_X, max_X, min_Y, max_Y))
        log.debug('Columns (X) = {}, Rows (Y) = {} (Total Die={})'.format(col_count, row_count, len(wfr.dielist)))
        
         
        if self.basewidth >= self.baseheight:
            sizeRatio = float(self.basewidth) / float(self.baseheight)
        else:
            sizeRatio = float(self.baseheight) / float(self.basewidth)
             
        log.debug('Size Ratio: {:.2f}, width={}, height={}'.format(sizeRatio, self.basewidth, self.baseheight))
        
        
        #---------------------------------------------------------------------------
        # If image autosize is enabled, the canvas size may be increased to ensure
        # die are visible.  This will force a minimum pixel size of "autosize_minpx".
        # The original aspect ratio will be maintained.
        #---------------------------------------------------------------------------
        
        if self.autosize:
            
            autominX = (self.autosize_minpx * col_count) + (2 * self.padding)
            autominY = (self.autosize_minpx * row_count) + (2 * self.padding)
            log.debug('Autosize Minimum Map Size X={} Y={} at Autopx = {}'.format( 
                      autominX, autominY, self.autosize_minpx))
        
            if(autominX > self.basewidth):
                self.basewidth = autominX
                self.baseheight = int (float(self.basewidth) * float(sizeRatio))
                log.debug('Autosize (autominX > bw) Updated sizes - width={}, height={}, sizeRatio={}'.format(
                    self.basewidth, self.baseheight, float(sizeRatio)))
            elif (autominY > self.baseheight):
                self.baseheight = autominY
                self.basewidth = int (float(self.baseheight) * float(sizeRatio))
                log.debug('Autosize (autominY > bh) Updated sizes - width={}, height={}, sizeRatio={}'.format(
                    self.basewidth, self.baseheight, float(sizeRatio)))
            else:
                log.debug('Autosize sizing not required, width={}, height={}, autominX={}, autominY={}'.format(
                    self.basewidth, self.baseheight, autominX, autominY)) 
    
            
            #Store updated values back in cfg 
#             App.cfg['image']['basewidth'] = bw
#             App.cfg['image']['baseheight'] = bh
        
    
        
        # Nominal size of map excluding padding
        mapX = self.basewidth - (self.padding *2)
        mapY = self.baseheight - (self.padding *2)
        log.debug('Map Space (BaseSize - 2*Padding)  (X,Y)=({},{})  Padding = {}'.format(
            mapX, mapY, self.padding))
        
        
        # Calculate the die's pixel size - width (X) and height (Y) based on map size 
        # divided by the number of rows & columns
        X_pixels = mapX / col_count     #X-diesize in pixels
        Y_pixels = mapY / row_count     #Y diesize in pixels
        log.debug('Pixels per die: X={}, Y={}'.format(X_pixels, Y_pixels))
        
        #---------------------------------------------------------------------------
        # Unless the nominal image size (Canvas size minus padding) happens to be an
        # exact multiple of the calculated die size in pixels, we will have some 
        # space left on all sides.
        # Calculate the extra space so we can center the image on the canvas
        #---------------------------------------------------------------------------   
        slackX = (mapX - (X_pixels * col_count)) / 2
        slackY = (mapY - (Y_pixels * row_count)) / 2
        log.debug('Slack: X={}, Y={}'.format(slackX, slackY))
        log.debug('Calculated Map Size (excluding slack) - (X,Y) = ({},{})'.format( 
                  X_pixels * col_count, Y_pixels * row_count))
    #     
        #-------------------------------------------------------------------------
        # Have the legend calculate its size, it will be rendered later, but we
        # need to know the space it will take up so we can adjust the canvas size 
        # Actual Map width is then adjusted to allow for legend.
        #--------------------------------------------------------------------------
        actualWidth = self.basewidth
        if self.showlegend:
            self.legend.getsize(wfr.dielist, testset)
            actualWidth += self.legend.width
            log.debug('Legend Width = {}'.format(self.legend.width))
           
        #--------------------------------------------------------------------------
        # baseheight and fontsize adjusted for title
        #--------------------------------------------------------------------------
        # Start with a reasonable guess for the size of the title font and then
        # autosize it from there.   May not be the most efficient way to do 
        # this, but it works for now...
        #--------------------------------------------------------------------------
        actualHeight = self.baseheight
        titleheight = 0
        if self.showtitle:
            
            #A guess...
            title_fontsize = actualWidth//40    
            titlekeys = self.title.autosize(lot.mir, wfr, title_fontsize, testset)
            upsearch=False
            
            # While title string width at current font size is > canvas width, decrease 
            # font size and re-evaluate 
            if(titlekeys['maxfw'] > actualWidth):
                while titlekeys['maxfw'] > actualWidth:
                    upsearch=False
                    title_fontsize -= 1
                    titlekeys = self.title.autosize(lot.mir, wfr, title_fontsize, testset)
        #             print "D:imageWith = {}, fontsize = {}, maxfw={}, height={}".format(actualWidth, title_fontsize, titlekeys['maxfw'], titlekeys['maxfh'])
            # Otherwise, font is too small, increase it and re-evaluate
            else:
                while titlekeys['maxfw'] < actualWidth:
                    upsearch=True
                    title_fontsize += 1
                    titlekeys = self.title.autosize(lot.mir, wfr, title_fontsize, testset)
        #             print "U:imageWith = {}, fontsize = {}, maxfw={}, height={}".format(actualWidth, title_fontsize, titlekeys['maxfw'], titlekeys['maxfh'])    
        
            # If we were decreasing font size when the while condition became false, all the titlekeys are properly set, 
            # from the last loop cycle.... but if we were increasing font size, the last loop cycle left the titlekeys 
            # in a state for a larger font, so decrease the font size by one and re-evaluate the titlekeys
            if(upsearch):
                title_fontsize -=1
                titlekeys = self.title.autosize(lot.mir, wfr, title_fontsize, testset)
        
            titleheight = titlekeys['maxfh']
            
            # Increase canvas size to allow for title
            actualHeight += titleheight
            log.debug('Title Height = {}, Title Fontsize = {}'.format(titleheight, title_fontsize))
    
        #--------------------------------------------------------------------------
        # Adjust Width and Height for axis space
        #--------------------------------------------------------------------------
#         if self.showaxis:
#             actualWidth += axis_space
#             actualHeight += axis_space
        #--------------------------------------------------------------------------
        # Get axis space, add in 10 pixels for flat spacing.  (the axes are 
        # shifted left or up by 10 pixels when they are drawn to account for the
        # 10 pixels).
        #--------------------------------------------------------------------------
        axis_space = 0
        if self.showaxis:
            axis_space = maputil.do_axis(self, wfr.dielist, X_pixels, Y_pixels) + 10
            log.debug('Axis Space = {}'.format(axis_space))
            
        actualWidth += axis_space
        actualHeight += axis_space           
                      
        log.debug('Axis space = {}'.format(axis_space))    
        log.debug('Actual Image Size (X,Y) = ({},{})'.format(actualWidth, actualHeight))     

                            
        #--------------------------------------------------------------------------
        # Create the canvas and draw the wafermap
        #--------------------------------------------------------------------------
        self.img = Image.new('RGB', (actualWidth,actualHeight), self.bgcolor)
    
        # Get the drawable object...
        dr = ImageDraw.Draw(self.img)
        
        # map_extents are used for tracking the actual pixel extents of the drawn map which makes
        # calculating the location to draw the flat & axis labels a bit easier...
        
        map_extents = {'minx':65535, 'miny':65535, 'maxx':0, 'maxy':0}
        
        # limit flag_size factor to a minimum of 1.0 (or else flag will exceed die boundary)
        App.cfg['flag']['size_factor'] = max(App.cfg['flag']['size_factor'], 1.0)
        
        # if we want the grid, draw it first so it's behind everything else...
        if self.showgrid:   
            maputil.do_grid(self, wfr.dielist, X_pixels, Y_pixels, self.padding, axis_space, slackX, slackY, titleheight)
       
        idx=0       
        imap = []
        #-----------------------------------------------------------
        # Draw All die loop
        #-----------------------------------------------------------
        for eachDie in wfr.dielist:
            mybin=getattr(eachDie,App.cfg['binmap'])
            idx+=1      
            x1 = self.padding + axis_space + ((eachDie.X - min_X) * X_pixels) + slackX
            y1 = self.padding + axis_space + ((eachDie.Y - min_Y) * Y_pixels) + slackY + titleheight
            x2 = x1 + X_pixels
            y2 = y1 + Y_pixels
            
            # Draw the die and file with bincolor
            if eachDie.testset == testset:
                dr.rectangle([x1,y1,x2,y2], fill=App.cfg['bin'][str(mybin)]['color'], outline=self.streetcolor)
                imap.append({'Row':eachDie.Y,'Col':eachDie.X,'x':x1,'y':y1,'width':x2-x1,'height':y2-y1})
                # Draw any specified symbols, if enabled 
                if App.cfg['enable_symbols']:
                    maputil.do_symbol(dr,x1,y1,x2,y2, False, **App.cfg['bin'][str(mybin)])
            
            # Draw flags if appropriate        
            xystr="{}|{}".format(eachDie.X, eachDie.Y)   # Bindict Key 
            if (wfr.diedict[xystr]['flags'] & constants.FLAG_MULTITEST) and App.cfg['flag']['show']:
                if wfr.diedict[xystr]['flags'] & constants.FLAG_DUPLICATE_BIN:
                    flagcolor= App.cfg['flag']['duplicate_color']
                else:
                    flagcolor= App.cfg['flag']['split_color'] 
                flagX = int(float(x2-x1)/float(App.cfg['flag']['size_factor']))
                flagY = int(float(y2-y1)/float(App.cfg['flag']['size_factor'])) 
                dr.polygon([(x1,y1+flagY),(x1,y1),(x1+flagX,y1)], fill=flagcolor, outline=(0,0,0))  
       
        
            # track minimum and maximums of actual drawn wafermap.
            map_extents['minx']= min(map_extents['minx'],x1)
            map_extents['maxx']= max(map_extents['maxx'],x2)
            map_extents['miny']= min(map_extents['miny'],y1)
            map_extents['maxy']= max(map_extents['maxy'],y2)
        
        #-----------------------------------------------------------
           
        log.debug('Drawn Map Extents = {}'.format(map_extents))
    
    #     do_html(imap, actualWidth, actualHeight)
            
        #--------------------------------------------------------------------------
        # Draw title area
        #--------------------------------------------------------------------------
        if self.showtitle:
            dr.rectangle([0,0,actualWidth-1,titleheight], fill=self.title.bgcolor, outline=self.bordercolor)
            self.title.render(self.img, wfr, titlekeys)
        
        #--------------------------------------------------------------------------
        # Draw legend, border, flat indicator, timestamp, axis labels
        #--------------------------------------------------------------------------
        if self.showlegend:
            self.legend.render(self.img, self.basewidth + axis_space , self.padding + titleheight)
        
        if self.showborder:
            dr.rectangle([0,0,actualWidth-1,actualHeight-1], fill=None, outline=self.bordercolor)
        
        if self.showflat:
            maputil.do_flat(self, lot.wcr['WF_FLAT'], map_extents, self.flatcolor)
        
        if self.showtimestamp:
            maputil.do_timestamp(self, color=self.timestampcolor) 
    
        if self.showaxis:
            maputil.do_axis(self, wfr.dielist, X_pixels, Y_pixels, map_extents, True)
       
        return(self.img)