コード例 #1
0
ファイル: jetFighter.py プロジェクト: bd3young/pygame
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Jet Fighter")

        # creat an instance to store game stats
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.jet = Jet(self)
        self.bullets = pygame.sprite.Group()
        self.planes = pygame.sprite.Group()

        self.createFleet()

        # make play button
        self.playButton = Button(self, "play")

        # Set the background color.
        self.bgColor = (0, 230, 0)
コード例 #2
0
def runGame():
    # Initialize game, settings and screen object
    pygame.init()
    drSettings = Settings()
    screen = pygame.display.set_mode(
        (drSettings.screenWidth, drSettings.screenHeight))
    pygame.display.set_caption("Drag Race")
    totalTime = 0

    # Make the car
    car = Car(drSettings, screen)

    # Initialize the timer, gear text and speed
    hud = HeadUpDisplay(drSettings, screen, totalTime, car) 

    # Store the game statistics
    stats = GameStats()

    # Start the main loop for the game
    while True:
        # Check for keypresses
        gf.checkEvents(car, stats)

        # Update the game active state
        if not car.onScreen:
            stats.gameActive = False

        if stats.gameActive:
            # Update the position of the car and the hud
            car.update() 
            hud.update(stats.totalTime, car)
            stats.totalTime += drSettings.timeIncrement

        # Update the screen
        gf.updateScreen(drSettings, screen, car, hud)
コード例 #3
0
 def __init__(self):
     pygame.init()
     self.settings = Settings()
     self.screen = pygame.display.set_mode(
         (self.settings.screen_width, self.settings.screen_height))
     self.ship = Ship(self.screen, self.settings.ship_speed)
     pygame.display.set_caption("Alien invasion")
     self.bullets = Group()
     self.aliens = Group()
     self.stats = GameStats(self.settings)
コード例 #4
0
 def __init__(self):
     pygame.init()
     self.settings = Settings()
     self.screen = pygame.display.set_mode((self.settings.screenWidth,self.settings.screenHeight))
     pygame.display.set_caption("Alien invasion... Sideways")
     self.stats = GameStats(self)
     self.sb = Scoreboard(self)
     self.ship = SpaceShip(self)
     self.bullets = pygame.sprite.Group()
     self.aliens = pygame.sprite.Group()
     self.bg = pygame.image.load("images/bg.bmp")
     self.playButton = Button(self,"Play",50,50)
     self.practiceButton = Button(self,"Practice",100,100)
コード例 #5
0
def Game():
    pygame.init()

    gamesettings = Settings()
    screen = pygame.display.set_mode(
        (gamesettings.screen_width, gamesettings.screen_height))
    pygame.display.set_caption("Pacman Portal")

    # Start screen
    startScreen = StartScreen(screen, gamesettings)
    showgamestats = GameStats(screen, gamesettings)

    # Grouping blocks and pellets
    blocks = Group()
    powerpills = Group()
    shield = Group()
    portal = Group()

    thepacman = Pacman(screen, gamesettings)

    # Making the ghosts
    redghost = Ghosts(screen, "red")
    cyanghost = Ghosts(screen, "cyan")
    orangeghost = Ghosts(screen, "orange")
    pinkghost = Ghosts(screen, "pink")

    startScreen.makeScreen(screen)
    gf.readFile(screen, blocks, shield, powerpills, portal)

    screen.fill(BLACK)
    while True:
        screen.fill(BLACK)
        showgamestats.blitstats()
        gf.check_events(thepacman)
        gf.check_collision(thepacman, blocks, powerpills, shield)
        thepacman.update()
        for block in blocks:
            block.blitblocks()
        for theshield in shield:
            theshield.blitshield()
        for pill in powerpills:
            pill.blitpowerpills()
        for theportal in portal:
            theportal.blitportal()
        thepacman.blitpacman()
        redghost.blitghosts()
        cyanghost.blitghosts()
        orangeghost.blitghosts()
        pinkghost.blitghosts()

        pygame.display.flip()
コード例 #6
0
def runGame():
    # Initializes game and window
    pygame.init()
    settings = Settings()
    
    screen = pygame.display.set_mode((settings.screenWidth, settings.screenHeight))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(screen, settings)
    bullets = Group()
    aliens = Group()
    stats = GameStats(settings)
    scoreboard = Scoreboard(settings=settings, stats=stats, screen=screen)
    playButton = Button(settings = settings, screen = screen, text = "Play")
    
    gameFunctions = GameFunctions(settings, screen, ship, bullets, playButton, stats, aliens, scoreboard)
    gameFunctions.createFleet()
            
    while True:
        gameFunctions.checkEvents()
        
        if stats.gameActive:
            ship.update()
            gameFunctions.updateBullets()
            gameFunctions.updateAliens()
            
        gameFunctions.updateScreen()
コード例 #7
0
ファイル: gameController.py プロジェクト: ntsdav561/jaialai
 def __init__(self, player_list,gameType, pwin_dict):
     self.topScoreCard = ScoreCard(player_list)
     self.topPlayerQueue = PlayerQueue(player_list)
     self.gameType = gameType
     self.gameStats = GameStats(player_list)
    
     self.pwin_dict = pwin_dict
