Ejemplo n.º 1
0
    def __init__(self):
        # initializes game
        pygame.init()
        pygame.display.set_caption(settings.title)
        pygame.key.set_repeat(500, 100)
        self.seconds = 60
        self.minutes = 3
        pygame.time.set_timer(USEREVENT + 1,
                              1000)  # 1 second is 1000 milliseconds
        self.screen = pygame.display.set_mode((settings.w, settings.h))
        self.clock = pygame.time.Clock()
        self.sb = ScoreBoard(self, settings, self.screen)

        # for determning the map being used
        self.makeCopies()
        self.mapName = self.map1
        self.previousMapName = self.map1
        self.newMap = False
        self.new1()
        self.playerRestarts = False
        self.stillPlaying = True
        self.playerDone = False

        # for the timer
        self.clock = pygame.time.Clock()
Ejemplo n.º 2
0
class Draughts(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        '''initiates application UI'''
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)
        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
        ''' Makes the connection with the scoreboard. '''
        self.scoreBoard.make_connection(self.tboard)

        self.tboard.start()

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('DraughtsV3')
        self.show()

    def center(self):
        '''centers the window on the screen'''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
Ejemplo n.º 3
0
class Chess(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def getBoard(self):
        return self.board

    def getScoreBoard(self):
        return self.scoreBoard

    def initUI(self):
        '''initiates application UI'''
        self.board = Board(self)
        self.setCentralWidget(self.board)
        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.scoreBoard.make_connection(self.board)

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('Chess')
        self.show()

    def center(self):
        '''centers the window on the screen'''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
Ejemplo n.º 4
0
    def initUI(self):
        """
        Initilization of the game board and the score board.

        :return: Nothing
        """
        # Initialization of the board class
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)

        # Initialization of the ScoreBoard class
        self.scoreBoard = ScoreBoard(self.tboard)
        self.tboard.setScoreBoard(self.scoreBoard)

        # Set the score board in a dockwidget at the right of the window
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)

        # Initialization of the status bar
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)

        # Start the class Board
        self.tboard.start()
        self.gameToolbar()

        # Initialization of the windows
        self.resize(900, 800)
        self.setFixedSize(self.size())
        self.center()
        self.setWindowTitle('Checkers')
        self.show()
Ejemplo n.º 5
0
 def __init__(self, SM, player):
     self.sm = SM
     self.player = player
     self.clock = pygame.time.Clock()
     self.gameObjects = []
     self.addbackground()
     self.retry = False
     self.scoreBoard = ScoreBoard()
Ejemplo n.º 6
0
    def initUI(self):
        '''initiates application UI'''
        self.board = Board(self)
        self.setCentralWidget(self.board)
        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.scoreBoard.make_connection(self.board)

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('Chess')
        self.show()
Ejemplo n.º 7
0
def run_game():
    #to e able to use the module
    pygame.init()
    #setting the settings object
    aliens = Group()
    ai_setting = Settings(aliens)
    screen = pygame.display.set_mode((ai_setting.width, ai_setting.legnth))
    pygame.display.set_caption("Invasion game")
    #setting the charecter object
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    alien_bullets = Group()
    stats = States(ai_setting)
    gf.create_fleet(ai_setting, screen, aliens, ship, stats)
    play_button = Button(ai_setting, screen, "Play")
    sb = ScoreBoard(ai_setting, screen, stats)
    clock = pygame.time.Clock()

    while True:
        gf.check_events(stats, play_button, aliens, bullets, ai_setting, ship,
                        screen, sb)
        if stats.game_active:
            #ai_setting.main_music.play(loops=10)
            gf.moving(ship, screen, ai_setting.ship_speed_factor)
            gf.delet_bullets(bullets)
        #clock.tick(ai_setting.fps)
        gf.update_screen(stats, aliens, bullets, ship, ai_setting, screen,
                         play_button, sb, alien_bullets)
Ejemplo n.º 8
0
    def initUI(self):
        '''initiates application UI'''
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)
        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
        ''' Makes the connection with the scoreboard. '''
        self.scoreBoard.make_connection(self.tboard)

        self.tboard.start()

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('DraughtsV3')
        self.show()
Ejemplo n.º 9
0
 def __init__(self):
     self.settings = GameSettings()
     self.scoreBoard = ScoreBoard(self.settings)
     self.gameBoard = GameBoard(self.settings)
     self.instructions = Instructions()
     self.endScreen = EndScreen()
     self.ballGrid = [[0 for x in range(self.settings.numberBallsH)]
                      for y in range(self.settings.numberBallsV)]
     self.level = 2
     self.score = 0
