Example #1
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    ship = Ship(ai_settings, screen)
    stats = GameStats(ai_settings)
    score = Score(ai_settings, screen, stats)
    stats.score = 0
    aliens = Group()
    bullets = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    pygame.display.update()

    while True:
        gf.check_events(ai_settings, screen, stats, score, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, score, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
            for bullet in bullets.copy():
                if bullet.rect.bottom <= 0:
                    bullet.remove(bullets)
                    print(len(bullets))
        gf.update_screen(ai_settings, screen, stats, score, ship, aliens,
                         bullets, play_button)
Example #2
0
def run_game():
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Alien Invaders")
    ship = Ship(screen, setting)
    bullets = Group()
    aliens = Group()

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

    stats = GameStats(setting)

    sb = Scoreboard(setting, screen, stats)

    g_o = GameOver(screen, "Game Over")

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

    while True:
        gf.check_game(ship, setting, screen, bullets, aliens, stats,
                      play_button, sb)
        gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                         play_button, sb)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, aliens, setting, ship, screen, stats,
                              sb)
            gf.update_aliens(setting, aliens, ship, screen, bullets, stats, sb)
            gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                             play_button, sb)
Example #3
0
File: pong.py Project: jbakerr/Pong
def run_game():
    pygame.init()

    ai_settings = Settings()

    screen = pygame.display.set_mode((1200, 800))

    pygame.display.set_caption("Pong")

    ball = Ball(ai_settings, screen)

    human_paddle = Paddle(ai_settings, screen, 'right')
    ai_paddle = Paddle(ai_settings, screen, 'left')

    stats = GameStats(ai_settings)

    while True:

        gf.check_events(ai_settings, screen, human_paddle, stats)
        if stats.game_active:
            human_paddle.update()
            ball.update()
            gf.ai_update(ball, ai_paddle, ai_settings)
            ai_paddle.update()
            gf.update_ball(ai_settings, screen, human_paddle, ai_paddle, ball,
                           stats)
            gf.update_screen(ai_settings, screen, human_paddle, ai_paddle,
                             ball)
Example #4
0
def run_game():
    pygame.init()
    ai_settings = settings.Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    #screen=pygame.display.set_mode((1200,800))
    #bg_color=(200,200,222)
    pygame.display.set_caption("alien invasion")
    ship = Ship(ai_settings, screen)
    play_button = Button(ai_settings, screen, "play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    #存储子弹
    bullets = Group()
    aliens = Group()

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

    #开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        bullets, aliens)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        #每次循环都重绘屏幕
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Example #5
0
def start_screen():
    pygame.init()
    ai_settings = Settings()
    start_scr = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, start_scr, stats)

    music = pygame.mixer.Sound("Sounds/space_music.wav")

    play_button = Button(ai_settings, start_scr, "Start", (600, 50))
    score_button = Button(ai_settings, start_scr, "Highscore", (600, 750))
    score_button.msg_image_rect.center = 600, 750

    a = gm.display_alien_start_screen(ai_settings, start_scr)
    gm.score1(start_scr)

    while True:
        music.play()
        gm.check_button_press(play_button, ai_settings, stats, sb)
        if stats.game_active:
            run_game()
        elif not stats.game_active:
            play_button.draw_button()
            score_button.draw_button()

        a = gm.score_menu(score_button, ai_settings, stats, sb)
        if a is True:
            score_screen()

        pygame.display.flip()
Example #6
0
def run_game():
    """Engine of the game"""
    # Initialize game and create a screen object.
    pygame.init()
    game_set = Settings()
    screen = pygame.display.set_mode(
        (game_set.screen_width, game_set.screen_height))
    # Setting caption
    pygame.display.set_caption("Alien Invasion")
    # An instance to store game statistics and create a scoreboard.
    stats = GameStats(game_set)
    sb = Scoreboard(game_set, screen, stats)
    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(game_set, screen)
    flag = 0
    # Create the fleet of aliens.
    Timer(0.0, gf.create_alien, [game_set, screen]).start()
    Timer(8.0, gf.delete_alien, [game_set, screen, ship]).start()
    # Start the main loop for the game.
    while True:
        # Watch for keyboard events.
        flag = gf.check_events(game_set, screen, ship, stats, flag)
        # End game check
        if flag == 1:
            break
        # Update condition of bullets and ship
        ship.update()
        Bullet_Norm.bullets.update()
        Bullet_Wait.bullets.update()
        # Get rid of bullets that have disappeared.
        gf.update_bullets(game_set, screen, stats, sb, ship)
        gf.update_screen(game_set, screen, stats, sb, ship)
    print("Counter : " + (str)(stats.score))
    os._exit(0)
Example #7
0
 def __init__(self):
     """Initialize the game, and create game resources."""
     pygame.init()
     # Clock set-up for framerate
     self.clock = pygame.time.Clock()
     self.settings = Settings()
     self.stats = GameStats(self)
     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("Bouncing Ball")
     self.bar = Bar(self)
     self.ball = Ball(self)
     self.timebar = TimeBar(self)
     self.play_button = Button(self, 'Play')