コード例 #8
0
def run_game():
    pygame.init()
    setting = Setting()
    stats = GameStats(setting)
    screen = pygame.display.set_mode((setting.width, setting.height))
    pygame.display.set_caption("Alien  Invasion")

    ship = Ship(screen, setting)
    bullets = Group()
    aliens = Group()  # Alien(setting,screen)
    gf.creat_fleet(setting, screen, aliens, ship)
    playbutton = Button(screen, setting, 'play')
    board = Board(setting, screen, stats)

    while True:
        gf.check_events(aliens, playbutton, stats, setting, screen, ship,
                        bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullet(setting, screen, ship, bullets, aliens, board,
                             stats)
            gf.update_aliens(setting, screen, ship, bullets, aliens, stats,
                             board)
        #print(len(aliens))444
        gf.update_window(setting, screen, ship, bullets, aliens, playbutton,
                         stats, board)
コード例 #9
0
def run_game():
    #获取游戏参数
    game_settings = Settings()

    #初始化游戏
    pygame.init()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("飞机大战")

    #初始化游戏控制
    gs = GameStats(game_settings, screen)

    #定义玩家
    player = Fighter(game_settings, screen, gs.img_role)

    #存储敌机
    enemies1 = pygame.sprite.Group()
    enemies_down = pygame.sprite.Group()

    #存储补给
    supplies = pygame.sprite.Group()

    #定义时钟
    clock = pygame.time.Clock()

    while True:
        # 控制游戏帧数,表示每秒循环60次
        clock.tick(60)

        if gs.bStarted and not gs.bPaused and not gs.bOver and not gs.bWin:
            #发射子弹
            player.shoot(gs)

            #生成敌机
            Enemy.discover(game_settings, gs, enemies1)

            #生成补给
            Supply.discover(game_settings, gs, supplies)

            #更新敌机并检测碰撞
            cf.update_enemies(screen, enemies1, enemies_down, player,
                              gs.sound_gameover)

            #更新子弹并检测碰撞
            cf.update_bullets(game_settings, player, enemies1, enemies_down,
                              supplies)

            #更新补给并检测碰撞
            cf.update_supplies(game_settings, gs, player, enemies1,
                               enemies_down, supplies)

        #更新画面
        cf.update_screen(game_settings, gs, screen, player, enemies1,
                         enemies_down, supplies)

        #鼠标和键盘事件处理
        cf.check_events(gs, player)
コード例 #10
0
 def __init__(self):
     pygame.init()
     config = ConfigParser()  # parse settings file
     config.read('settings.ini')
     screen_size = (int(config['screen_settings']['width']),
                    int(config['screen_settings']['height']))
     self.screen = pygame.display.set_mode(screen_size)
     self.stats = GameStats(self.screen)
     pygame.display.set_caption(config['game_settings']['title'])
     self.clock = pygame.time.Clock()  # clock for limiting fps
     self.game_objects = None
     self.tmx_data = None
     self.map_layer = None
     self.map_group = None
     self.player_spawn = None
     self.mario = None
     self.timer = None
     self.time_warn = None
     self.last_tick = 0
     self.score = 0
     self.lives = 3
     self.coins = 0
     self.SFX = {
         '1-up': pygame.mixer.Sound('audio/1-Up.wav'),
         'warning': pygame.mixer.Sound('audio/Time-Warning.wav')
     }
     self.init_world()
     self.mario = Mario(self.game_objects, self.map_layer, self.map_group,
                        self.screen)
     self.prep_enemies()
     self.mario.rect.x, self.mario.rect.y = self.player_spawn.x, self.player_spawn.y
     self.map_layer.center(
         (self.mario.rect.x, self.mario.rect.y))  # center camera
     self.map_layer.zoom = 0.725  # camera zoom
     self.map_group.add(self.mario)  # add test sprite to map group
     self.paused = False
     # print(self.map_layer.view_rect.center)
     # action map for event loop
     self.paused = False
     self.game_active = False
     self.game_won = False
     self.menu = Menu(self.screen)
     self.action_map = {pygame.KEYDOWN: self.set_paused}
     print(self.map_layer.view_rect.center)
コード例 #11
0
    def __init__(self):
        """Initialize the game, and create game resources"""
        pygame.init()
        self.settings = Settings()

        #(self.settings.screen_width,self.settings.screen_height)
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")

        #Create an instace to store game statistics
        #and create a scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        #Make the pay button
        self.play_button = Button(self, "Play")
コード例 #12
0
ファイル: main.py プロジェクト: Kaine-R/AlienKaineR
def run_game():

    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("images/music.mp3")
    pygame.mixer.music.play(-1, 130.0)
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Aliens")
    stats = GameStats(ai_settings)
    playButton = Button(ai_settings, screen, "Play")
    highScore = HighScores(screen, ai_settings)
    score = Score(ai_settings, screen, "Wave#: " + str(stats.waveNumber),
                  stats)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    stars = Group()
    badBullets = Group()
    barriers = Group()
    gf.makeBarriers(barriers, screen, ai_settings)
    gf.createFleet(ai_settings, screen, ship, aliens)
    highScore.prepScores()

    screen.fill(ai_settings.bg_color)
    while True:
        screen.fill(ai_settings.bg_color)
        gf.updateBackground(ai_settings, screen, stars)
        gf.drawBarrier(barriers)
        gf.check_events(ai_settings, screen, ship, stats, playButton, aliens,
                        bullets, barriers)
        gf.updateScreen(ai_settings, screen, stats, ship, aliens, bullets,
                        playButton, score, badBullets)

        if stats.gameActive:
            ship.update()
            gf.barriersCollide(barriers, bullets)
            gf.updateBullets(ai_settings, screen, stats, ship, aliens, bullets,
                             badBullets, highScore, barriers)
            gf.updateAliens(ai_settings, stats, screen, ship, aliens, bullets,
                            highScore, badBullets)
            gf.badShotting(aliens, badBullets, ai_settings, screen)
        else:
            highScore.prepScores()
            highScore.drawScores()

        pygame.display.flip()
コード例 #13
0
def run_game():
    '''背景 平台初始化'''
    pygame.init()
    ai_settings = Settings()
    #screen = pygame.display.set_mode((1200,800))
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("game play")
    '''开始按钮'''
    play_button = Button(ai_settings, screen, "play")
    '''存储游戏的计分板'''
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    '''游戏背景颜色'''
    bg_color = (230, 230, 230)
    '''创建飞船子弹怪物'''
    ship = Ship(ai_settings, screen)
    # monster = Alien(ai_settings, screen)
    # bullets = Bullet(ai_settings, screen, ship)
    # bullets = pygame.sprite.Group()
    bullets = Group()
    #aliens = pygame.sprite.Group()
    aliens = Group()
    '''创造舰队'''
    ck.create_fleet(ai_settings, screen, ship, aliens)

    #game_loop
    while True:
        ck.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            ck.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            ck.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        # for event in pygame.event.get():
        #     if event.type == pygame.QUIT:
        #         sys.exit()
        # screen.fill(ai_settings.bg_color)
        # ship.blitme()
        # pygame.display.flip()
        ck.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
コード例 #14
0
 def __init__(self, dict_info={}):
     if dict_info != {}:
         if "championId" in dict_info.keys():
             self.championId = dict_info["championId"]
         if "highestAchievedSeasonTier" in dict_info.keys():
             self.highestAchievedSeasonTier = dict_info[
                 "highestAchievedSeasonTier"]
         if "participantId" in dict_info.keys():
             self.participantId = dict_info["participantId"]
         if "spell1Id" in dict_info.keys():
             self.spell1Id = dict_info["spell1Id"]
         if "spell2Id" in dict_info.keys():
             self.spell2Id = dict_info["spell2Id"]
         if "teamId" in dict_info.keys():
             self.teamId = dict_info["teamId"]
         if "stats" in dict_info.keys():
             self.stats = GameStats(dict_info["stats"])
         if "timeline" in dict_info.keys():
             self.timeline = TimeLine(dict_info["timeline"])
コード例 #15
0
ファイル: alienInvasion.py プロジェクト: varunk08/pie
def runGame():
    pygame.init()
    aiSettings = Settings()
    screen = pygame.display.set_mode((aiSettings.screenWidth, aiSettings.screenHeight))
    pygame.display.set_caption("Alien Invasion")
    stats = GameStats(aiSettings)
    ship = Ship(aiSettings, screen)
    bullets = Group()
    aliens = Group()
    gf.createFleet(aiSettings, screen, aliens, ship)
    playButton = Button(aiSettings, screen, "Play")
    sb = Scoreboard(aiSettings, screen, stats)

    while True:
        gf.checkEvents(aiSettings, screen, ship, bullets, aliens, stats, playButton, sb)
        if stats.gameActive:
            ship.update()
            gf.updateBullets(aiSettings, bullets, aliens, screen, ship, stats, sb)
            gf.updateAliens(aiSettings, stats, screen, aliens, bullets, ship, sb)
        gf.updateScreen(aiSettings, screen, ship, bullets, aliens, stats, playButton, sb)
コード例 #16
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()
コード例 #17
0
ファイル: fight_game.py プロジェクト: zuahua/pythonGame
def run_game():
    # 初始化游戏并创建屏幕对象
    pygame.init()

    # 使用Settings类
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Fight Warriors")
    # 创建Play按钮
    play_button = Button(ai_settings, "Play", screen)

    # 创建游戏玩家
    player = Player(screen, ai_settings)

    # 创建存储子弹的编组
    bullets = Group()

    # 创建敌人编组
    enemies = Group()
    # 创建敌人群
    gf.creat_fleet(ai_settings, screen, enemies, player)

    # 实例化游戏统计信息
    stats = GameStats(ai_settings)
    # 创建分数实例
    score_board = Scoreboard(ai_settings, screen, stats)

    # 开始游戏主循环
    while True:
        gf.check_event(player, ai_settings, screen, bullets, stats,
                       play_button, enemies, score_board)
        if stats.active_game:
            player.update()
            gf.update_bullets(bullets, enemies, ai_settings, screen, player,
                              stats, score_board)
            gf.update_enemies(enemies, ai_settings, player, stats, screen,
                              bullets, score_board)
        gf.update_screen(ai_settings, screen, player, bullets, enemies,
                         play_button, stats, score_board)
コード例 #18
0
def run_game():

    pygame.init()  # Initialize game and create a screen object.

    game_settings = Settings()  # Make it constructor.Make an instance.

    screen = pygame.display.set_mode(
        (game_settings.screen_width,
         game_settings.screen_height))  # Set screen size
    alien = Alien(game_settings, screen)  # Make Alien.
    pygame.display.set_caption("Alien Shooter")

    # Make the Play button.
    play_button = Button(game_settings, screen, "Play")  # Make Button.

    ship = Ship(screen, game_settings)  # Make a a ship.

    stats = GameStats(
        game_settings)  # Create an instance to store game statistics.

    sb = ScoreBoard(game_settings, screen, stats)
    bullets = Group()  # Make a group of bullets.
    aliens = Group()  # # Make a group of aliens.

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

    # Start main loop for the game.
    while True:
        # Watch Keyboard and Mouse events.
        gf.check_events(ship, game_settings, screen, bullets, play_button,
                        stats, aliens, sb)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, aliens, game_settings, screen, ship,
                              stats, sb)  # Updating bullets.
            gf.update_aliens(game_settings, aliens, ship, stats, screen,
                             bullets, sb)  # Update aliens.
        # Updating or loading the screen.
        gf.update_screen(game_settings, screen, ship, bullets, aliens,
                         play_button, stats, sb)