Ejemplo n.º 10
0
def runGame():
    """<<alien invasion>>主函数"""
    # 初始化游戏
    pygame.init()
    # 创建Settings类对象访问游戏设置
    aiSettings = Settings()
    # 创建一个屏幕对象
    screen = pygame.display.set_mode(
        (aiSettings.screenWidth, aiSettings.screenHeight))
    """
	set_mode会返回一个Surface对象,代表了在桌面上出现的那个窗口,三个参数第一个为元祖,代表分辨率(必须);
	第二个是一个标志位,具体意思见下表,如果不用什么特性,就指定0;第三个为色深。
	标志位 	功能
	FULLSCREEN 	创建一个全屏窗口
	DOUBLEBUF 	创建一个“双缓冲”窗口,建议在HWSURFACE或者OPENGL时使用
	HWSURFACE 	创建一个硬件加速的窗口,必须和FULLSCREEN同时使用
	OPENGL 		创建一个OPENGL渲染的窗口
	RESIZABLE 	创建一个可以改变大小的窗口
	NOFRAME 	创建一个没有边框的窗口
	"""
    # 创建一个统计数据存储对象,并初始化游戏部分动态参数
    status = GameStatus(aiSettings)
    # 创建一个飞船对象
    ship = Ship(aiSettings, screen)
    # 创建一组外星人序列
    aliens = Group()
    # 创建一组子弹序列
    bullets = Group()
    # 创建PLAY按钮
    playButton = Button(aiSettings, screen, 'Play')
    # 创建计分板
    scoreBoard = ScoreBoard(aiSettings, screen, status)
    # 设置窗口标题
    pygame.display.set_caption("Alien Invasion By JerCas丶Ety")

    # 开始游戏主循环
    """
	无限循环,直到用户跳出。在这个主循环里做的事情就是不停地画背景和更新光标位置,
	虽然背景是不动的,我们还是需要每次都画它, 否则鼠标覆盖过的位置就不能恢复正常了。
	"""
    while True:
        # 1.检查玩家输入-2.更新飞船位置-3.更新所有未消失子弹位置并删除已消失子弹位置-4.根据以上更新后的screen对象位置刷新重新绘制屏幕
        gameFunction.checkEvents(aiSettings, screen, status, playButton, ship,
                                 aliens, bullets, scoreBoard)
        # 游戏处于活动状态时 才刷新三者对象位置
        if status.gameActive:
            # 飞船位置更新,!!!必须置于屏幕刷新语句前,以便实现飞船位置更新后再刷新屏幕而将更新后的新位置刷新到屏幕上以实现视觉上的位置移动
            ship.update()
            gameFunction.updateBullets(aiSettings, screen, status, ship,
                                       aliens, bullets, scoreBoard)
            gameFunction.updateAliens(aiSettings, status, screen, ship, aliens,
                                      bullets, scoreBoard)
        gameFunction.updateScreen(aiSettings, screen, status, ship, aliens,
                                  bullets, playButton, scoreBoard)
Ejemplo n.º 11
0
def runGame():
    pygame.init()
    pygame.display.set_caption("Pong")
    settings = Settings()
    gameStats = GameStats()
    screen = pygame.display.set_mode(
        (settings.screenWidth, settings.screenHeight))
    menu = Menu()
    button = Button(screen, settings, "Play")
    scores = ScoreBoard(screen, settings, gameStats)
    player = Player(screen, settings)
    bot = AI(screen, settings, menu)
    balls = Group()
    newBall = Ball(screen, settings, menu)
    balls.add(newBall)

    while True:
        screen.fill(settings.bgColor)
        gf.drawField(screen, settings)
        gf.checkEvent(player, settings, menu, gameStats, scores, button)
        gf.updateScreen(player, balls, bot, scores)

        if gameStats.gameActive == True:
            player.update()
            bot.update(balls)
            balls.update(settings, gameStats, scores, balls)
            scores.showScore()
            gf.checkBallAmount(screen, settings, bot, balls, menu)

            if gameStats.playerScore >= settings.scoreLimit or gameStats.botScore >= settings.scoreLimit:
                gf.restartGame(screen, settings, gameStats, player, bot, balls,
                               menu)

        if gameStats.gameActive == False:
            button.drawButton()
            pygame.mouse.set_visible(True)
            menu.drawWin(gameStats, settings)
            menu.prepMenu(screen, settings, balls, bot)
            menu.drawMenu()

        pygame.display.flip()
Ejemplo n.º 12
0
def run_game():
    """main game function"""
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    pygame.display.set_caption("Plane Wars")
    game_settings = Settings()

    framerate = pygame.time.Clock()  # 设置framerate来获取时间和帧率,是用来控制m1爆炸的动画速率
    # 监听是否有按键被长按,如果有,则根据设置的delay延迟重复触发
    pygame.key.set_repeat(game_settings.bullet_delay,
                          game_settings.bullet_interval)  # 实现子弹连续间隔发射

    # 设置定时器事件:创建敌机事件
    pygame.time.set_timer(st.CREATE_M1_EVENT, 1000)
    pygame.time.set_timer(st.CREATE_M2_EVENT, 3000)
    pygame.time.set_timer(st.CREATE_M3_EVENT, 5000)
    pygame.time.set_timer(st.FIRE_EVENT, 2000)

    # screen is an instance of class Surface
    # Surface can be recognized as a image
    # use Surface.blit can show another image on current Surface
    screen = pygame.display.set_mode((game_settings.screen_size))
    screen_other_part = pygame.Rect(
        game_settings.screen_other_part_coordinate[0],
        game_settings.screen_other_part_coordinate[1],
        game_settings.screen_other_part[0], game_settings.screen_other_part[1])
    screen_game_part = game_settings.screen_game_part_image.get_rect()

    stats = GameStats(game_settings)
    sb = ScoreBoard(game_settings, screen, stats, screen_other_part)

    player = Player(screen, game_settings)
    bullets = pygame.sprite.Group()
    m1s = pygame.sprite.Group()
    m2s = pygame.sprite.Group()
    m3s = pygame.sprite.Group()

    # 开始游戏的主循环
    while True:
        framerate.tick(game_settings.M1_down_rate)
        ticks = pygame.time.get_ticks()
        # 监视键盘和鼠标事件
        gf.check_events(player, game_settings, screen, bullets, m1s, m2s, m3s)
        # 让角色可见
        player.update(bullets, game_settings, screen, ticks)

        gf.update_bullets(bullets, m1s, m2s, m3s)
        gf.update_m1s(m1s, game_settings, ticks, player, stats, sb)
        gf.update_m2s(m2s, game_settings, ticks, player, stats, sb)
        gf.update_m3s(m3s, game_settings, ticks, player, stats, sb)

        # 让最近绘制的屏幕可见
        gf.update_screen(
            game_settings,
            screen,  # 固定参数
            screen_other_part,
            screen_game_part,  # 屏幕划分
            stats,
            sb,  # 计分板
            player,
            bullets,
            m1s,
            m2s,
            m3s  # 可移动的角色
        )