Example #8
0
def score_screen():
    pygame.init()
    ai_settings = Settings()
    score_scr = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")

    music = pygame.mixer.Sound("Sounds/space_music.wav")

    play_button = Button(ai_settings, score_scr, "Start", (600, 50))

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, score_scr, stats)
    a = gm.store_score(stats, score_scr)

    y = 0

    gm.display_scores(a, score_scr, y)

    while True:
        music.play()
        gm.check_button_press(play_button, ai_settings, stats, sb)

        if stats.game_active:
            run_game()
        elif not stats.game_active:
            play_button.draw_button()
        pygame.display.flip()
Example #9
0
def run_game():
	
	pygame.init()
	ai_settings = Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width,
										ai_settings.screen_height))
													
	pygame.display.set_caption("Alien invasion")
	bg_color = (ai_settings.bg_color)
	ship = Ship(ai_settings, screen)	
	block = Block(ai_settings, screen)
	bullets = Group()	
	play_button = Button(ai_settings, screen, "Play")
	stats = GameStats(ai_settings)			
	
	
	while True:
		
		gf.check_events(ai_settings, screen, stats, play_button, ship, bullets)
		
		if stats.game_active:
			ship.update()	
			gf.update_bullets(bullets)
			for bullet in bullets.copy():
				gf.training(ai_settings, screen, bullets, block, bullet)
			block.update(ai_settings)
		gf.update_screen(ai_settings,screen,ship, stats, 
					bullets, block, play_button)
Example #10
0
def run_game():
    # Initialize game and create a screen object
    pygame.init()
    wof_settings = GameSettings()  # set the game settings
    screen = pygame.display.set_mode((wof_settings.width, wof_settings.height))
    pygame.display.set_caption(wof_settings.caption)
    # hide mouse cursor
    pygame.mouse.set_visible(False)

    stats = GameStats()

    fns.start_screen(screen, wof_settings)  # show the title screen

    # read the level map from the text file
    # input: text file name
    # return: a dictionary with coordinates of the game elements
    levels = fns.read_levels(wof_settings)
    current_level = 0

    while True:
        fns.level_screen(screen, wof_settings, current_level)
        wof_settings.running = True
        status = run_level(levels, current_level, wof_settings, screen, stats)

        if status in ('next', 'done'):
            current_level += 1
            if current_level >= len(levels):
                current_level = 0
        elif status == 'back':
            current_level -= 1
            if current_level < 0:
                current_level = len(levels) - 1
        elif status == 'replay':
            pass
Example #11
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Space Invaders")

    music = pygame.mixer.Sound("Sounds/space_music.wav")

    play_button = Button(ai_settings, screen, "Play", (600, 50))
    barrier = Barrier(ai_settings, screen)
    ship = Ship(ai_settings, screen)

    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    bullets = Group()
    aliens = Group()

    gm.create_fleet(ai_settings, screen, ship, aliens)
    gm.create_barriers(ai_settings, screen)

    while True:
        music.play()
        gm.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        bullets.update()
        ship.update()
        barrier.update()
        gm.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets)
        gm.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                          bullets)
        gm.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets)

        pygame.display.flip()
Example #12
0
def run_game():
    ai_settings = Settings()
    pygame.init()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption(ai_settings.screen_caption)
    bg = Background(screen)
    bg2 = Background2(screen)
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play")
    game_over_label = Label(ai_settings, screen, "Game Over! Play again!", 250,
                            50, 175, 300)
    game_paused_label = Label(ai_settings, screen, "Game Paused", 250, 50, 175,
                              300)
    gf.create_fleet(ai_settings, screen, aliens)

    while True:
        gf.check_events(ai_settings, stats, screen, ship, aliens, bullets,
                        play_button)
        if stats.game_active == True:
            ship.update()
            gf.update_bullets(bullets, aliens, ai_settings, screen)
            gf.update_aliens(aliens, ship, ai_settings, stats, screen, bullets)
        gf.update_screen(ai_settings, stats, screen, bg, bg2, ship, aliens,
                         bullets, play_button, game_over_label,
                         game_paused_label)
def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    # Initialize Settings
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.width,ai_settings.height),pygame.RESIZABLE)
    # Set game window caption
    pygame.display.set_caption("Alien Invasion - Star Wars Edition")
    # Play Button
    play_button = Button(ai_settings, screen, "Play Star Wars")
    # Initilize Game Stats for every Player
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # Initialize Game's Ship
    ship = Ship(ai_settings,screen)
    # Store ship bullets
    bullets = Group()
    # Store empire fleet
    fleet = Group()
    # Send empire ships to the game
    af.create_fleet(ai_settings,screen,fleet,ship)
    # Start the main loop for the game - User actions control the flow of the game
    while True:
        # Check Events
        af.check_events(ai_settings, screen, ship, bullets,stats,play_button,fleet,sb)
        if stats.game_active:
            # Check movement
            ship.update_position()
            # Update bullets position and remove ones past screen
            af.update_bullets(ai_settings,screen,ship,bullets,fleet,stats,sb)
            # Update Fleet position
            af.update_empire_ship(ship,ai_settings, fleet,bullets,stats,screen)
        # Refresh Screen
        af.refresh_screen(ai_settings,screen,ship,fleet,bullets,play_button,stats,sb)