コード例 #19
0
class Participants:
    championId = 0
    highestAchievedSeasonTier = ""
    participantId = 0
    spell1Id = 0
    spell2Id = 0
    stats = GameStats()
    teamId = 0
    timeline = TimeLine()

    def __init__(self, dict_info={}):
        if dict_info != {}:
            if "championId" in dict_info.keys():
                self.championId = dict_info["championId"]
            if "highestAchievedSeasonTier" in dict_info.keys():
                self.highestAchievedSeasonTier = dict_info[
                    "highestAchievedSeasonTier"]
            if "participantId" in dict_info.keys():
                self.participantId = dict_info["participantId"]
            if "spell1Id" in dict_info.keys():
                self.spell1Id = dict_info["spell1Id"]
            if "spell2Id" in dict_info.keys():
                self.spell2Id = dict_info["spell2Id"]
            if "teamId" in dict_info.keys():
                self.teamId = dict_info["teamId"]
            if "stats" in dict_info.keys():
                self.stats = GameStats(dict_info["stats"])
            if "timeline" in dict_info.keys():
                self.timeline = TimeLine(dict_info["timeline"])

    def __str__(self):
        return "Use 'print_participants_info' function"

    def print_participants_info(self, champions):
        print("ParticipantId:", self.participantId)
        print("Champion:", champions.getchampforid(self.championId), "(",
              self.championId, ")")
        print("Tier:", self.highestAchievedSeasonTier)
        print("Team:", team_str(self.teamId))
コード例 #20
0
def runGame():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screenWidth, ai_settings.screenHeight))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(ai_settings, screen)
    aliens = Group()
    bullets = Group()
    queenBees = Group()
    queenBullets = Group()
    stats = GameStats(ai_settings)

    sb = Scoreboard(ai_settings, screen, stats)
    gf.createFleet(ai_settings, screen, stats, sb, ship, aliens)

    playButton = Button(ai_settings, screen, "Play", 200, 50, 0)
    resumeButton = Button(ai_settings, screen, "Resume Game", 250, 50, 0)

    pygame.mixer.music.load('audioFiles/were going on a trip.wav')
    pygame.mixer.music.play(-1)

    # updates game every run through
    while True:
        gf.checkEvents(ai_settings, screen, stats, sb, playButton, ship,
                       aliens, bullets, queenBees, queenBullets)
        if stats.gameActive:
            ship.update()
            gf.updateAliens(ai_settings, screen, stats, sb, ship, aliens,
                            bullets, queenBees, queenBullets)
            gf.updateBullets(ai_settings, screen, stats, sb, ship, aliens,
                             bullets, queenBees, playButton, queenBullets)
            gf.updateQueenBeeBullets(ai_settings, screen, stats, sb, ship,
                                     aliens, bullets, queenBees, playButton,
                                     queenBullets)

        gf.updateScreen(ai_settings, screen, stats, sb, ship, bullets, aliens,
                        queenBees, queenBullets, playButton, resumeButton)
コード例 #21
0
def run_game():
	#Initializes the settings needed for pygame to run properly
	pygame.init()
	
	aiSettings = Settings()
	#Display mode called 'screen' is made, with 1200 x 800 dimensions
	#Screen is where the game elements are shown
	screen = pygame.display.set_mode(
		(aiSettings.screen_width,aiSettings.screen_height))
	pygame.display.set_caption("Alien Invasion")
	#Sets background colour
	
	stats = GameStats(aiSettings)
	sb = Scoreboard(aiSettings, screen, stats)
	
	
	#Makes a ship on screen
	ship = Ship(aiSettings,screen)
	#Bullets! - make a group called bullets
	bullets = Group()
	#Aliens are made
	aliens = Group()
	
	#Calls on the createFleet function
	gf.createFleet(aiSettings, screen, ship, aliens)
	
	playButton = Button(aiSettings, screen, "Click to Play")
	
	while True:
		gf.check_events(aiSettings, screen, stats, sb, playButton, ship, aliens, bullets)
		sb.showScore()
		if stats.game_active:
			ship.update()
			gf.updateBullets(aiSettings, screen, stats, sb, ship, aliens, bullets)
			gf.updateAliens(aiSettings, stats, screen, ship, sb, aliens, bullets)
	
		gf.update_screen(aiSettings, screen, stats, sb, ship, aliens, bullets, playButton)