Ejemplo n.º 13
0
    def initUI(self):
        '''initiates application UI'''
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)
        # SETTING UP MENU BAR
        mainMenu = self.menuBar()

        # SETTING UP TWO MENUS IN MENU BAR
        gameMenu = mainMenu.addMenu(" Game")

        pauseAction = QAction(QIcon("./img/pause.png"), "Pause Game", self)
        gameMenu.addAction(pauseAction)
        pauseAction.triggered.connect(self.tboard.pause)

        playAction = QAction(QIcon("./img/play.png"), "Play Game", self)
        gameMenu.addAction(playAction)
        playAction.triggered.connect(self.tboard.start)

        resetAction = QAction(QIcon("./img/reset.png"), "Reset", self)
        gameMenu.addAction(resetAction)
        resetAction.triggered.connect(self.tboard.resetGame)

        exitAction = QAction(QIcon("./img/exit.png"), "Exit", self)
        gameMenu.addAction(exitAction)
        exitAction.triggered.connect(self.exit)

        helpMenu = mainMenu.addMenu("Help")
        help = helpMenu.addMenu(QIcon("./img/help.png"), " Help")
        htp = help.addMenu("How To Play")

        rulesAction = QAction("Rules", self)
        help.addAction(rulesAction)
        rulesAction.triggered.connect(self.rules)

        about = QAction(QIcon("./img/about.png"), "About", self)
        helpMenu.addAction(about)
        about.triggered.connect(self.about)

        howtoplay = QAction(QIcon("./img/checkers.png"), "How To Play", self)
        htp.addAction(howtoplay)
        howtoplay.triggered.connect(self.htpHelp)

        pause = QAction(QIcon("./img/pause.png"), "Pause", self)
        htp.addAction(pause)
        pause.triggered.connect(self.pauseHelp)

        play = QAction(QIcon("./img/play.png"), "Play", self)
        htp.addAction(play)
        play.triggered.connect(self.playHelp)

        reset = QAction(QIcon("./img/reset.png"), "Reset", self)
        htp.addAction(reset)
        reset.triggered.connect(self.resetHelp)

        exit = QAction(QIcon("./img/exit.png"), "Exit", self)
        htp.addAction(exit)
        exit.triggered.connect(self.exitHelp)

        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
        self.scoreBoard.make_connection(self.tboard)

        self.tboard.start()

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('Draughts')
        self.setWindowIcon(QIcon("./img/checkers.png"))
        self.show()
        self.option()