Example #14
0
 def __init__(self):
     pygame.init()
     pygame.mixer.init()
     self.screen = pygame.display.set_mode((280, 360))
     self.screen_rect = self.screen.get_rect()
     self.font = pygame.font.Font(None, 50)
     self.font2 = pygame.font.Font(None, 25)
     self.won = False
     self.lost = False
     pygame.display.set_caption("Pacman Portal")
     self.clock = pygame.time.Clock()
     self.maze = Maze(self.screen, 'mazefile1.txt')
     self.p_man = PacMan(self.screen, 25, 13, self.maze)
     self.pinky = Ghost('p', self.p_man, self.screen, self.maze, 16, 14)
     self.blinky = Ghost('b', self.p_man, self.screen, self.maze, 13, 14)
     self.inky = Ghost('i', self.p_man, self.screen, self.maze, 16, 12,
                       self.blinky)
     self.clyde = Ghost('c', self.p_man, self.screen, self.maze, 16, 16)
     self.ghosts = Group()
     self.ghosts.add(self.blinky)
     self.ghosts.add(self.pinky)
     self.ghosts.add(self.inky)
     self.ghosts.add(self.clyde)
     self.stats = GameStats()
     self.pb = Button(self.screen, "Play", 150)
     self.sb = Scoreboard(self.screen, self.stats)
     self.menu_timer = pygame.time.get_ticks()
Example #15
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.init()
    pygame.init()
    game_settings = GameSettings()
    screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("Pac Man Portal")

    # Open sprite sheet
    sprite_sheet = SpriteSheet(file_name='images/spritesheet.png')

    # Make the Play and Scores button.
    play_button = Button(screen=screen, msg="Play", order=0)
    score_button = Button(screen=screen, msg="High Scores", order=1)

    # Open high score file
    try:
        high_score_file = open("high_score_file.txt", "r+")
    except FileNotFoundError:
        high_score_file = open("high_score_file.txt", "w+")

    # Open maze layout file
    maze_file = open('mazelayout.txt', 'r')

    # Make sound manager
    sounds = Sounds()

    # Initialize game stats and scoreboard
    stats = GameStats(game_settings=game_settings)
    sb = Scoreboard(screen=screen, game_settings=game_settings, stats=stats, sprite_sheet=sprite_sheet,
                    high_score_file=high_score_file, sounds=sounds)

    # Initialize pacman
    pacman = Pacman(screen=screen, game_settings=game_settings, stats=stats, sb=sb,
                    image_list=sprite_sheet.pacman_image, death_anim_list=sprite_sheet.pacman_death_image,
                    sounds=sounds)

    # Initialize maze
    maze = Maze(screen=screen, game_settings=game_settings, maze_file=maze_file, sprite_sheet=sprite_sheet,
                pacman=pacman, sounds=sounds)

    # Initialize the event handler
    event_handler = EventHandler(pacman=pacman, play_button=play_button, score_button=score_button, stats=stats, sb=sb,
                                 maze=maze, sounds=sounds)

    # Initialize the display manager
    display = Display(screen=screen, game_settings=game_settings, stats=stats, sb=sb, sprite_sheet=sprite_sheet,
                      play_button=play_button, score_button=score_button, maze=maze, pacman=pacman,
                      event_handler=event_handler, sounds=sounds)

    # Start the main loop for the game
    while True:
        event_handler.check_events()
        if stats.game_active:
            pacman.update(maze=maze, display=display)
            maze.update_ghosts()
            maze.update_bullets()
            maze.update_portals()
        display.update_screen()
    def __init__(self):

        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("Alien Invasion")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.stats = GameStats(self)

        self._create_fleet()
        self.play_button = Button(self, "Play Now")