コード例 #22
0
class Game:
    def __init__(self):
        pygame.init()
        config = ConfigParser()  # parse settings file
        config.read('settings.ini')
        screen_size = (int(config['screen_settings']['width']),
                       int(config['screen_settings']['height']))
        self.screen = pygame.display.set_mode(screen_size)
        self.stats = GameStats(self.screen)
        pygame.display.set_caption(config['game_settings']['title'])
        self.clock = pygame.time.Clock()  # clock for limiting fps
        self.game_objects = None
        self.tmx_data = None
        self.map_layer = None
        self.map_group = None
        self.player_spawn = None
        self.mario = None
        self.timer = None
        self.time_warn = None
        self.last_tick = 0
        self.score = 0
        self.lives = 3
        self.coins = 0
        self.SFX = {
            '1-up': pygame.mixer.Sound('audio/1-Up.wav'),
            'warning': pygame.mixer.Sound('audio/Time-Warning.wav')
        }
        self.init_world()
        self.mario = Mario(self.game_objects, self.map_layer, self.map_group,
                           self.screen)
        self.prep_enemies()
        self.mario.rect.x, self.mario.rect.y = self.player_spawn.x, self.player_spawn.y
        self.map_layer.center(
            (self.mario.rect.x, self.mario.rect.y))  # center camera
        self.map_layer.zoom = 0.725  # camera zoom
        self.map_group.add(self.mario)  # add test sprite to map group
        self.paused = False
        # print(self.map_layer.view_rect.center)
        # action map for event loop
        self.paused = False
        self.game_active = False
        self.game_won = False
        self.menu = Menu(self.screen)
        self.action_map = {pygame.KEYDOWN: self.set_paused}
        print(self.map_layer.view_rect.center)

    def retrieve_map_data(self, data_layer_name):
        # gets the map data
        try:
            data = self.tmx_data.get_layer_by_name(data_layer_name)
        except ValueError:
            data = []
        return data

    def init_world(self, map_name='world1', spawn='player', reset=True):
        # load the world level
        self.tmx_data, self.map_layer, self.map_group = load_world_map(
            'images/' + map_name + '.tmx', self.screen)
        self.player_spawn = self.tmx_data.get_object_by_name(
            spawn)  # get player spawn object from map data
        self.init_game_objects()
        self.map_layer.center((self.player_spawn.x, self.player_spawn.y))
        self.map_layer.zoom = 0.725  # camera zoom
        if self.mario:
            self.map_group.add(self.mario)
            self.prep_enemies()
            self.mario.reset(self.map_layer, self.game_objects, reset)
            self.mario.rect.x, self.mario.rect.y = self.player_spawn.x, self.player_spawn.y

    def handle_pipe(self):
        # mario going through
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_DOWN] is 1:
            for pipe in self.game_objects['pipes']:
                if (pipe.destination and self.mario.rect.left >= pipe.rect.left
                        and self.mario.rect.right <= pipe.rect.right):
                    self.init_world(map_name=pipe.destination,
                                    spawn=pipe.spawn,
                                    reset=False)
                    self.mario.x, self.mario.y = self.player_spawn.x, self.player_spawn.y
                    pygame.mixer.music.load('audio/' + str(pipe.music))
                    pygame.mixer.music.play(-1)
        elif keys_pressed[pygame.K_RIGHT] is 1:
            for pipe in self.game_objects['pipes']:
                if (pipe.destination and pipe.horiz
                        and self.mario.rect.right >= pipe.rect.left
                        and self.mario.rect.bottom <= pipe.rect.bottom):
                    self.init_world(map_name=pipe.destination,
                                    spawn=pipe.spawn,
                                    reset=False)
                    self.mario.x, self.mario.y = self.player_spawn.x, self.player_spawn.y
                    pygame.mixer.music.load('audio/' + str(pipe.music))
                    pygame.mixer.music.play(-1)

    def check_stage_clear(self):
        # checks if stage is cleared
        for rect in self.game_objects['win-zone']:
            if rect.colliderect(self.mario.rect):
                pygame.mixer.music.load('audio/End-Clear-Stage.wav')
                pygame.mixer.music.play()
                self.mario.flag_pole_sliding()
                self.game_won = True

    def init_game_objects(self):
        # creates the game objects
        self.game_objects = {
            'floors': [],
            'blocks': pygame.sprite.Group(),
            'q_blocks': pygame.sprite.Group(),
            'rubble': pygame.sprite.Group(),
            'coins': pygame.sprite.Group(),
            'pipes': pygame.sprite.Group(),
            'collide_objs': pygame.sprite.Group(
            ),  # for checking collisions with all collide-able objects
            'flag': pygame.sprite.Group(),
            'items': pygame.sprite.Group(),
            'koopa': pygame.sprite.Group(),
            'goomba': pygame.sprite.Group(),
            'win-zone': []
        }
        floor_data = self.retrieve_map_data('walls')
        block_data = self.retrieve_map_data('blocks')
        q_block_data = self.retrieve_map_data('q-blocks')
        pipe_data = self.retrieve_map_data('pipes')
        coin_data = self.retrieve_map_data('coins')
        flag_data = self.retrieve_map_data('flag')
        background = self.retrieve_map_data('decorations')
        for obj in floor_data:  # walls represented as pygame Rects
            self.game_objects['floors'].append(
                pygame.Rect(obj.x, obj.y, obj.width, obj.height))
        for block in block_data:
            if not block.properties.get('pipe', False):
                b_sprite = CoinBlock.coin_block_from_tmx_obj(
                    block, self.screen, self.map_group, self.game_objects)
            else:
                b_sprite = Block(block.x, block.y, block.image, self.screen)
            self.map_group.add(b_sprite)  # draw using this group
            self.game_objects['blocks'].add(
                b_sprite)  # check collisions using this group
            self.game_objects['collide_objs'].add(b_sprite)
        for q_block in q_block_data:
            q_sprite = QuestionBlock.q_block_from_tmx_obj(
                q_block, self.screen, self.map_group, self.game_objects)
            self.map_group.add(q_sprite)  # draw using this group
            self.game_objects['q_blocks'].add(
                q_sprite)  # check collisions using this group
            self.game_objects['collide_objs'].add(q_sprite)
        for coin in coin_data:
            c_sprite = Coin(coin.x, coin.y, self.screen)
            self.map_group.add(c_sprite)
            self.game_objects['coins'].add(c_sprite)
        for pipe in pipe_data:
            p_sprite = Pipe.pipe_from_tmx_obj(pipe, self.screen)
            self.map_group.add(p_sprite)  # draw using this group
            self.game_objects['pipes'].add(
                p_sprite)  # check collisions using this group
            self.game_objects['collide_objs'].add(p_sprite)
        for flag_part in flag_data:
            if flag_part.image:
                f_sprite = Block(flag_part.x, flag_part.y, flag_part.image,
                                 self.screen)
                self.map_group.add(f_sprite)  # draw using this group
                self.game_objects['flag'].add(
                    f_sprite)  # check collisions using this group
            else:
                self.game_objects['win-zone'].append(
                    pygame.Rect(flag_part.x, flag_part.y, flag_part.width,
                                flag_part.height))
        for bg in background:
            self.map_group.add(Decoration(bg.x, bg.y, bg.image))

    def prep_enemies(self):
        # prepares the enemy sprites
        enemy_spawn_data = self.retrieve_map_data('enemy-spawns')
        for spawn in enemy_spawn_data:
            if spawn.properties.get('e_type', 'goomba') == 'goomba':
                enemy = Goomba(self.screen, spawn.x, spawn.y, self.mario,
                               self.game_objects['floors'],
                               self.game_objects['collide_objs'],
                               self.game_objects['goomba'],
                               self.game_objects['koopa'])
                enemy.rect.y += 65 - enemy.rect.height
                self.game_objects['goomba'].add(enemy)
            else:
                enemy = Koopa(self.screen, spawn.x, spawn.y, self.mario,
                              self.game_objects['floors'],
                              self.game_objects['collide_objs'],
                              self.game_objects['goomba'],
                              self.game_objects['koopa'])
                enemy.rect.y += (65 - enemy.rect.height)
                print('Enemy rect begin:' + str(enemy.rect.y))
                self.game_objects['koopa'].add(enemy)
            self.map_group.add(enemy)

    def set_paused(self, event):
        # pauses the game
        key = event.key
        if key == pygame.K_p:
            self.paused = not self.paused
            pygame.mixer.music.load('audio/Pause-Screen.wav')
            pygame.mixer.music.play()

    def update(self):
        # updates the screen and objects on the screen
        if not self.paused and self.game_active:
            for block in self.game_objects['blocks']:
                points = block.check_hit(other=self.mario)
                if points:
                    self.score += points
                    self.coins += 1
            for q_block in self.game_objects['q_blocks']:
                points = q_block.check_hit(other=self.mario)
                if points:
                    self.score += points
                    self.coins += 1
            for coin in self.game_objects['coins']:
                if pygame.sprite.collide_rect(coin, self.mario):
                    self.score += coin.points
                    self.coins += 1
                    self.mario.SFX['coin'].play()
                    coin.kill()
            self.game_objects['blocks'].update()
            self.game_objects['rubble'].update()
            one_up_check = pygame.sprite.spritecollideany(
                self.mario, self.game_objects['items'])
            if one_up_check and one_up_check.item_type == Item.ONE_UP:
                self.lives += 1
                self.SFX['1-up'].play()
                one_up_check.kill()
            self.mario.update(pygame.key.get_pressed()
                              )  # update and check if not touching any walls
            self.handle_pipe()
            self.check_stage_clear()
            # print(self.mario.rect.x, self.mario.rect.y)
            self.game_objects['q_blocks'].update()
            self.game_objects['items'].update()
            self.game_objects['coins'].update()
            for goomba in self.game_objects['goomba']:
                goomba.update()
            for koopa in self.game_objects['koopa']:
                koopa.update()
        self.map_group.draw(self.screen)
        if not self.game_active:
            self.menu.blit()
        if self.game_active:
            self.stats.blit()
            self.check_timer()
        pygame.display.flip()

    def check_timer(self):
        # check the game timer
        if not self.paused:
            time = pygame.time.get_ticks()
            if time - self.last_tick > 600 and self.timer > 0:
                self.last_tick = time
                self.timer -= 1
            elif self.timer <= 100 and not self.time_warn:
                self.time_warn = True
                self.SFX['warning'].play()
            elif self.timer <= 0 and not self.mario.state_info['dead']:
                self.mario.start_death_jump()
        score = self.score + self.mario.score
        self.stats.update(str(score), str(self.coins), str('1-1'),
                          str(self.timer), str(self.lives))

    def handle_player_killed(self):
        # player has been killed by game
        self.lives -= 1
        if self.lives > 0:
            self.init_world()
            self.timer = 400
        else:
            self.game_active = False

    def run(self):
        # run application loop
        loop = EventLoop(loop_running=True, actions=self.menu.action_map)

        while True:
            loop.check_events()
            self.update()
            if self.menu.start:
                self.game_active = True
                self.timer = 400
                self.time_warn = False
                self.start_game()
                self.menu.start = False
                self.game_active = False
                self.game_won = False
                self.init_world()

    def start_game(self):
        # launches game
        loop = EventLoop(loop_running=True, actions=self.action_map)
        self.score = 0
        self.lives = 3
        self.coins = 0

        while loop.loop_running and self.game_active:
            self.clock.tick(60)  # 60 fps cap
            loop.check_events()
            self.update()
            if self.mario.state_info['death_finish']:
                self.handle_player_killed()
            elif not pygame.mixer.music.get_busy() and self.game_won:
                self.menu.high_score.save(self.score)
                self.game_active = False
            elif not pygame.mixer.music.get_busy(
            ) and self.mario.state_info['dead']:
                pygame.mixer.music.load('audio/Mario-Die.wav')
                pygame.mixer.music.play()
            elif not pygame.mixer.music.get_busy() and not self.paused:
                pygame.mixer.music.load('audio/BG-Main.wav')
                pygame.mixer.music.play(-1)