Ejemplo n.º 14
0
class Draughts(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        '''initiates application UI'''
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)
        # SETTING UP MENU BAR
        mainMenu = self.menuBar()

        # SETTING UP TWO MENUS IN MENU BAR
        gameMenu = mainMenu.addMenu(" Game")

        pauseAction = QAction(QIcon("./img/pause.png"), "Pause Game", self)
        gameMenu.addAction(pauseAction)
        pauseAction.triggered.connect(self.tboard.pause)

        playAction = QAction(QIcon("./img/play.png"), "Play Game", self)
        gameMenu.addAction(playAction)
        playAction.triggered.connect(self.tboard.start)

        resetAction = QAction(QIcon("./img/reset.png"), "Reset", self)
        gameMenu.addAction(resetAction)
        resetAction.triggered.connect(self.tboard.resetGame)

        exitAction = QAction(QIcon("./img/exit.png"), "Exit", self)
        gameMenu.addAction(exitAction)
        exitAction.triggered.connect(self.exit)

        helpMenu = mainMenu.addMenu("Help")
        help = helpMenu.addMenu(QIcon("./img/help.png"), " Help")
        htp = help.addMenu("How To Play")

        rulesAction = QAction("Rules", self)
        help.addAction(rulesAction)
        rulesAction.triggered.connect(self.rules)

        about = QAction(QIcon("./img/about.png"), "About", self)
        helpMenu.addAction(about)
        about.triggered.connect(self.about)

        howtoplay = QAction(QIcon("./img/checkers.png"), "How To Play", self)
        htp.addAction(howtoplay)
        howtoplay.triggered.connect(self.htpHelp)

        pause = QAction(QIcon("./img/pause.png"), "Pause", self)
        htp.addAction(pause)
        pause.triggered.connect(self.pauseHelp)

        play = QAction(QIcon("./img/play.png"), "Play", self)
        htp.addAction(play)
        play.triggered.connect(self.playHelp)

        reset = QAction(QIcon("./img/reset.png"), "Reset", self)
        htp.addAction(reset)
        reset.triggered.connect(self.resetHelp)

        exit = QAction(QIcon("./img/exit.png"), "Exit", self)
        htp.addAction(exit)
        exit.triggered.connect(self.exitHelp)

        self.scoreBoard = ScoreBoard()
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
        self.scoreBoard.make_connection(self.tboard)

        self.tboard.start()

        self.resize(800, 800)
        self.center()
        self.setWindowTitle('Draughts')
        self.setWindowIcon(QIcon("./img/checkers.png"))
        self.show()
        self.option()

    def center(self):
        '''centers the window on the screen'''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def option(self):
        items = ("Red", "Blue", "Green", "Yellow", "Pink")
        item, okPressed = QInputDialog.getItem(self, "Options",
                                               "Player1 Colour:", items, 0,
                                               False)
        if okPressed and item:
            print(item)
        else:
            item = "Yellow"
        if item == "Red":
            player1colour = Qt.red

            items2 = ("Blue", "Yellow")
        elif item == "Blue":
            player1colour = Qt.blue
            items2 = ("Red", "Green", "Yellow", "Pink")
        elif item == "Yellow":
            player1colour = Qt.yellow
            items2 = ("Red", "Green", "Blue", "Pink")
        elif item == "Pink":
            player1colour = Qt.magenta
            items2 = ("Green", "Yellow", "Blue")
        else:
            player1colour = Qt.green
            items2 = ("Blue", "Yellow", "Pink")
        item2, okPressed = QInputDialog.getItem(self, "Options",
                                                "Player2 Colour:", items2, 0,
                                                False)
        if okPressed and item2:
            print(item2)
        else:
            item2 = "Red"
        if item2 == "Red":
            player2colour = Qt.red
        elif item2 == "Blue":
            player2colour = Qt.blue
        elif item2 == "Yellow":
            player2colour = Qt.yellow
        elif item2 == "Pink":
            player2colour = Qt.magenta
        else:
            player2colour = Qt.green
        self.tboard.ColorSelection(player1colour, player2colour)
        self.scoreBoard.seticon(item, item2)
        self.tboard.start()

    def exit(
        self
    ):  # it's an option for users to pick to exit. It'll automatically get connected to the closeEvent method down below.
        self.close()

        # CLOSE EVENT METHOD FOR CLICKING THE 'X' BUTTON

    def closeEvent(
        self, event
    ):  # a window to pop up when the user wants to exit using 'X' button.
        # window asks the user if they're sure to exit and give them options to say yes, save or cancel.
        # selecting yes will close the app.
        # selecting save will get connected to the save method and check if user actually saved the file. If they didn't it won't close the application.
        # selecting cancel will ignore the request and keep the application open.
        close = QMessageBox()
        close.setWindowTitle("Exit")
        close.setWindowIcon(QIcon("./img/exit.png"))
        close.setText("Are you sure you want to quit?\n")
        close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = close.exec()
        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def rules(self):
        help = QMessageBox()
        help.setWindowTitle("Rules")
        help.setWindowIcon(QIcon("./img/checkers.png"))
        help.setText(
            "1) Each Player start with 12 pieces.\n 2) Pieces can only move diagonally and forward (only one square).\n 3) Captures are made by jumping over an enemy piece.\n 4) If you make a capture, you can keep playing.\n 5) A piece becomes a king if it reaches to the enemy side.\n 6) A king can move forwards and backwards.\n 7) A Player wins if the opponent runs out of time or if the Player captures all 12 enemy pieces in time.\n"
        )
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def pauseHelp(self):
        help = QMessageBox()
        help.setWindowTitle("Pause")
        help.setWindowIcon(QIcon("./img/pause.png"))
        help.setText(
            "This button allows you to pause the game once you started.\n")
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def playHelp(self):
        help = QMessageBox()
        help.setWindowTitle("Play")
        help.setWindowIcon(QIcon("./img/play.png"))
        help.setText(
            "This button allows you to start the game after you pause it.\n")
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def resetHelp(self):
        help = QMessageBox()
        help.setWindowTitle("Reset")
        help.setWindowIcon(QIcon("./img/reset.png"))
        help.setText(
            "This button allows you to reset the timers, the stats, and the position of the pieces.\n"
        )
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def exitHelp(self):
        help = QMessageBox()
        help.setWindowTitle("Exit")
        help.setWindowIcon(QIcon("./img/exit.png"))
        help.setText("This button allows you to exit the application.\n")
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def htpHelp(self):
        help = QMessageBox()
        help.setWindowTitle("How To Play")
        help.setWindowIcon(QIcon("./img/checkers.png"))
        help.setText(
            "If the score board says it's your turn, you can move by clicking on a piece. The application will highlight the available squares to move. You can pause, start, reset and exit by clicking the Game menu in the menu bar. Hope you'll enjoy it!\n"
        )
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()

    def about(self):
        help = QMessageBox()
        help.setWindowTitle("About")
        help.setWindowIcon(QIcon("./img/about.png"))
        help.setText(
            "This application is a Draughts game (aka Checkers) made by Ecem Oral 2929807 and Stefan Wirtz 2981467.\n"
        )
        help.setStandardButtons(QMessageBox.Ok)
        help = help.exec()