def run_game(player_name):
	# Initialize game and create a screen object.
	pygame.init()
	cg_settings = Settings()
	screen = pygame.display.set_mode((cg_settings.screen_width, cg_settings.screen_height))
	pygame.display.set_caption("Collect the Eggs!")

	#Make a play button
	play_btn = Button(screen,"Let's Play!!")
	
	#make hidden bsket
	basket_h = Basket_hidden(cg_settings,screen)
	# Make a basket.
	basket = Basket(cg_settings,screen)
	# Make a group of hens.
	hens = []
	#eggs
	eggs_w=Group()
	eggs_g=Group()
	#poops
	poops=Group()
	
	gs = GameStats(cg_settings)
	sb  = Scoreboard(cg_settings,screen,gs)
	sb.prep_score()


	#create the fleet of hens
	gf.create_fleet(cg_settings, screen, hens)
	while True:
		gf.check_events(basket,basket_h,play_btn,gs)
		basket.update()
		basket_h.update(basket)
		gf.eggs_g_update(eggs_g,basket_h,gs,cg_settings.golden_score)
		gf.eggs_w_update(eggs_w,basket_h,gs,cg_settings.white_score)
		gf.poops_update(poops,basket_h,gs,cg_settings.poop_score)
		sb.prep_score()
		if(gs.score>gs.high_score):
			gs.high_score=gs.score
	
		sb.prep_high_score()
		sb.prep_level()

		#gf.create_egg(screen,egg)
		gf.update_screen(cg_settings, screen,sb,basket_h, basket, hens, eggs_w,eggs_g,poops,gs,play_btn)
		gf.check_level_crossed(cg_settings, screen,sb, basket_h,basket, hens, eggs_w,eggs_g, poops,gs,player_name)
Example #18
0
def run_game():
    # calling pygame
    pygame.init()
    setting = Setting()

    # putting the background
    screen = pygame.display.set_mode([setting.width, setting.height])
    background = pygame.transform.scale(pygame.image.load_basic('grass.bmp'),
                                        (setting.width, setting.height))
    backgroundrect = background.get_rect()
    screen.blit(background, backgroundrect)

    # loading the background music and setting a caption
    rabbit = Bunny(screen, setting)
    pygame.display.set_caption("Mouse Infestation")
    pygame.mixer.music.load('moonlight.wav')
    pygame.mixer.music.play(-1, 0.0)
    pygame.mixer.music.set_volume(0.25)

    # calling the classes
    play_button = Button(setting, screen, "Play")
    Health_bar = Health(screen)

    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)
    bullets = Group()
    mice = Group()
    castles = Group()

    gf.create_castle(screen, setting, 80, castles)

    # making a loop for the game
    while True:

        # checking the program
        gf.check_event(setting, screen, stats, play_button, sb, rabbit, mice,
                       bullets)

        # placing the healthbar
        if stats.game_active == False:
            Health_bar.reset_health_bar()

        # summoning the mice(enemies)
        if stats.game_active:
            for mouse in mice:
                if mouse.rect.x < mouse.image.get_rect().centerx:
                    gf.create_fleet(setting, screen, mice)
                    break

            # updating the screen in order for the program to run
            rabbit.update()
            gf.update_bullet(setting, screen, stats, sb, rabbit, bullets, mice)
            gf.update_mouse(setting, Health_bar, screen, rabbit, mice, bullets,
                            castles, stats)
        gf.update_screen(background, backgroundrect, screen, setting, sb,
                         rabbit, stats, bullets, mice, play_button, castles,
                         Health_bar)
Example #19
0
def start_game():
	#INitialise game
	pygame.init()
	ol_settings = Settings()
	screen = pygame.display.set_mode((ol_settings.screen_width,ol_settings.screen_height))
	pygame.display.set_caption("Save Ozone Layer!")
	#The Play button is made.
	play_button = Button(ol_settings,screen,"Play")
	#Load game stats
	stats = GameStats(ol_settings)
	#Dislpay the score.
	sc=ScoreCard(ol_settings,screen,stats)
	#Making a plane.
	plane = Plane(ol_settings,screen)
	#alien=Alien(ol_settings,screen) --See top@import comment
	#Make a group to store bullets in.
	bullets = Group()
	alien_ships = Group()

	#Create swarm of alien egg ships.
	ge.create_swarm(ol_settings,screen,plane,alien_ships)

	#Start the main loop for the game.
	while True:

		#watch for keyboard and mouse events.
		ge.check_events(ol_settings,screen,plane,bullets,stats,play_button,alien_ships,sc)

		#active_status = False when Play button isnt clicked and when the plane limit of 3 is breached.
		if stats.active_status:
			plane.update()
			ge.update_bullets(ol_settings,screen,plane,alien_ships,bullets,stats,sc)
			ge.update_alien_ships(ol_settings,stats,screen,plane,alien_ships,bullets,sc)
		else:
			if stats.high_score_flag:
			#At this point the stats.high_score holds the new highest score.
			#But, it's not written into the file yet. So, let's do it now.
				stats.pickle_high_score()

		#Doesn't depend on active_status.
		ge.update_screen(ol_settings,screen,plane,bullets,alien_ships,play_button,stats,sc)