コード例 #23
0
def runGame():
    #Initialize game and create a window
    pg.init()
    #create a new object using the settings class
    setting = Settings()
    #creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))
    #set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    playBtn = Button(setting, screen, "PLAY", 200)
    menuBtn = Button(setting, screen, "MENU", 250)
    twoPlayBtn = Button(setting, screen, "2PVS", 250)
    #setBtnbtn = Button(setting, screen, "SETTING", 300)
    aboutBtn = Button(setting, screen, "ABOUT", 300)
    quitBtn = Button(setting, screen, "QUIT", 400)
    greyBtn = Button(setting, screen, "GREY", 200)
    redBtn = Button(setting, screen, "RED", 250)
    blueBtn = Button(setting, screen, "BLUE", 300)
    #make slector for buttons
    sel = Selector(setting, screen)
    sel.rect.x = playBtn.rect.x + playBtn.width + 10
    sel.rect.centery = playBtn.rect.centery

    #Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    #Make a ship
    ship = Ship(setting, screen)
    #Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    #make a group of bullets to store
    bullets = Group()
    eBullets = Group()
    setting.explosions = Explosions()

    #Make an alien
    aliens = Group()
    gf.createFleet(setting, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    #plays bgm
    pg.mixer.music.load("sounds/galtron.mp3")
    pg.mixer.music.set_volume(0.25)
    pg.mixer.music.play(-1)

    runGame = True

    #Set the two while loops to start mainMenu first
    while runGame:
        #Set to true to run main game loop
        while stats.mainMenu:
            mm.checkEvents(setting, screen, stats, sb, playBtn, twoPlayBtn,
                           aboutBtn, quitBtn, menuBtn, sel, ship, aliens,
                           bullets, eBullets)
            mm.drawMenu(setting, screen, sb, playBtn, menuBtn, twoPlayBtn,
                        aboutBtn, quitBtn, sel)

        while stats.playMenu:
            pm.checkEvents(setting, screen, stats, sb, playBtn, greyBtn,
                           redBtn, blueBtn, quitBtn, menuBtn, sel, ship,
                           aliens, bullets, eBullets)
            pm.drawMenu(setting, screen, sb, greyBtn, redBtn, blueBtn, menuBtn,
                        quitBtn, sel)

        while stats.mainGame:
            #Game functions
            gf.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, sel,
                           ship, aliens, bullets, eBullets)  #Check for events

            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship, aliens,
                                bullets, eBullets)  #Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens,
                                 bullets, eBullets)  #Update collisions
                ship.update(bullets)  #update the ship
            #Update the screen
            gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets,
                            eBullets, playBtn, menuBtn, quitBtn, sel)
        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb, playBtn, quitBtn,
                              menuBtn, sel, ship, aliens, bullets, eBullets)
            About.drawMenu(setting, screen, sb, menuBtn, quitBtn, sel)

        while stats.twoPlayer:
            tp.checkEvents(setting, screen, stats, playBtn, quitBtn, sel,
                           bullets, eBullets, ship1, ship2)
            if stats.gameActive:
                ship1.update(bullets)
                ship2.update(bullets)
                tp.updateBullets(setting, screen, stats, ship1, ship2, bullets,
                                 eBullets)
            tp.updateScreen(setting, screen, stats, bullets, eBullets, playBtn,
                            menuBtn, quitBtn, sel, ship1, ship2)
        while stats.mainGame:
            if runGame == True:
                print("test")
コード例 #24
0
def runGame():
	#Initialize game and create a window
	pg.init()
	pg.mixer.init()
	pg.time.delay(1000)
	#create a new object using the settings class
	setting = Settings()
	#creaete a new object from pygame display
	screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))
	#set window caption using settings obj
	pg.display.set_caption(setting.windowCaption)

	bgm = pg.mixer.Sound('music/背景音乐.ogg')
	bgm.set_volume(0.05)
	bgm.play(-1)


	fps = 120
	fclock = pg.time.Clock()

	playBtn = Button(setting, screen, "PLAY", 200)
	menuBtn = Button(setting, screen, "MENU", 250)
	aboutBtn = Button(setting, screen, "ABOUT", 250)
	quitBtn = Button(setting, screen, "QUIT", 300)

	#make slector for buttons
	sel = Selector(setting, screen)
	sel.rect.x = playBtn.rect.x + playBtn.width + 10
	sel.rect.centery = playBtn.rect.centery

	#Create an instance to stor game stats
	stats = GameStats(setting)
	sb = Scoreboard(setting, screen, stats)

	#Make a ship
	ship = Ship(setting, screen)
	#Ships for two player 
	ship1 = Ship(setting, screen)
	ship2 = Ship(setting, screen)

	#make a group of bullets to store
	bullets = Group()

	#Make an alien
	aliens = Group()
	gf.createFleet(setting, screen, ship, aliens)
	icon = pg.image.load('gfx/SpaceShip.png')
	pg.display.set_icon(icon)

	runGame = True

	#Set the two while loops to start mainMenu first
	while runGame:
		#Set to true to run main game loop
		while stats.mainMenu:
			mm.checkEvents(setting, screen, stats, sb, playBtn, aboutBtn, quitBtn, menuBtn, sel, ship, aliens, bullets)
			mm.drawMenu(setting, screen, sb, playBtn, menuBtn, aboutBtn, quitBtn, sel)

		while stats.mainGame:
			#Game functions
			gf.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, sel, ship, aliens, bullets) #Check for events
			if stats.gameActive:
				gf.updateAliens(setting, stats, sb, screen, ship, aliens, bullets) #Update aliens
				gf.updateBullets(setting, screen, stats, sb, ship, aliens, bullets) #Update collisions
				ship.update() #update the ship
			gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets, playBtn, menuBtn, quitBtn, sel) #Update the screen

			fclock.tick(fps)

		while stats.mainAbout:
			About.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, menuBtn, sel, ship, aliens, bullets)
			About.drawMenu(setting, screen, sb, menuBtn, quitBtn, sel)

		while stats.mainGame:
			if runGame == True:
				print("test")
コード例 #25
0
ファイル: main.py プロジェクト: Kaine-R/AIProject
def runGame():
    pygame.init()

    # Basic init (clock for fps, settings for easy number changes, gamestats for game variables, screen/display for window)
    clock = pygame.time.Clock()
    settings = Settings()
    gameStats = GameStats()
    screen = pygame.display.set_mode(
        (settings.screenWidth, settings.screenHeight))
    pygame.display.set_caption("AI Game")

    text = Text(screen, settings, "Generation # Text", 30, 10, 10)
    allText = [text]

    spikes = Group()  # group of all spikes
    map = Group()  # Group of all Blocks
    gf.makeMap(map, spikes, screen,
               settings)  # assigns blocks and spikes to groups

    enemies = Group()  # testing enemy
    # newEnemy = Baddie(screen, settings)
    # newEnemy.rect.x, newEnemy.rect.y = 550, settings.screenHeight - 85
    # enemies.add(newEnemy)

    Bots = []
    gf.createBots(screen, settings, Bots)  # For loop to create and append bots

    while True:
        screen.fill(
            settings.bgColor
        )  # Fills background with solid color, can add clouds or something later
        gf.blitMap(map)  # Draws the map on screen
        gf.drawGrid(
            settings, screen,
            gameStats)  # Draw the Grid, helps for coding can be removed

        gf.checkEvents(gameStats)  # Checks Button Presses
        #gf.checkCollide(player, map, spikes)     # Checks to see if player is hitting the world around him
        gf.enemyBlockCollide(enemies, map)
        #gf.enemyPlayerCollide(player, enemies)
        gf.screenRoll(gameStats, map, spikes, Bots)

        if gameStats.pause == False:

            for bot in Bots:
                if gf.checkCollide(bot, map, spikes):
                    gameStats.death += 1
                if bot.dead == False:
                    if bot.rect.x > 19 * (
                            bot.settings.screenWidth / 24
                    ):  # screen roll, Make optional or only scan once
                        gameStats.screen_bot_roll = True
                    data, item = gf.scanFront(bot, map, spikes)
                    bot.chooseInput(data, item)

            if gf.roundTimer(gameStats) or gameStats.death >= len(
                    Bots
            ):  ## Things that are done to prepare for next gen ** Alll this into a function
                gameStats.screen_bot_roll = False  ## This needs to be a function check to turn off
                gf.resetScreen(gameStats, map, spikes, Bots)

                tempTimerAdd = gf.splitBots(
                    Bots
                )  # Deletes the worst half and return the highest score
                gameStats.addTimer(tempTimerAdd)
                ## TIMER MIGHT BE MESS UP RIGHT NOW MUST CHECK LATER *******************************************

                for i in range(len(Bots)):
                    Bots[i].id = i + 1
                    Bots[i].increaseLife()

            gf.printInfo(Bots, gameStats.death, settings)
            for i in range(int(len(Bots))):
                if Bots[i].dead == False:
                    Bots[i].update()
                Bots[i].blit()
        else:  # When pause is True
            for i in range(int(len(Bots))):
                Bots[i].blit()

        for enemy in enemies:  # not affected by pause since it's being tested
            enemy.update()
            enemy.blit()

        gf.printText(allText, gameStats)

        gf.deadBotBox(len(Bots), screen)
        spikes.draw(screen)

        pygame.display.flip(
        )  # Makes the display work (Don't Touch, Make sure this stay near the bottom)
        clock.tick(75)