Ejemplo n.º 15
0
class Game:
    def __init__(self):
        # initializes game
        pygame.init()
        pygame.display.set_caption(settings.title)
        pygame.key.set_repeat(500, 100)
        self.seconds = 60
        self.minutes = 3
        pygame.time.set_timer(USEREVENT + 1,
                              1000)  # 1 second is 1000 milliseconds
        self.screen = pygame.display.set_mode((settings.w, settings.h))
        self.clock = pygame.time.Clock()
        self.sb = ScoreBoard(self, settings, self.screen)

        # for determning the map being used
        self.makeCopies()
        self.mapName = self.map1
        self.previousMapName = self.map1
        self.newMap = False
        self.new1()
        self.playerRestarts = False
        self.stillPlaying = True
        self.playerDone = False

        # for the timer
        self.clock = pygame.time.Clock()

    # takes the tile maps and converts them into arrays to read from
    def makeCopies(self):
        self.map1 = CopyMap("maps/copyMap.txt", settings)
        self.map2 = CopyMap("maps/copyUnderGroundMap.txt", settings)
        self.map3 = CopyMap("maps/copyMap2.txt", settings)
        self.map4 = CopyMap("maps/gameOver.txt", settings)
        self.map5 = CopyMap("maps/endScreen.txt", settings)

    # creates the tileMap/player locations/sets up camera
    def new1(self):
        self.wallGroup = Group()
        for row, tiles in enumerate(self.mapName.data):
            for col, tile in enumerate(tiles):
                gf.findWhichType(self, self.sb, tile, col, row, settings)
        self.camera = Camera(self.mapName.width, self.mapName.height, settings)

    # loads a new map if player reaches end of first map
    def new(self):
        for x in self.wallGroup:
            gf.findWhichMap(self, x, self.sb)
        if self.newMap:
            self.new1()
            self.newMap = False

    # draws the walls, characters, and player
    def draw(self, settings):
        if self.mapName != self.map4 and self.mapName != self.map2:
            self.screen.fill(settings.blue)
        else:
            self.screen.fill(settings.black)
        for x in self.wallGroup:
            self.screen.blit(x.image, self.camera.apply(x))
        self.screen.blit(self.newPlayer.image,
                         self.camera.apply(self.newPlayer))
        self.sb.showScore(self)
        pygame.display.flip()

    # checks events, updates any changes, draws events/changes
    # where the main game is ran- only stops if player finishes or loses
    def run(self, settings):
        self.playing = True
        settings.endingMovements = False
        while self.playing:
            self.new()
            gf.checkEvents(self, settings, self.sb, self.newPlayer,
                           self.wallGroup, USEREVENT)
            self.update()
            self.draw(settings)
            if self.playerRestarts:
                self.restartGame()

    # updates players movement; camera; and enemy movement
    def update(self):
        self.newPlayer.update(settings, self.wallGroup)
        self.camera.update(self.newPlayer)
        for x in self.wallGroup:
            if x.type == '5' or x.type == 'c':
                x.update(self.camera)

    # quits game
    def quit(self):
        pygame.quit()
        sys.exit()

    # restarts stats/restarts to first map
    def restartGame(self):
        self.makeCopies()
        self.sb.livesLeft = 3
        self.sb.coinsCollected = 0
        self.sb.score = 0
        self.seconds = 60
        self.minutes = 3
        self.mapName = self.map1
        self.previousMapName = self.map1
        self.newMap = True
        self.playerRestarts = False

    # end screen; if player finishes- either ends game or restarts
    def showEndScreen(self):
        self.mapName = self.map5
        self.new1()
        while self.stillPlaying:
            self.dt = self.clock.tick(settings.FPS) / 1000
            gf.checkEvents(self, settings, self.sb, self.newPlayer,
                           self.wallGroup, USEREVENT)
            self.update()
            self.draw(settings)
            if self.playerRestarts == True:
                self.stillPlaying = False
            elif self.playerDone == True:
                self.stillPlaying = False