Example #20
0
def run_game():
    """
    Initialize pygame, make player and platform objects, and run the game loop.
    """
    pygame.init()
    sett = Settings()
    stats = GameStats(sett)
    screen = pygame.display.set_mode((sett.swidth, sett.sheight))
    pygame.display.set_caption("Arena-brawler Roguelike")
    score_display = ScoreDisplay(screen, stats.score)

    player = Player(screen, sett)
    lives = PlayerLives(screen)
    platforms = Group()
    enemies = Group()
    enemy_movement = EnemyMovement()
    start_button = StartButton(screen, "Start... and die.")

    player_attack_right = PlayerFistAttackRight(player, screen)
    player_attack_left = PlayerFistAttackLeft(player, screen)

    platform_1 = Platform(screen, 100, sett.sheight - 200)
    platform_2 = Platform(screen, sett.swidth - platform_1.rect.width - 100,
                          sett.sheight - 200)
    platform_3 = Platform(screen,
                          (sett.swidth / 2) - (platform_1.rect.width / 2),
                          sett.sheight - 400)
    platform_4 = Platform(screen, 100, sett.sheight - 550)
    platform_5 = Platform(screen, sett.swidth - platform_1.rect.width - 100,
                          sett.sheight - 550)

    # Add platform_x to platforms
    platforms.add(platform_1)
    platforms.add(platform_2)
    platforms.add(platform_3)
    platforms.add(platform_4)
    platforms.add(platform_5)

    enemy_counter = sett.enemy_counter
    enemy_counter_threshold = sett.enemy_counter_threshold

    while True:
        # Game loop.
        enemy_counter += 1
        player.player_gravity(platforms, sett, player)
        gf.check_events(player, platforms, sett, player_attack_left,
                        player_attack_right, stats, start_button)
        gf.update_screen(screen, sett, player, platforms, enemies,
                         enemy_counter, enemy_counter_threshold, stats,
                         player_attack_left, player_attack_right,
                         enemy_movement, lives, start_button, score_display)
        if enemy_counter == enemy_counter_threshold:
            enemy_counter = sett.enemy_counter
Example #21
0
 def __init__(self,
              model,
              name,
              title='',
              batch=1000,
              iters=3,
              agent_batch=0,
              agent_monitor=True,
              model_params=None,
              fresh=True,
              save=False,
              grader=None):
     self.model = model
     self.name = name
     self.title = title
     self.batch = batch
     self.iters = iters
     self.agent_batch = agent_batch
     self.agent_monitor = agent_monitor
     self.fresh = fresh
     self.save = save
     self.stats = {}
     self.stat_list = []
     self.model_stats = Stats()
     self.game_stats = GameStats()
     if model_params is None:
         self.model_params = [('', {})]
     else:
         self.model_params = model_params
     if title == '':
         self.title = name
     else:
         self.title = title
     if grader is None:
         self.grader = Grader()
     else:
         self.grader = grader
     self.model_stats.new_tracker(self.name)
     self.game_stats.new_tracker(self.name)
Example #22
0
def run_game():
    # Initialize game
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invaders by Diana Joya")

    # Game Stats
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Screens
    start_screen = Start(ai_settings, screen)
    score_board = HighScores(ai_settings, screen, stats)

    # Sprite Groups
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    bunkers = Group()
    random_ufo = UFO(ai_settings, screen)
    bullet_animation = BulletAnimation(ai_settings, screen, ship, bullets,
                                       aliens, stats, sb, random_ufo, bunkers)

    events = Update(ai_settings, screen, ship, bullets, aliens, stats, sb,
                    start_screen, score_board, random_ufo, bunkers)
    collision = Collisions(ai_settings, screen, ship, bullets, aliens, stats,
                           sb, start_screen, score_board, random_ufo, bunkers)

    # Game Loop
    while True:
        events.check_events()

        if stats.game_active:
            current_time = pygame.time.get_ticks()
            ship.update()
            bullet_animation.update_bullets()
            collision.update_aliens()
            bunkers.update()
            if ai_settings.ufo_allowed:
                random_ufo.update(current_time)

        events.update_screen()
Example #23
0
def run_game():
    '''main toplevel function for the game'''
    # Init game, settings and create a screen object
    pygame.init()
    settings = Settings()
    screen_x, screen_y = settings.screen_width, settings.screen_height
    screen = pygame.display.set_mode((screen_x, screen_y))
    stats = GameStats(settings)
    pygame.display.set_caption("Alien Invasion")

    # Create containers for application objects so arg passing to functions isn't bloated
    MetaObjs = namedtuple('MetaObj',
                          'settings screen stats buttons scoreboard')
    GameObjs = namedtuple('GameObj', 'ship bullets aliens stars alien_bullets')
    Buttons = namedtuple('Buttons', 'play pause')

    # Prep up buttons
    buttons = Buttons(play=Button(settings, screen, 'Click to Start'),
                      pause=Button(settings, screen, 'Paused'))

    meta_objs = MetaObjs(settings=settings,
                         screen=pygame.display.set_mode((screen_x, screen_y)),
                         stats=stats,
                         buttons=buttons,
                         scoreboard=Scoreboard(settings, screen, stats))

    game_objs = GameObjs(ship=Ship(settings, screen),
                         bullets=Group(),
                         stars=Group(),
                         aliens=Group(),
                         alien_bullets=Group())

    # Create first alien fleet
    create_alien_fleet(meta_objs, game_objs)

    # Main game loop
    while True:
        game_objs.stars.add(Star(meta_objs.settings, meta_objs.screen))
        check_events(meta_objs, game_objs)
        if meta_objs.stats.active:
            game_objs.ship.update()
            update_bullets(meta_objs, game_objs)
            update_aliens(meta_objs, game_objs)
        update_screen(meta_objs, game_objs)