コード例 #26
0
def runGame():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screenWidth, settings.screenHeight))
    pygame.display.set_caption("PacMan")
    mainMenu = Menu(screen, settings)
    play = Play(screen, settings)
    gameStats = GameStats()
    map = BuildMap(screen, settings)
    details = Details(screen, settings)
    blocks = Group()
    dots = Group()
    ghosts = []
    for i in range(4):
        new = Ghost(screen, settings)
        new.type = i
        new.x += 30 * i
        new.prep()
        ghosts.append(new)
    fruit = Fruit(screen, settings)
    powerPills = Group()
    player = Player(screen, settings)
    map.makeMap(blocks, dots, powerPills)
    pygame.mixer.init()

    while True:
        screen.fill((50, 20, 20))
        map.drawMap(blocks, dots, powerPills)

        details.blit()
        gf.checkEvents(player, gameStats, play)
        if gameStats.gameActive:
            if gameStats.pause == False:
                if player.movementRight or player.movementLeft or player.movementUp or player.movementDown:
                    pygame.mixer.music.load('sound/dotSound.mp3')
                    pygame.mixer.music.play(0, .052)
                player.update()
                player.blit()
                for i in range(4):
                    ghosts[i].update(gameStats)
                    ghosts[i].blit()
                    gf.checkScreenLimits(ghosts[i])
                gf.checkScreenLimits(player)
            details.prep(gameStats)
            fruit.blit(gameStats)
            gf.spawnFruit(gameStats, fruit)
            gf.ghostCollide(ghosts[0], blocks)
            gf.ghostCollide(ghosts[2], blocks)
            gf.fruitCollide(player, fruit, gameStats)
            gf.addDiff(ghosts[2], gameStats)
            gf.wallCollide(player, blocks)
            gf.dotCollide(player, dots, gameStats)
            gf.pillCollide(player, powerPills, gameStats)
            for ghost in ghosts:
                gf.playerGhostCollide(player, ghost, gameStats, mainMenu)
            gf.roundEnd(gameStats, player, ghosts, dots, powerPills, map)
        else:
            mainMenu.checkShowHS(gameStats.showHS)
            mainMenu.update()
            mainMenu.blit()
            play.blit()

        pygame.display.flip()