Ejemplo n.º 16
0
class DiedMenu:
    def __init__(self, SM, player):
        self.sm = SM
        self.player = player
        self.clock = pygame.time.Clock()
        self.gameObjects = []
        self.addbackground()
        self.retry = False
        self.scoreBoard = ScoreBoard()

    def addbackground(self):
        self.gameObjects = []
        for x in range(16):
            for y in range(9):
                self.gameObjects.append(BackWall((x, y)))
                self.gameObjects[-1].display = True

    def display(self):
        self.firstMenu()
        while not self.retry:
            tick = self.clock.tick(60)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    #test if we clicked a button
                    for obj in self.gameObjects:
                        if obj.rect.collidepoint(
                                event.pos
                        ) and obj.__class__.__name__ == 'Button':
                            obj.click()
            self.sm.displayElements(self.gameObjects)
        self.retry = False

    def firstMenu(self):
        self.addbackground()
        self.gameObjects.append(
            DisplayableElement(aggregateAnim('sprites/menu/', 'you died'),
                               0.001))
        self.gameObjects[-1].moveto((530, 140))
        self.gameObjects.append(
            Button((300, 440), 'sprites/menu/', 'retry', self.retryMenu))
        self.gameObjects.append(
            Button((700, 440), 'sprites/menu/', 'submit', self.submitMenu))
        self.gameObjects.append(
            Button((512, 300), 'sprites/menu/', 'credits', self.credits))

    def retryMenu(self):
        self.addbackground()
        #add text: choose your upgrades
        self.gameObjects.append(
            TextElement('Choose your upgrades before starting over!',
                        'Calibri', 40))
        self.gameObjects[-1].moveto((540, 140))
        self.gameObjects.append(
            TextElement(str(self.player.score), 'Calibri', 30))
        self.gameObjects[-1].moveto((540, 170))
        #add text: score
        self.gameObjects.append(
            Button((250, 270), 'sprites/skills/', 'skil - rapid',
                   self.upgradeSpeed))
        self.gameObjects.append(
            TextElement(str(self.player.upgrades.walkingSpeed * 1000),
                        'Calibri', 20))
        self.gameObjects[-1].moveto((250, 320))
        self.gameObjects.append(
            Button((380, 270), 'sprites/skills/', 'skill - attack',
                   self.upgradeAtk))
        self.gameObjects.append(
            TextElement(str(self.player.upgrades.attackMultiplier * 500),
                        'Calibri', 20))
        self.gameObjects[-1].moveto((380, 320))
        if not self.player.upgrades.earPods:
            self.gameObjects.append(
                Button((470, 270), 'sprites/skills/', 'skill - earpods',
                       self.upgradeEarpods))
            self.gameObjects.append(TextElement(str(2000), 'Calibri', 20))
            self.gameObjects[-1].moveto((470, 320))

        self.gameObjects.append(
            Button((610, 270), 'sprites/skills/', 'skill - resistance',
                   self.upgradeRes))
        self.gameObjects.append(
            TextElement(str(1 / self.player.upgrades.resistance), 'Calibri',
                        20))
        self.gameObjects[-1].moveto((610, 320))
        self.gameObjects.append(
            Button((770, 270), 'sprites/skills/', 'skill - saut',
                   self.upgradeJump))
        self.gameObjects.append(
            TextElement(str(self.player.upgrades.jumpingHeight * 500),
                        'Calibri', 20))
        self.gameObjects[-1].moveto((770, 320))
        #if not upgraded yeet
        if not self.player.upgrades.heavyHit:
            self.gameObjects.append(
                Button((850, 270), 'sprites/skills/', 'skills- coup fort',
                       self.upgradeheavyHit))
            self.gameObjects.append(TextElement(str(1000), 'Calibri', 20))
            self.gameObjects[-1].moveto((850, 320))

        self.gameObjects.append(
            Button((540, 440), 'sprites/menu/', 'retry', self.retryForReal))

    def upgradeSpeed(self):
        self.player.upgrades.buyWalkingSpeed(self.player)
        self.retryMenu()

    def upgradeAtk(self):
        self.player.upgrades.buyAttack(self.player)
        self.retryMenu()

    def upgradeEarpods(self):
        self.player.upgrades.buyEarPods(self.player)
        self.retryMenu()

    def upgradeRes(self):
        self.player.upgrades.buyResistance(self.player)
        self.retryMenu()

    def upgradeJump(self):
        self.player.upgrades.buyJumpingHeight(self.player)
        self.retryMenu()

    def upgradeheavyHit(self):
        self.player.upgrades.buyHeavyHit(self.player)
        self.retryMenu()

    def retryForReal(self):
        self.retry = True

    def submitMenu(self):
        self.addbackground()
        self.gameObjects.append(TextElement('High Scores:', 'Calibri', 40))
        self.gameObjects[-1].moveto((512, 25))
        self.gameObjects.append(
            Button((512, 75), 'sprites/menu/', 'retry', self.retryForReal))
        self.scoreBoard.ajouterScore(self.player.score)
        self.player.score = 0
        self.player.upgrades = Upgrades()
        i = 0
        for score in self.scoreBoard.scores:
            i += 1
            self.gameObjects.append(
                TextElement(score[0] + '       ' + str(score[1]), 'Calibri',
                            20))
            self.gameObjects[-1].moveto((512, 100 + (i * 20)))

    def credits(self):
        self.addbackground()
        self.gameObjects.append(TextElement('A Game by : GZEN', 'Calibri', 40))
        self.gameObjects[-1].moveto((512, 20))
        self.gameObjects.append(
            TextElement('Lead Programming : Olivier Senn', 'Calibri', 20))
        self.gameObjects[-1].moveto((512, 40))
        self.gameObjects.append(
            TextElement(
                'Programming : Yannis Lachkar, Roxane Deflandre, Tom Arnaud',
                'Calibri', 20))
        self.gameObjects[-1].moveto((512, 60))
        self.gameObjects.append(
            TextElement(
                'Game Design : Olivier Senn, Yannis Lachkar, Roxane Deflandre, Tom Arnaud',
                'Calibri', 20))
        self.gameObjects[-1].moveto((512, 80))
        self.gameObjects.append(
            TextElement('Level Design : Tom Arnaud', 'Calibri', 20))
        self.gameObjects[-1].moveto((512, 100))
        self.gameObjects.append(
            TextElement('Lead Graphism / Animations: Roxane Deflandre',
                        'Calibri', 20))
        self.gameObjects[-1].moveto((512, 120))
        self.gameObjects.append(
            TextElement('Additional Graphism / Animations : Tom Arnaud',
                        'Calibri', 20))
        self.gameObjects[-1].moveto((512, 140))
        self.gameObjects.append(
            TextElement('Cover : Yannis Lachkar, Roxane Deflandre', 'Calibri',
                        20))
        self.gameObjects[-1].moveto((512, 160))
        self.gameObjects.append(
            TextElement('Music : Tom Arnaud', 'Calibri', 20))
        self.gameObjects[-1].moveto((512, 180))
        self.gameObjects.append(
            TextElement('Lead Bodge Engineer : Olivier Senn (all of it)',
                        'Calibri', 20))
        self.gameObjects[-1].moveto((512, 200))
        self.gameObjects.append(
            TextElement(
                'Lead Pizza Eater : Yannis Lachkar (enough (for 3 people))',
                'Calibri', 20))
        self.gameObjects[-1].moveto((512, 220))
        self.gameObjects.append(
            TextElement(
                'Lead PyxelEdit Master : Roxane Deflandre (5687 Pixels)',
                'Calibri', 20))
        self.gameObjects[-1].moveto((512, 240))
        self.gameObjects.append(
            TextElement('Lead Coffee Drinker : Tom Arnaud (15L)', 'Calibri',
                        20))
        self.gameObjects[-1].moveto((512, 260))
        self.gameObjects.append(
            Button((540, 440), 'sprites/menu/', 'retry', self.firstMenu))