Example #24
0
def run_game():
    # 初始化游戏并创建屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("外星人")

    # 创建play按钮
    play_button = Button(ai_settings, screen, "play")

    # 创建外星人
    alien = Alien(ai_settings, screen)

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # 创建用于储存数据的实例
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # 创建外星人群
    fun.create_fleet(ai_settings, screen, ship, aliens)

    # 开始游戏的主循环
    while True:
        fun.check_events(ai_settings, screen, stats, play_button, ship, aliens,
                         bullets)
        if stats.game:
            ship.update()
            fun.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                               bullets)
            fun.update_aliens(ai_settings, stats, screen, ship, aliens,
                              bullets)
        fun.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                          bullets, play_button)
Example #25
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Example #26
0
from pygame.sprite import Group

from scoreboard import Scoreboard
from settings import Settings
from game_objects import Player, Background
import game_fuction as gf
from stats import GameStats
from button import Button

pygame.init()
pygame.display.set_caption('Catch This')
ct_settings = Settings()
screen = pygame.display.set_mode((ct_settings.width, ct_settings.height))
clock = pygame.time.Clock()
stats = GameStats(ct_settings)
sb = Scoreboard(ct_settings, stats, screen)
play_button = Button(screen, 'Play')

#Groups
friends = Group()
enemies = Group()
bonus = Group()

#Game objects
player = Player(ct_settings, screen)
background = Background(ct_settings, screen)

while True:
    gf.check_events(bonus, ct_settings, enemies, friends, play_button, player, sb, stats)
    if stats.game_active:
class AlienInvasion:
    def __init__(self):

        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("Alien Invasion")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.stats = GameStats(self)

        self._create_fleet()
        self.play_button = Button(self, "Play Now")

    def run_game(self):

        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    def _check_events(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)

        if button_clicked and not self.stats.game_active:
            self.stats.reset_stats()
            self.settings.initialize_dynamic_settings()
            self.stats.game_active = True

            self.aliens.empty()
            self.bullets.empty()
            self._create_fleet()
            self.ship.center_ship()

            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):

        if event.key == pygame.K_d:
            self.ship.moving_right = True
        elif event.key == pygame.K_a:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):

        if event.key == pygame.K_d:
            self.ship.moving_right = False
        elif event.key == pygame.K_a:
            self.ship.moving_left = False

    def _fire_bullet(self):

        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):

        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self.check_alien_collisions()

    def check_alien_collisions(self):
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

    def _update_screen(self):

        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        self.aliens.draw(self.screen)

        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self.ship_hit()

        self._check_aliens_bottom()

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        rows = available_space_y // (2 * alien_height)

        for rowN in range(rows):
            for number in range(number_aliens_x):
                self._create_alien(number, rowN)

    def _create_alien(self, number, rowN):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * rowN
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def ship_hit(self):
        if self.stats.ships_left > 0:
            self.stats.ships_left -= 1
            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.center_ship()

            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()

        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break