コード例 #27
0
ファイル: gameController.py プロジェクト: ntsdav561/jaialai
class GameController(object):
    """
    Controls the game according to the State of Florida Regulations
    Accepts a player list in post starting order
    Example: ['a', 'b', 'c','d','e','f','g','h']
    Creates a TopScoreCard - to keep track of the score through the whole game
    Example: {'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 3, 'f': 1}
    Creates a PlayerQueue  - a list of players in post order
    Example: ['a', 'b', 'c','d','e','f','g','h']
    Plays a series of 'point sets' between players until the 1st, 2nd 3rd, and 4th positions are filled with only one player in each position. The sequence of point sets makes up a 'game'. The conditions for how a point set is scored and what it takes to finish a point set depend on the type of game (Spectacular 7, or Spectacular 9), the number of tied players at particular positions, and how many points have been played. A series of games makes up a program - ie Matinee or evening program.
    Returns a positionList - a ranked dict of players based on their relative scores
    Example: {1: ['f'], 2: ['a'], 3: ['c'], 4: ['b'], 5: ['e','d'], 6: []}
    """
    FIRST_ALLOWED_TIED_POSITION = 5    
    
    def __init__(self, player_list,gameType, pwin_dict):
        self.topScoreCard = ScoreCard(player_list)
        self.topPlayerQueue = PlayerQueue(player_list)
        self.gameType = gameType
        self.gameStats = GameStats(player_list)
       
        self.pwin_dict = pwin_dict
        

    def play_game(self):
        #print self.topScoreCard.get_first_tied_position()
        while self.topScoreCard.has_ties() and self.topScoreCard.get_first_tied_position() < self.FIRST_ALLOWED_TIED_POSITION:
            tiedScoreCard = self.topScoreCard.get_first_tied_score_card()
            tiedPlayerQueue = self.topPlayerQueue.get_first_tied_player_queue(tiedScoreCard.get_score_card())
            number_tied = tiedScoreCard.get_number_of_players_on_scorecard()
            # Get the appropriate rules from the rules dictionary
            rules_dict = self.gameType.get_point_set_rules_dict(number_tied, tiedScoreCard.get_score_card())
            if number_tied == 8:
                # This is the starting point set and is played until there is a winner
                # This point set is always played and the final queue positions determine the 
                # rotation sequence for playing all the ties. Therfore, need to capture the
                # queue status at this point to drive all the other tie breakers
                point_set_rules = self.get_8_tied_point_set_rules(rules_dict)
                #self.topPlayerQueue. = PlayerQueue(PlayerQueue.getPlayerQueue())
            if number_tied == 7:
                point_set_rules = self.get_7_tied_point_set_rules(rules_dict)
            if number_tied == 6:
                point_set_rules = self.get_6_tied_point_set_rules(rules_dict)
            if number_tied == 5:
                point_set_rules = self.get_5_tied_point_set_rules(rules_dict)
            if number_tied == 4:
                point_set_rules = self.get_4_tied_point_set_rules(rules_dict)
            if number_tied == 3:
                point_set_rules = self.get_3_tied_point_set_rules(rules_dict)
            if number_tied == 2:
                point_set_rules = self.get_2_tied_point_set_rules(rules_dict)
            # Some tied conditions call for a knockout point playing sequence instead of standard
            if point_set_rules.get('rotation') == 'knockout':
                #print 'knockout'
                tiedPlayerQueue = KnockOutPlayerQueue(tiedPlayerQueue.getPlayerQueue())
                
            pointSetPlayer = PointSetPlayer()
            
            
            untied_score_card = pointSetPlayer.play_point_set(tiedScoreCard, tiedPlayerQueue, point_set_rules, self.gameStats, self.pwin_dict)
            self.topScoreCard = self.topScoreCard.incorporate_sub_score_card(untied_score_card)
            #print tiedScoreCard.get_score_card()
            #print self.topScoreCard.get_score_card()
        posList = self.topScoreCard.make_position_list()
        game_stats_data = self.gameStats.get_game_stats()
        ####################### TO DO ######################
        # Can update playerstats here using posList
        # also send points_played out to somewhere 
        #print self.gameStats.get_game_stats()
        return posList, game_stats_data
            
    def get_2_tied_point_set_rules(self, rules_dict):
        """
        {'2>=0':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'score':'all_scores_different'}}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if tied_score_card.all_scores_different() == True:
                return True
            return False
                  
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2}
        return point_set_rules_dict


    def get_3_tied_point_set_rules(self, rules_dict):
        """
        {'3>=0':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'point_and_score':[2,7],'score':'all_scores_different'}}}
        """
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played >= rules_dict['endConditions']['point_and_score'][0]) or (tied_score_card.all_scores_different() == True):
                return True
            return False
 
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2}
        return point_set_rules_dict                


        
    def get_4_tied_point_set_rules(self, rules_dict):
        """
        {'4>=0':{'point_system':[1,2], 'rotation':'knockout', 'endConditions':{'point_and_score':[1,7],'points_played':2}}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played > rules_dict['endConditions']['point_and_score'][0]) or points_played == rules_dict['endConditions']['points_played']:
                return True
            return False
            
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2,'rotation':'knockout'}
        return point_set_rules_dict

        
    def get_5_tied_point_set_rules(self, rules_dict):
        """
        {'5=0':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'point_and_score':[1,4]}}}
        {'5>=1':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'point_and_score':[1,7]}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played >= rules_dict['endConditions']['point_and_score'][0]):
                return True
            return False
            
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2}
        return point_set_rules_dict        


    def get_6_tied_point_set_rules(self, rules_dict):
        """
        {'6>=0':{'point_system':[1,2], 'rotation':'knockout', 'endConditions':{'point_and_score':[1,7],'points_played':3}}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played > rules_dict['endConditions']['point_and_score'][0]) or points_played == rules_dict['endConditions']['points_played']:
                return True
            return False
            
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2,'rotation':'knockout'}
        return point_set_rules_dict
        
        


    def get_7_tied_point_set_rules(self, rules_dict):
        """
        {'7=0':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'point_and_score':[1,6]}}}
        {'7>=1':{'point_system':[1,2], 'rotation':'queue', 'endConditions':{'point_and_score':[1,7]}}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played >= rules_dict['endConditions']['point_and_score'][0]):
                return True
            return False
            
        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 2}
        return point_set_rules_dict
        
        
    def get_8_tied_point_set_rules(self, rules_dict):
        """
        {'8>=0':{'point_system':[1,1,7,2], 'rotation':'queue', 'endConditions':{'point_and_score':[1,7]}}}
        """
        
        def end_condition_met_function(tied_score_card, points_played):
            if (tied_score_card.get_high_score() >= rules_dict['endConditions']['point_and_score'][1] and points_played > rules_dict['endConditions']['point_and_score'][0]):
                return True
            return False

        point_set_rules_dict = {'end_condition_function':end_condition_met_function,'initial_points': 1, 'threshold':8,'next_points':2}
        return point_set_rules_dict        
コード例 #28
0
def runGame():
    #initsialise game and create screen object
    pygame.init()  #To initialise the background settings
    cNM_S = Settings(
    )  # object of the settings class cNM_S stands for "Creeper Nah Man! Settings"

    screen = pygame.display.set_mode(
        (cNM_S.screen_width, cNM_S.screen_height)
    )  # We create a display called screen, (1200,800) is a tuple which defines
    # the dimensions of the game window.
    # The screen object just created is called a surface
    # In pygame a surface is part of the screen where we display a game element,eg creeper will be a surface and the Pewdiepie model will be a surface in the game
    pygame.display.set_caption("Creeper Nah Man!")

    #Make a play button
    playButton = Button(cNM_S, screen, "Play")

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

    #Make a Pewds model, a group of tridents and a group of creepers:-

    #Create a Pewdiepie model
    pewdsModel = Pewds(
        cNM_S, screen
    )  # Creating an instance of Pewds class , this part is outside while since we do not want to create a new instance of Pewds class on each

    #Make a group to store tridents in
    tridents = Group()
    #The group is created outside the while loop so that we dont create a new group each time we pass through the while loop
    #This group will store all the live tridents so that we can manage the tridents that have already been fired by the user
    #This group will be an instance of the class pygame.sprite.Group, which behaves like a list with some extra functionality which is helpful when
    # building games, we will use this group to draw tridents on the screen on each pass through the main loop (while loop) and to update each tridents'
    # position

    #Make a group of creepers
    creepers = Group()

    #Create a collection of creepers
    gf.createCreeperCollection(cNM_S, screen, pewdsModel, creepers)

    #setting up backround image for the game
    bkgnd = pygame.image.load(
        "C:\\Users\\Rahul Pillai\\Desktop\\_\\College\\SkillShare\\PythonGameDevelopment\\Codes\\CreeperNahMan\\CreeperNahMan\\CreeperNahMan\\ImageAssets\\bkgnd.png"
    )
    #.convert() #convert is used since the image needs to be converted to a format Pygame can more easily work with.

    #set background color (Already done in Settings.py)
    #bg_color=(135,206,250) (Can use this if there was no Settings file)

    #start main loop for the game

    while True:  # while loop that contains the game

        screen.blit(
            bkgnd, [0, 0])  # to set our background initially before everything
        # watch for keyboard and mouse events
        gf.checkEvents(cNM_S, screen, stats, sb, playButton, pewdsModel,
                       creepers,
                       tridents)  #this function exists in gameFunctions.py
        #tridents is passed to this function since we need to check the event when space bar is pressed to shoot trident

        if stats.gameActive:
            pewdsModel.update()

            #tridents is passed to this function since we need to update the tridents drawn to the screen so we see the tridents moving up
            gf.updateTridents(
                cNM_S, screen, stats, sb, creepers, pewdsModel, tridents
            )  # instead of doing tridents.update() and removal of off screen tridents here
            # we have moved that code to a new function in gameFunctions.py

            gf.updateCreepers(cNM_S, stats, screen, sb, pewdsModel, creepers,
                              tridents)

        gf.updateScreen(cNM_S, screen, stats, sb, pewdsModel, tridents,
                        creepers, playButton)
コード例 #29
0
def runGame():
    # Initialize game and create a window
    pg.init()
    # create a new object using the settings class
    setting = Settings()
    # creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))

    # intro
    intro.introimages()

    # set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    bMenu = ButtonMenu(screen)
    bMenu.addButton("play", "PLAY")
    bMenu.addButton("menu", "MENU")
    bMenu.addButton("twoPlay", "2PVS")
    bMenu.addButton("settings", "SETTINGS")
    bMenu.addButton("invert", "INVERT")
    bMenu.addButton("about", "ABOUT")
    bMenu.addButton("quit", "QUIT")
    bMenu.addButton("grey", "GREY")
    bMenu.addButton("red", "RED")
    bMenu.addButton("blue", "BLUE")
    bMenu.addButton("retry", "RETRY")
    bMenu.addButton("hard", "HARD")
    bMenu.addButton("normal", "NORMAL")

    mainMenuButtons = ["play", "about", "settings", "quit"]  # delete "twoPlay"
    playMenuButtons = ["grey", "red", "blue", "menu", "quit"]
    levelMenuButtons = ["hard", "normal", "quit"]
    mainGameButtons = ["play", "menu", "quit"]
    aboutButtons = ["menu", "quit"]
    settingsMenuButtons = ["menu", "invert", "quit"]

    bgManager = BackgroundManager(screen)
    bgManager.setFillColor((0, 0, 0))
    bgManager.addBackground(
        "universe_1", "gfx/backgrounds/stars_back.png", 0, 1)
    bgManager.addBackground(
        "universe_1", "gfx/backgrounds/stars_front.png", 0, 1.5)
    bgManager.selectBackground("universe_1")

    # Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    # Make a ship
    ship = Ship(setting, screen)
    # Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    # make a group of items to store
    items = Group()

    # make a group of bullets to store
    bullets = Group()
    charged_bullets = Group()
    eBullets = Group()
    setting.explosions = Explosions()

    # Make an alien
    aliens = Group()
    gf.createFleet(setting, stats, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    bgImage = pg.image.load('gfx/title_c.png')
    bgImage = pg.transform.scale(
        bgImage, (setting.screenWidth, setting.screenHeight))
    bgImageRect = bgImage.get_rect()

    aboutImage = pg.image.load('gfx/About_modify2.png')
    aboutImage = pg.transform.scale(
        aboutImage, (setting.screenWidth, setting.screenHeight))
    aboutImageRect = aboutImage.get_rect()

    # plays bgm
    pg.mixer.music.load('sound_bgms/galtron.mp3')
    pg.mixer.music.set_volume(0.25)
    pg.mixer.music.play(-1)

    rungame = True

    sounds.stage_clear.play()
    # Set the two while loops to start mainMenu first
    while rungame:
        # Set to true to run main game loop
        bMenu.setMenuButtons(mainMenuButtons)
        while stats.mainMenu:
            if not stats.gameActive and stats.paused:
                setting.initDynamicSettings()
                stats.resetStats()
                ##stats.gameActive = True

                # Reset the alien and the bullets
                aliens.empty()
                bullets.empty()
                eBullets.empty()

                # Create a new fleet and center the ship
                gf.createFleet(setting, stats, screen, ship, aliens)
                ship.centerShip()

            mm.checkEvents(setting, screen, stats, sb, bMenu,
                           ship, aliens, bullets, eBullets)
            mm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(levelMenuButtons)
        while stats.levelMenu:
            lm.checkEvents(setting, screen, stats, sb, bMenu,
                           ship, aliens, bullets, eBullets)
            lm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(playMenuButtons)
        while stats.playMenu:
            pm.checkEvents(setting, screen, stats, sb, bMenu,
                           ship, aliens, bullets, eBullets)
            pm.drawMenu(setting, screen, sb, bMenu)

        bMenu.setMenuButtons(mainGameButtons)

        while stats.mainGame:
            # Game functions
            gf.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets, charged_bullets)  # Check for events
            # Reset Game
            if gf.reset == 1:
                gf.reset = 0
                pg.register_quit(runGame())
            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship,
                                aliens, bullets, eBullets)  # Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens, bullets,
                                 eBullets, charged_bullets, items)  # Update collisions
                gf.updateItems(setting, screen, stats, sb, ship,
                               aliens, bullets, eBullets, items)
                ship.update(bullets, aliens)  # update the ship
                # Update the screen
            gf.updateScreen(setting, screen, stats, sb, ship, aliens,
                            bullets, eBullets, charged_bullets, bMenu, bgManager, items)

        bMenu.setMenuButtons(aboutButtons)
        bMenu.setPos(None, 500)

        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb,
                              bMenu, ship, aliens, bullets, eBullets)
            About.drawMenu(setting, screen, sb, bMenu,
                           aboutImage, aboutImageRect)

        while stats.twoPlayer:
            tp.checkEvents(setting, screen, stats, sb, bMenu,
                           bullets, aliens, eBullets, ship1, ship2)
            if stats.gameActive:
                ship1.update(bullets, aliens)
                ship2.update(bullets, aliens)
                tp.updateBullets(setting, screen, stats, sb,
                                 ship1, ship2, aliens, bullets, eBullets, items)
            tp.updateScreen(setting, screen, stats, sb, ship1,
                            ship2, aliens, bullets, eBullets, bMenu, items)

        bMenu.setMenuButtons(settingsMenuButtons)

        while stats.settingsMenu:
            sm.checkEvents1(setting, screen, stats, sb, bMenu,
                            ship, aliens, bullets, eBullets)
            sm.drawMenu(setting, screen, sb, bMenu)

        while stats.mainGame:
            if rungame == True:
                print("test")
コード例 #30
0
ファイル: app.py プロジェクト: jaskinner/stats-buddy
def get_matchup_stats():
    return GameStats().get_average_atr()
コード例 #31
0
ファイル: app.py プロジェクト: jaskinner/stats-buddy
def get_reb_stats(team_id):
    stats = GameStats(team_id=team_id).get_average_atr()
    return stats
コード例 #32
0
def Game():
    pygame.init()

    gamesettings = Settings()
    screen = pygame.display.set_mode(
        (gamesettings.screen_width, gamesettings.screen_height))
    pygame.display.set_caption("Pacman Portal")

    # Start screen
    showgamestats = GameStats(screen, gamesettings)
    startScreen = StartScreen(screen, gamesettings, showgamestats)

    # Grouping blocks and pellets and ghosts
    blocks = Group()
    powerpills = Group()
    shield = Group()
    portals = Group()
    ghosts = Group()
    intersections = Group()
    fruit = Fruit(screen)

    thepacman = Pacman(screen, gamesettings)

    # Making the ghosts
    redghost = Ghosts(screen, "red")
    cyanghost = Ghosts(screen, "cyan")
    orangeghost = Ghosts(screen, "orange")
    pinkghost = Ghosts(screen, "pink")

    ghosts.add(redghost)
    ghosts.add(cyanghost)
    ghosts.add(orangeghost)
    ghosts.add(pinkghost)

    # Making the two portals
    orange = Portal(screen, "orange")
    blue = Portal(screen, "blue")

    portals.add(orange)
    portals.add(blue)

    startScreen.makeScreen(screen, gamesettings)
    fruit.fruitReset()
    gf.readFile(screen, blocks, shield, powerpills, intersections)

    frames = 0  # for the victory fanfare and death animation

    # play intro chime
    playIntro = True

    screen.fill(BLACK)
    while True:
        if (gamesettings.game_active):
            pygame.time.Clock().tick(120)  #120 fps lock
            screen.fill(BLACK)
            showgamestats.blitstats()
            gf.check_events(thepacman, powerpills, gamesettings, orange, blue)
            gf.check_collision(thepacman, blocks, powerpills, shield, ghosts,
                               intersections, showgamestats, gamesettings,
                               fruit, orange, blue)
            for block in blocks:
                block.blitblocks()
            for theshield in shield:
                theshield.blitshield()
            for pill in powerpills:
                pill.blitpowerpills()
            for portal in portals:
                portal.blitportal()
            for ghost in ghosts:
                ghost.blitghosts()
                ghost.update()
                if (ghost.DEAD):
                    ghost.playRetreatSound()
                elif (ghost.afraid):
                    ghost.playAfraidSound(
                    )  # if ghosts are afraid, loop their sound
            for intersection in intersections:
                intersection.blit()
            fruit.blitfruit()
            thepacman.blitpacman()
            thepacman.update()

            if (len(powerpills) == 0):
                gamesettings.game_active = False
                gamesettings.victory_fanfare = True
            if (playIntro and pygame.time.get_ticks() % 200 <= 50):
                mixer.Channel(2).play(
                    pygame.mixer.Sound('sounds/pacman_beginning.wav'))
                pygame.time.wait(4500)
                playIntro = False
        elif (gamesettings.victory_fanfare):
            if (frames <= 120):
                for block in blocks:
                    block.color = ((255, 255, 255))
                    block.blitblocks()
            elif (frames <= 240):
                for block in blocks:
                    block.color = ((0, 0, 255))
                    block.blitblocks()
            elif (frames <= 360):
                for block in blocks:
                    block.color = ((255, 255, 255))
                    block.blitblocks()
            elif (frames <= 480):
                for block in blocks:
                    block.color = ((0, 0, 255))
                    block.blitblocks()
            else:
                gamesettings.game_active = True
                gamesettings.victory_fanfare = False
                thepacman.resetPosition()
                for ghost in ghosts:
                    ghost.resetPosition()
                    ghost.speed += 1
                showgamestats.level += 1
                fruit.fruitReset()
                gf.readFile(screen, blocks, shield, powerpills, intersections)
                frames = 0
                pygame.time.wait(1000)
            frames += 1
        elif (thepacman.DEAD):
            thepacman.deathAnimation(frames)
            frames += 1
            if (frames > 600):
                gamesettings.game_active = True
                thepacman.DEAD = False
                thepacman.resetPosition()
                for ghost in ghosts:
                    ghost.resetPosition()
                frames = 0
                pygame.time.wait(1000)

        if (showgamestats.num_lives < 0):
            #reset game and save score
            screen.fill(BLACK)
            pygame.time.wait(2000)
            gamesettings.game_active = False
            thepacman.resetPosition()
            for ghost in ghosts:
                ghost.resetPosition()
                ghost.speed = 1
            showgamestats.num_lives = 3
            showgamestats.save_hs_to_file()
            showgamestats.score = 0
            showgamestats.level = 1
            fruit.fruitReset()
            playIntro = True  # reset the chime
            gf.readFile(screen, blocks, shield, powerpills, intersections)
            startScreen.makeScreen(screen, gamesettings)

        pygame.display.flip()