Ejemplo n.º 17
0
class Draughts(QMainWindow):
    """
    This class allows to create the board for the game and the scoreboard to display all information.
    """
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        """
        Initilization of the game board and the score board.

        :return: Nothing
        """
        # Initialization of the board class
        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)

        # Initialization of the ScoreBoard class
        self.scoreBoard = ScoreBoard(self.tboard)
        self.tboard.setScoreBoard(self.scoreBoard)

        # Set the score board in a dockwidget at the right of the window
        self.addDockWidget(Qt.RightDockWidgetArea, self.scoreBoard)

        # Initialization of the status bar
        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)

        # Start the class Board
        self.tboard.start()
        self.gameToolbar()

        # Initialization of the windows
        self.resize(900, 800)
        self.setFixedSize(self.size())
        self.center()
        self.setWindowTitle('Checkers')
        self.show()

    def center(self):
        """
        Centers the window on the screen
        :return: Nothing
        """

        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def gameToolbar(self):
        """
        This function allows to create the Menubar.
        It contains th Game, the View, the Help and the Exit menu.
        :return: Nothing
        """
        # Declaration of each menu in the menu bar.
        mainMenu = self.menuBar()
        self.resetMenu = mainMenu.addMenu(" Game")
        self.aiMenu = mainMenu.addMenu(" AI")
        self.viewMenu = mainMenu.addMenu(" View")
        self.helpMenu = mainMenu.addMenu(" Help")
        self.exitMenu = mainMenu.addMenu(" Exit")

        # Initialization of each menu in the menu bar.
        self.gameSettings()
        self.gameAIEasy()
        self.gameAIMedium()
        self.gameAIHard()
        self.pauseGame()
        self.viewSettings()
        self.helpSettings()
        self.exitSettings()

    def gameSettings(self):
        """
        This function allows to reset the game.
        The shortcut is the following: Ctrl+R
        If the user click on this menu, the resetGame funtion will be call.

        :return: Nothing
        """
        resetAction = QAction(QIcon(CLEAR_IMAGE), "Reset", self)
        resetAction.setShortcut("Ctrl+R")
        self.resetMenu.addAction(resetAction)
        resetAction.triggered.connect(self.resetGame)

    def gameAIEasy(self):
        """
        This function allows to create a game against an artificial intelligence.
        The shortcut is the following: Ctrl+A
        If the user click on this menu, the AIPlayer funtion will be call.

        :return: Nothing
        """
        aiAction = QAction(QIcon(ROBOT_EASY), "Play against an easy AI", self)
        aiAction.setShortcut("Ctrl+A")
        self.aiMenu.addAction(aiAction)
        aiAction.triggered.connect(self.AIPlayerE)

    def gameAIMedium(self):
        """
        This function allows to create a game against an artificial intelligence.
        The shortcut is the following: Ctrl+A
        If the user click on this menu, the AIPlayer funtion will be call.

        :return: Nothing
        """
        aiAction = QAction(QIcon(ROBOT_MEDIUM), "Play against an medium AI",
                           self)
        aiAction.setShortcut("Ctrl+Q")
        self.aiMenu.addAction(aiAction)
        aiAction.triggered.connect(self.AIPlayerM)

    def gameAIHard(self):
        """
        This function allows to create a game against an artificial intelligence.
        The shortcut is the following: Ctrl+A
        If the user click on this menu, the AIPlayer funtion will be call.

        :return: Nothing
        """
        aiAction = QAction(QIcon(ROBOT_HARD), "Play against an hard AI", self)
        aiAction.setShortcut("Ctrl+W")
        self.aiMenu.addAction(aiAction)
        aiAction.triggered.connect(self.AIPlayerH)

    def pauseGame(self):
        """
        This function allows set the game in pause.
        The shortcut is the following: Ctrl+P
        If the user click on this menu, the pause funtion will be call.

        :return: Nothing
        """
        resetAction = QAction(QIcon(PAUSE_IMAGE), "Pause / Continue", self)
        resetAction.setShortcut("Ctrl+P")
        self.resetMenu.addAction(resetAction)
        resetAction.triggered.connect(self.pause)

    def viewSettings(self):
        """
        This function allows to view the status of the game.
        The shortcut is the following: Ctrl+V
        If the user click on this menu, the viewStatus funtion will be call.

        :return: Nothing
        """

        resetAction = QAction(QIcon(STATUS_IMAGE), "View status", self)
        resetAction.setShortcut("Ctrl+V")
        self.viewMenu.addAction(resetAction)
        resetAction.triggered.connect(self.viewStatus)

    def helpSettings(self):
        """
        This function allows to display the rules of the game.
        The shortcut is the following: Ctrl+H
        If the user click on this menu, the help funtion will be call.

        :return: Nothing
        """

        helpAction = QAction(QIcon(HELP_IMAGE), "Help", self)
        helpAction.setShortcut("Ctrl+H")
        self.helpMenu.addAction(helpAction)
        helpAction.triggered.connect(self.help)

    def exitSettings(self):
        """
        This function allows to exit the checkers game.
        The shortcut is the following: Ctrl+E

        :return: Nothing
        """

        exitAction = QAction(QIcon(EXIT_IMAGE), "Exit", self)
        exitAction.setShortcut("Ctrl+E")
        self.exitMenu.addAction(exitAction)
        exitAction.triggered.connect(qApp.quit)

    def resetGame(self):
        """
        This function will initialize the game and the score board.

        :return: Nothing
        """
        # Initialization of the game
        self.tboard.init()
        self.tboard.start()
        # Initialization of the scoreBoard
        self.scoreBoard.setAI(False)
        self.scoreBoard.updateUI()
        self.tboard.setScoreBoard(self.scoreBoard)

    def pause(self):
        """
        This function will call the pause function in the Board class to set the game in pause.

        :return: Nothing
        """
        self.tboard.pause()

    def AIPlayerE(self):
        """
        Function to allows the player to play against an easy AI

        :return: Nothing
        """
        self.tboard.isAI = True
        self.scoreBoard.setAI(True)
        self.tboard.aiDifficulties = 1

    def AIPlayerM(self):
        """
        Function to allows the player to play against an medium AI

        :return: Nothing
        """
        self.tboard.isAI = True
        self.scoreBoard.setAI(True)
        self.tboard.aiDifficulties = 2

    def AIPlayerH(self):
        """
        Function to allows the player to play against an hard AI

        :return: Nothing
        """
        self.tboard.isAI = True
        self.scoreBoard.setAI(True)
        self.tboard.aiDifficulties = 3

    def viewStatus(self):
        """
        This function allows to display the status of the game in a QMessageBox.

        :return: Nothing
        """
        title = "Game status "
        message = self.tboard.status
        QMessageBox.about(self, title, message)
        self.show()

    def help(self):
        """
        This function display a QMessageBox. This box help the user to know what the application
        exactyly doing.
        Indeed, it contains rules of the game.

        :return: Nothing
        """
        title = "Help"
        message = "It's a checker game.\n" \
                  "The rules:\n" \
                  "Moves are allowed only on the dark squares, so pieces always move diagonally.\n" \
                  "Single pieces are always limited to forward moves.\n" \
                  "A piece making a move only on one square. A piece making a capturing move leaps over one of the opponent's pieces,\n" \
                  "landing in a straight diagonal line on the other side.\n" \
                  "Only one piece may be captured in a single jump; however, multiple jumps are allowed during a single turn.\n" \
                  "When a piece is captured, it is removed from the board.\n" \
                  "If a player is able to make a capture, there is no option; the jump must be made.\n" \
                  "If more than one capture is available, the player is free to choose whichever he or she prefers.\n" \
                  "When a piece reaches the furthest row from the player who controls that piece, it is crowned and becomes a king.\n" \
                  "One of the pieces which had been captured is placed on top of the king so that it is twice as high as a single piece.\n" \
                  "Kings are limited to moving diagonally but may move both forward and backward.\n" \
                  "Kings may combine jumps in several directions, forward and backward, on the same turn.\n" \
                  "Single pieces may shift direction diagonally during a multiple capture turn, but must always jump forward.\n"

        QMessageBox.about(self, title, message)
        self.show()