Example #28
0
def run_game():
    pygame.init()

    # Запускает matlotlib во встроенном режиме
    matplotlib.use("Agg")

    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    screen_rect = screen.get_rect()
    stats = GameStats(settings)

    # Generating Data
    np.seterr(divide='ignore', invalid='ignore')

    # Данные для графиков

    #x1,y1

    # Creating graph objects

    scoreboard = Scoreboard(settings, screen, stats)

    pygame.display.set_caption("Graph")
    pygame.display.set_icon(pygame.image.load("stocks.bmp"))

    # Menu buttons
    start_button = Button(settings,
                          screen,
                          stats,
                          scoreboard, (400, 250),
                          'Start', (0, 100, 0),
                          callback=start_game)
    exit_button = Button(settings,
                         screen,
                         stats,
                         scoreboard, (400, 350),
                         'Exit', (100, 0, 0),
                         callback=exit_game)

    # Game buttons

    # level1 game elements

    # buttons
    skip_button1 = Button(settings,
                          screen,
                          stats,
                          scoreboard, (400, 550),
                          'Skip', (0, 0, 100),
                          callback=skip_game)

    answer_button1 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (200, 500),
                            'Answer 1', (0, 0, 50),
                            callback=wrong_button_l1)
    answer_button2 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (400, 500),
                            'Answer 2', (0, 0, 50),
                            callback=correct_button_l1)
    answer_button3 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (600, 500),
                            'Answer 3', (0, 0, 50),
                            callback=wrong_button_l1)
    # data
    x1 = np.linspace(-2, 2, 100)
    y1 = (x1**3)

    z1 = np.around(np.arange(-10, 10, 1), decimals=4)
    k1 = (z1**2)

    a1 = np.around(np.arange(-10, 10, 1), decimals=4)
    b1 = a1

    #graph
    graphs1 = Graph(x1, y1, z1, k1, a1, b1, screen)

    # level2_game_elements

    # buttons
    skip_button2 = Button(settings,
                          screen,
                          stats,
                          scoreboard, (400, 550),
                          'Skip', (0, 0, 100),
                          callback=skip_game)

    answer_button4 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (200, 500),
                            'Answer 1', (0, 0, 50),
                            callback=correct_button_l2)
    answer_button5 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (400, 500),
                            'Answer 2', (0, 0, 50),
                            callback=wrong_button_l2)
    answer_button6 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (600, 500),
                            'Answer 3', (0, 0, 50),
                            callback=wrong_button_l2)
    # data
    x2 = np.around(np.arange(-10, 10, 1), decimals=4)
    y2 = np.sin(x2)

    z2 = np.around(np.arange(-10, 10, 1), decimals=4)
    k2 = np.exp(z2)

    a2 = np.around(np.arange(-10, 10, 1), decimals=4)
    b2 = np.cos(a2)

    #graphs
    graphs2 = Graph(x2, y2, z2, k2, a2, b2, screen)

    # level3_game_elements

    #buttons
    skip_button3 = Button(settings,
                          screen,
                          stats,
                          scoreboard, (400, 550),
                          'Skip', (0, 0, 100),
                          callback=skip_game)

    answer_button7 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (200, 500),
                            'Answer 1', (0, 0, 50),
                            callback=wrong_button_l3)
    answer_button8 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (400, 500),
                            'Answer 2', (0, 0, 50),
                            callback=wrong_button_l3)
    answer_button9 = Button(settings,
                            screen,
                            stats,
                            scoreboard, (600, 500),
                            'Answer 3', (0, 0, 50),
                            callback=correct_button_l3)
    # data

    x3 = np.around(np.arange(-10, 10, 1), decimals=4)
    y3 = np.log(x3)

    z3 = np.around(np.arange(-10, 10, 1), decimals=4)
    k3 = np.sqrt(z3)

    a3 = np.around(np.arange(-10, 10, 1), decimals=4)
    b3 = np.cbrt(a3)

    # graphs
    graphs3 = Graph(x3, y3, z3, k3, a3, b3, screen)

    menu_buttons = Group(start_button, exit_button)

    game_buttons1 = Group(answer_button1, answer_button2, answer_button3,
                          skip_button1)
    game_buttons2 = Group(answer_button4, answer_button5, answer_button6,
                          skip_button2)
    game_buttons3 = Group(answer_button7, answer_button8, answer_button9,
                          skip_button3)

    while True:
        update_screen(settings, screen, stats, menu_buttons, scoreboard,
                      game_buttons1, game_buttons2, game_buttons3, graphs1,
                      graphs2, graphs3)
        check_events(settings, screen, stats, menu_buttons, game_buttons1,
                     game_buttons2, game_buttons3, scoreboard)
