Pygame-生活游戏,在网格中选择多个单元

时间:2019-05-25 12:30:01

标签: pygame python-3.7 conways-game-of-life

我正在从事生活游戏的pygame游戏。我可以通过单击它们来手动激活或停用单元格,但是我想添加一个在网格上绘制的功能(通过单击一次然后移动鼠标光标来激活多个单元格)。 现在,用鼠标左键可以手动选择单元格,我想将绘图功能分配给鼠标右键。我通过将事件按钮设置为1或3来分隔了鼠标单击。我无法弄清楚在单击鼠标右键后将鼠标悬停在它们上方可以激活多个单元格。我以为我需要一个while循环(在按下按钮时执行此操作..),但是它仅激活了第一个单元格(您单击的单元格)。对于如何解决这个问题,有任何的建议吗?下面添加了部分代码。

    # Runs the game loop
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.game_over = True  
            if event.type == pygame.MOUSEBUTTONDOWN:  
                posn = pygame.mouse.get_pos()
                x = int(posn[0] / CELL_SIZE)
                y = int(posn[1] / CELL_SIZE)
                print(x,y)
                if event.button == 1: #Left click is 1, right click is 3.
                    if next_generation[x][y] == COLOR_DEAD:
                        self.activate_living_cell(x, y)
                    else:
                        self.deactivate_living_cell(x, y)
                elif event.button == 3:
                        self.activate_living_cell(x, y)

            if event.type == pygame.KEYDOWN:  
                if event.unicode == 'q':  # Press q to quit.
                    self.game_over = True
                    print("q")

                elif event.key == pygame.K_SPACE:  # Space for the next iteration manually.
                    self.create_next_gen()
                    print("keypress")
                elif event.unicode == 'a':  # a to automate the iterations.
                    self.next_iteration = True
                    print("a")
                elif event.unicode == 's':  # s to stop the automated iterations.
                    self.next_iteration = False
                    print("s")
                elif event.unicode == 'r':  # r to reset the grid.
                    self.next_iteration = False
                    self.init_gen(next_generation, COLOR_DEAD)
                    print("r")

    def run(self):
        while not self.game_over:
            # Set the frames per second.
            self.handle_events()
            if self.next_iteration:  # if next iteration is true, the next gen is created according to the rules.
                self.create_next_gen()
            # Updating
            self.update_gen()
            pygame.display.flip()
            self.FPSCLOCK.tick(fps_max)
            self.root.update()

if __name__ == "__main__":
    game = GameOfLife()
    game.run()

0 个答案:

没有答案