Ejemplo n.º 18
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((1200,1000))
    pygame.display.set_caption("test app")
    
    score_board = ScoreBoard()
    map = Map("./stage.txt")
    block_group = map.get_blocks()
    cookie_group = map.get_cookies()
    powercookie_group = map.get_powercookies()
    enemy_group = map.get_enemys()
    # enemy = Enemy([416,416],block_group)
    # enemy_group = pygame.sprite.Group(enemy)
    packman = Packman([32,32],enemy_group, block_group, cookie_group,powercookie_group, score_board)
    my_group = pygame.sprite.Group(packman)
    
    add_enemy_timer = 0
    enemy_state=[True,True,True,True,True]

    GAME_STATE = 1
    
    clock = pygame.time.Clock()
    
    screen.fill((0,0,0))
    
    while True:
        
        screen.fill((0,0,0))
        for event in pygame.event.get():
            if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
        if GAME_STATE == 1:
            my_group.update()
            my_group.draw(screen)
            p_x,p_y = packman.get_position()
            enemy_group.update(p_x,p_y,packman.immune_state)
            enemy_group.draw(screen)
            cookie_group.update(p_x,p_y)
            powercookie_group.update(p_x,p_y)
            block_group.draw(screen)
            cookie_group.draw(screen)
            powercookie_group.draw(screen)
            score_board.draw(screen)

            if len(enemy_group.sprites()) < 5:
                enemy_group.add(Enemy((352,320),block_group))
            
            if all(enemy_state):
                enemy_list = enemy_group.sprites()
                enemy_list[0].wait_state = False

            for index,enemy in enumerate(enemy_group):
                enemy_state[index] = enemy.wait_state

            if add_enemy_timer != 0 and add_enemy_timer % 1500 == 0:
                enemy_list = enemy_group.sprites()
                for index,enemy in enumerate(enemy_state):
                    if enemy == True:
                        enemy_list[index].wait_state = False
                        break

            add_enemy_timer += 1

            if packman.dead_state == True:
                GAME_STATE = 2

            if len(cookie_group.sprites()) == 0:
                GAME_STATE =3

        elif GAME_STATE == 2:
            gameover_font = pygame.font.SysFont(None, 80)
            gameover = gameover_font.render("GAME OVER", False, (255,0,0))
            screen.blit(gameover, ((400, 300)))

        elif GAME_STATE == 3:
            gameclear_font = pygame.font.SysFont(None, 80)
            gameclear = gameclear_font.render("GAME CLEAR", False, (255,255,255))
            screen.blit(gameclear, ((400, 300)))
        pygame.display.update()
        clock.tick(FPS)
Ejemplo n.º 19
0
#initialize game
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('BackSound.mp3')
pygame.mixer.music.set_volume(0.2)  # volume of the son
pygame.mixer.music.play(-1)

#Window Size
(winX, winY) = (800, 600)
screen = pygame.display.set_mode((winX, winY))

#clock used for fps
clock = pygame.time.Clock()

#initialzing the Objects
scoreB = ScoreBoard(0, 0)
score = 0
scoreB.setScore(score)
bg = SpaceBackground(screen, 2, 0)
p1 = player(300, 410, 64, 64)
b1 = projectile(5, 8, 32, 32, 6, (250, 250, 250), -1)
bullets = []

running = True
while running:
    #FPS
    clock.tick(100)

    screen.fill((24, 24, 24))

    #drawing ScoreBoard