Example #29
0
class BouncingBall:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        # Clock set-up for framerate
        self.clock = pygame.time.Clock()
        self.settings = Settings()
        self.stats = GameStats(self)
        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("Bouncing Ball")
        self.bar = Bar(self)
        self.ball = Ball(self)
        self.timebar = TimeBar(self)
        self.play_button = Button(self, 'Play')

    def run_game(self):
        """Main game loop."""
        while True:
            self._check_events()
            if self.stats.game_active:
                self._ball_checks()
                self.ball.update()
                self.bar.update() # implements movement depending on movement flag
                self.timebar.update(self)
                self._time_check(self.start)
            self._update_screen()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            # Pressing arrow keys for movement:
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            # Releasing arrow keys:
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        """Checks keydown events."""
        if event.key == pygame.K_RIGHT:
            self.bar.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.bar.moving_left = True
        elif event.key == pygame.K_ESCAPE:
            sys.exit()

    def _check_play_button(self, mouse_pos):
        """Restart game when Play button is clicked."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked:
            self._click_play()

    def _click_play(self):
        pygame.mouse.set_visible(False)
        self.stats.reset_stats()
        self.settings.initialize_settings()
        self.bar.center_bar()
        self.ball._init_old_pos()
        self.stats.game_active = True
        self.start = perf_counter()

    def _check_keyup_events(self, event):
        """Checks keyup events."""
        if event.key == pygame.K_RIGHT:
            self.bar.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.bar.moving_left = False

    def _ball_checks(self):
        self._check_ball_bar_collision()
        self._check_ball_lost()

    def _check_ball_bar_collision(self):
        if pygame.sprite.collide_rect(self.ball, self.bar):
            print('Bounce!')
            self.ball.bounce = True

    def _check_ball_lost(self):
        """Reset game if ball drops below bottom edge"""
        if self.ball.rect.top >= self.settings.screen_height:
            self._restart_game()

    def _time_check(self, start):
        """Increase game difficulty if session duration has elapsed."""
        if perf_counter() - start >= self.settings.session_duration:
            self.start = perf_counter()
            self.settings.increase_game_difficulty()

    def _restart_game(self):
        """Take action if ball is lost"""
        if self.stats.ball_left > 0:
            self.ball._init_old_pos()
            self.stats.ball_left -= 1
            sleep(0.5)
        else:
            pygame.mouse.set_visible(True)
            self.stats.game_active = False

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.bar.draw_bar()
        self.timebar.draw_timebar()
        self.ball.draw_ball()
        if not self.stats.game_active:
            self.play_button.draw_button()
        pygame.display.flip()
        self.clock.tick(150)
Example #30
0
class Pipe(object):
    def __init__(self,
                 model,
                 name,
                 title='',
                 batch=1000,
                 iters=3,
                 agent_batch=0,
                 agent_monitor=True,
                 model_params=None,
                 fresh=True,
                 save=False,
                 grader=None):
        self.model = model
        self.name = name
        self.title = title
        self.batch = batch
        self.iters = iters
        self.agent_batch = agent_batch
        self.agent_monitor = agent_monitor
        self.fresh = fresh
        self.save = save
        self.stats = {}
        self.stat_list = []
        self.model_stats = Stats()
        self.game_stats = GameStats()
        if model_params is None:
            self.model_params = [('', {})]
        else:
            self.model_params = model_params
        if title == '':
            self.title = name
        else:
            self.title = title
        if grader is None:
            self.grader = Grader()
        else:
            self.grader = grader
        self.model_stats.new_tracker(self.name)
        self.game_stats.new_tracker(self.name)

    def run_models(self, model_shape, realistic):
        for param_name, model_params in self.model_params:
            # get model name based on inputs
            if self.fresh:
                model = self.model(**model_params)
            else:
                model_name = self._name_model(model_shape, realistic,
                                              param_name)
                model = load_net(model_name)
            scores = self._model_trial(model, model_shape, realistic)
            self._log_run(model, model_shape, realistic, param_name, scores)
        self._save_stats()

    def _log_run(self, model, model_shape, realistic, param_name, scores):
        model_name = self._name_model(model_shape, realistic, param_name)
        model_scores, game_scores = scores
        stats_name = '-'.join([model_name, param_name])
        self.model_stats.set_stat(self.name, stats_name, model_scores)
        self.game_stats.set_stat(self.name, stats_name, game_scores)
        self._save_model(model, model_name)

    def _name_model(self, model_shape, realistic, param_name):
        shape_tag = 'S' + 'x'.join(map(str, model_shape))
        realism = 'mock'
        if not realistic:
            realism = 'rndm'
        name_tags = [self.name, shape_tag, realism]
        if param_name != '':
            param_tag = 'P_' + param_name
            name_tags.append(param_tag)
        return '-'.join(name_tags)

    def _save_stats(self):
        iters = 'x'.join(map(str, [self.iters, self.batch]))
        self.model_stats.save_stats(name='model', iters=iters)
        game_iters = 'x'.join(map(str, [self.iters, self.batch]))
        self.game_stats.save_stats(name='game', iters=game_iters)

    def _save_model(self, model, model_name):
        if not self.save:
            return
        save_net(model, model_name)

    def _model_trial(self, model, model_shape, realistic):
        # Train Model Against Sample Data
        model_scores = []
        agent_scores = []
        for i in range(self.iters):
            states, grades = create_samples(self.grader,
                                            self.batch,
                                            sample_shape=model_shape,
                                            realistic=realistic)
            # Check if the trial is batch training
            if self.iters > 1:
                # Partially fit the model since this will occur self.iters times
                print 'training model: %', (i * 100.0 / self.iters)
                model.partial_fit(states, grades)
            else:
                model.fit(states, grades)
            # Score Net mid-training
            model_score = test_score_net(model,
                                         self.batch,
                                         sample_shape=model_shape,
                                         realistic=realistic)
            model_scores.append(model_score)
            # Check if agent trials should occur mid-training
            if self.agent_monitor and self.agent_batch > 0:
                # Do mid-training agent trials
                agent_results = agent_trial(model, model_shape,
                                            self.agent_batch)
                agent_scores.append(agent_results)
        # Full Agent Trial
        if self.agent_batch > 0:
            agent_results = agent_trial(model, model_shape, self.agent_batch)
            agent_scores.append(agent_results)
        return model_scores, agent_scores