def test_move(): gc = GameController(800, 800) b = Board(800, 800, gc) p2 = Player2(b, gc) p2.move() assert p2.board.squares.tile_counts["black"] == 1 assert p2.board.squares.tile_counts["white"] == 4
def load_level(): """Generates a new random level.""" GAME['level'] = Level() GAME['level'].generate_solvable(8, 12, 0.2, 0.4, 0.05, 1, 3, 3) GAME['level'].save('tmp') GAME['player'] = Player2(GAME['level']) display_all() cli.display_toolbar() cli.handle_action()
def init_game(): pygame.init() game_settings = Settings() screen=pygame.display.set_mode((game_settings.screen_width,game_settings.screen_height)) player1 = Player1(screen) player2 = Player2(screen) while True: pygame.time.delay(30) g_f.check_events(game_settings, player1, player2 , screen) g_f.update_screen(screen, game_settings,player1, player2) player1.update() player2.update()
def enter(): gfw.world.init( ['bg', 'bg2', 'cloud', 'ball', 'player1', 'player2', 'goal', 'score']) bg = Background('bg.jpg') gfw.world.add(gfw.layer.bg, bg) bg2 = Background2('grass.jpg') gfw.world.add(gfw.layer.bg2, bg2) cloud = HorzScrollBackground('clouds2.png') cloud.speed = 10 gfw.world.add(gfw.layer.cloud, cloud) ball.init() gfw.world.add(gfw.layer.ball, ball) global player1, player2 player1 = Player() gfw.world.add(gfw.layer.player1, player1) player2 = Player2() gfw.world.add(gfw.layer.player2, player2) goal.init() gfw.world.add(gfw.layer.goal, goal) global score score = Score(get_canvas_width() // 2 + 40, 580) gfw.world.add(gfw.layer.score, score) game_set.init() global time, font, check, DELTA_TIME, GOAL_image, goal_sound time = 60 font = gfw.font.load(('res/NAL Hand.otf'), 50) check = 0 DELTA_TIME = 0 GOAL_image = gfw.image.load('res/goalll.png') goal_sound = load_wav('res/shout.wav') goal_sound.set_volume(50)
def game(): #initializes pygame pygame.init() #initializes pygame.mixer pygame.mixer.init() #defines the colors that will be used in this game black = (0, 0, 0) white = (255, 255, 255) #sets the height and width for the screen and displays the screen size = [512, 256] screen = pygame.display.set_mode(size) #title for our window pygame.display.set_caption("Pong") #adds sprites into a group all_sprites_list = pygame.sprite.Group() #defines the color, height, width and position of the player1 player1 = Player1(white, 5, 28) player1.rect.x = 512 player1.rect.y = 117 #defines the color, height, width and position of the player2 player2 = Player2(white, 5, 28) player2.rect.x = 0 player2.rect.y = 117 #defines the color, height, width and position for the arena arena = Arena(white, 1, 256) arena.rect.x = 256 arena.rect.y = 0 #defines the color, height, width and position of the ball ball = Ball(white, 5, 5) ball.rect.x = 256 ball.rect.y = 128 #keeps track of the balls direction ballDirX = -1 ballDirY = -1 #checks which directory pygame is looking at when finding sound effects os.getcwd() #creates a sound effect when the ball hits the wall walleffect = pygame.mixer.Sound('wall.wav') #creates a sound effect when the ball hits a player playereffect = pygame.mixer.Sound('player.wav') #creates a sound effect when a player scores scoreffect = pygame.mixer.Sound('score.wav') #adds player1, player2, ball and arena into sprites all_sprites_list.add(player1) all_sprites_list.add(player2) all_sprites_list.add(ball) all_sprites_list.add(arena) #initializes the clock (this will be used for the FPS of the game) clock = pygame.time.Clock() #defines player 1 initial score player1score = 0 #defines player 2 initial score player2score = 0 #checks if the ball collides with the wall def checkEdgeCollision(ball, ballDirX, ballDirY): #if the ball is outside of the top and bottom screen borders if ball.rect.top == 0 or ball.rect.bottom == 256: #change the balls direction (y axis) ballDirY = ballDirY * -1 #play the wall sound effect walleffect.play() return ballDirX, ballDirY #checks if the ball collides with either of the players def checkPlayerCollision(ball, player1, player2, ballDirx): #if the ball collides with player 2 if ballDirX == -1 and ball.rect.left == player2.rect.right and player2.rect.top < ball.rect.top and player1.rect.bottom > ball.rect.bottom: #play the player sound effect playereffect.play() #change the direction of the ball (x axis) return -1 #if the ball collides with player 1 elif ballDirX == 1 and ball.rect.right == player1.rect.left and player1.rect.top < ball.rect.top and player1.rect.bottom > ball.rect.bottom: #play the player sound effect playereffect.play() #change the direction of the ball (x axis) return -1 #if the ball doesn't collide with either of the players, do nothing. else: return 1 #a function that makes the ball move def moveBall(ball, ballDirX, ballDirY): #changes the position of the balls x axis according to ballDirX ball.rect.x += ballDirX # hanges the position of the balls y axis according to ballDirY ball.rect.y += ballDirY #returns ball return ball #checks if player1 has scored def checkScore(ball, player1score): if ball.rect.x < 0: #player 1 score increases by 1 player1score += 1 #plays the score sound effect scoreffect.play() #resets the ball reset() #returns player 1 score return player1score else: return player1score #checks if player2 has scored def checkScore2(ball, player2score): if ball.rect.x > 512: #player 2 score increases bt 1 player2score += 1 #plays the score sound effect scoreffect.play() #resets the ball reset() #returns player 2 score return player2score else: return player2score #resets the ball def reset(): ball.rect.x = 256 ball.rect.y = 128 ballDirX = -1 ballDirY = -1 #defines running as False, end as False and start as True (these are all while loops) end = False running = False start = True #while loop for start screen while start: #fills the screen as black screen.fill(black) #gets the font pong.ttf myfont = pygame.font.Font("pong.ttf", 50) myfont2 = pygame.font.Font("pong.ttf", 30) #creates the "Pong" text in white label = myfont.render("Pong", 1, (255, 255, 255)) #creates the "Press Enter to Play" text in grey with a white background label2 = myfont2.render("Press Enter to Play", 1, (49, 79, 79), (255, 255, 255)) #displays label and label 2 on the screen screen.blit(label, (200, 100)) screen.blit(label2, (110, 150)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: #if the player presses Enter if event.key == pygame.K_RETURN: #play the score effect scoreffect.play() #end the start while loop start = False #start the game while loop running = True #if the play presses 'x' if event.key == pygame.K_x: #end the start while loop start = False #quit pygame pygame.quit() #exit the system sys.exit() #if the player clicks the x button if event.type == pygame.QUIT: #end the start while loop start = False #quit pygame pygame.quit() #exist system sys.exit() #while loop for main game running = True end = False while running: for event in pygame.event.get(): #if the player closes the window the game quits if event.type == pygame.QUIT: running = False pygame.quit() sys.exit() #if the player clicks the "x" button the game quits elif event.type == pygame.KEYDOWN: if event.key == pygame.K_x: running = False pygame.quit() sys.exit() #updates the display pygame.display.update() #defines keys as the pygame functions key.get_pressed() keys = pygame.key.get_pressed() #controls for player 1 if keys[pygame.K_UP]: player1.moveUp(4) if keys[pygame.K_DOWN]: player1.moveDown(4) #creates border for player 1 if player1.rect.right > 512: player1.rect.right = 512 if player1.rect.left < 256: player1.rect.left = 256 if player1.rect.bottom > 256: player1.rect.bottom = 256 if player1.rect.top < 0: player1.rect.top = 0 #controls for player 2 if keys[ord('w')]: player2.moveUp(4) if keys[ord('s')]: player2.moveDown(4) #creates border for player 2 if player2.rect.right > 256: player2.rect.right = 256 if player2.rect.left < 0: player2.rect.left = 0 if player2.rect.bottom > 256: player2.rect.bottom = 256 if player2.rect.top < 0: player2.rect.top = 0 pygame.display.flip() #updates all sprites all_sprites_list.update() #colors the screen as black screen.fill(black) #draws all the sprites onto the screen all_sprites_list.draw(screen) #60 frames per second clock.tick(60) #calls the move method, makes the ball move ball = moveBall(ball, ballDirX, ballDirY) #checks for a collision between the ball and the wall and changes the direction accordingly ballDirX, ballDirY = checkEdgeCollision(ball, ballDirX, ballDirY) #checks for a collision between the ball and the player and changes the direction accordingly ballDirX = ballDirX * checkPlayerCollision(ball, player1, player2, ballDirX) #checks if player1 scored and adds the point to player1score if they did player1score = checkScore(ball, player1score) #checks if player 2 scored and adds the point to player2score if they did player2score = checkScore2(ball, player2score) #gets the font pong.ttf myfont = pygame.font.Font("pong.ttf", 75) myfont2 = pygame.font.Font("pong.ttf", 75) #gets the text for the score for player 1 and player 2 label = myfont.render(str(player2score), 1, (255, 255, 255)) label2 = myfont2.render(str(player1score), 1, (255, 255, 255)) #displays the text on screen screen.blit(label, (110, 20)) screen.blit(label2, (370, 20)) pygame.display.flip() winner = '' #if player 1 reaches 10 points if player1score == 10: #starts the game over while loop end = True winner = 'Player 1 Wins!' #if player 2 reaches 10 points if player2score == 10: #starts the game over while loop end = True winner = 'Player 2 Wins!' #game over while loop while end: #makes the screen black screen.fill(black) #gets the font pong.ttf myfont = pygame.font.Font("pong.ttf", 50) myfont2 = pygame.font.Font("pong.ttf", 20) #creates the text for the game over screen label = myfont.render("GAME OVER", 1, (255, 255, 255)) label2 = myfont2.render("Press Enter to Play Play Again", 1, (255, 255, 255)) label3 = myfont2.render(winner, 1, (255, 255, 255)) #displays the text and the screen screen.blit(label, (135, 100)) screen.blit(label2, (105, 150)) screen.blit(label3, (180, 200)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: #if the play presses return if event.key == pygame.K_RETURN: #restart the game game() #if the user presses x if event.key == pygame.K_x: pygame.quit() #quit the game sys.exit() #if the user clicks the exit button in the window if event.type == pygame.QUIT: pygame.quit() #quit the game sys.exit()
room['foyer'].s = room['outside'] room['foyer'].n = room['overlook'] room['foyer'].e = room['narrow'] room['overlook'].s = room['foyer'] room['narrow'].w = room['foyer'] room['narrow'].n = room['treasure'] room['treasure'].s = room['narrow'] # # Main # player = Player(room['outside']) # # player = Player2(room['outside']) player2 = Player2(room['outside']) print( "Welcome to this magical land! Explore the cave and come out with riches, or die and absolutely horrific death! >:D" ) # Make a new player object that is currently in the 'outside' room. while True: # Write a loop that: # If the user enters "q", quit the game. vinputs = ('n', 's', 'e', 'w') print(player2.location) player2.print_items() command = input("> ").split(',') if command[0] == 'n' or command[0] == 's' or command[0] == 'w' or command[
def start_policy_iteration(): cli.clear_status() display_all() cli.display("Starting Policy Iteration...") policy = policy_iteration.solve_p_i(0.99, GAME['level']) cli.add_status("Policy iteration done.") GAME['user_loop'] = True while GAME['user_loop']: GAME['level'].load(GAME['level'].name) player = Player2(GAME['level'], HP=5) GAME['player'] = player cli.add_status("Press (space) to apply next move in policy.") cli.add_status("Press (e) to quit.") while not (player.is_dead() or player.win) \ and GAME['user_loop']: state = player.get_state() x, y = player.x_pos, player.y_pos next_direction = policy[state][y][x] display_all() for line in get_policy_disp(policy, state): cli.display(line) # cli.display("Next direction is {}".format(next_direction)) cli.handle_action() if next_direction == 'u': player.move_up() if next_direction == 'd': player.move_down() if next_direction == 'l': player.move_left() if next_direction == 'r': player.move_right() _, continue_reaction = player.grid_reaction() while continue_reaction: _, continue_reaction = player.grid_reaction() if player.is_dead(): break # End of game cli.clear_status() if GAME['player'].is_dead(): cli.add_status('GAME OVER') cell = GAME['level'].grid[GAME['player'].y_pos][ GAME['player'].x_pos] if cell == 'C': cli.add_status('You fell into a crack and died.') elif cell == 'E': cli.add_status('An enemy killed you.') elif cell == 'R': cli.add_status('You walked into a deadly trap.') else: cli.add_status('You died.') if GAME['player'].win: cli.add_status('GAME WON') if not GAME['user_loop']: break display_all() cli.display("Press any key to continue.") cli.handle_action() cli.clear_status() display_all() cli.display("Press (e) to quit.") cli.wait_for_action('e')
def user_play(): """Start the user loop where the user can play the game using the arrow keys on linux or WASD/ZQSD on windows.""" cli.add_action( 'KEY_UP', (lambda: GAME.__setitem__('player_moved', GAME['player'].move_up()))) cli.add_action( 'KEY_DOWN', (lambda: GAME.__setitem__('player_moved', GAME['player'].move_down()))) cli.add_action('KEY_RIGHT', ( lambda: GAME.__setitem__('player_moved', GAME['player'].move_right()))) cli.add_action( 'KEY_LEFT', (lambda: GAME.__setitem__('player_moved', GAME['player'].move_left()))) GAME['user_loop'] = True while GAME['user_loop']: GAME['player'] = Player2(GAME['level']) cli.add_status( "You can play with ZQSD on Windows or the arrow keys on unix.") cli.add_status("Press (e) to exit.") while not (GAME['player'].win or GAME['player'].is_dead()): display_all() # Reset game state GAME['player_moved'] = False # Handle user input cli.handle_action() _, continue_reaction = GAME['player'].grid_reaction() while continue_reaction: _, continue_reaction = GAME['player'].grid_reaction() if GAME['player'].is_dead(): break # End of game cli.clear_status() if GAME['player'].is_dead(): cli.add_status('GAME OVER') cell = GAME['level'].grid[GAME['player'].y_pos][ GAME['player'].x_pos] if cell == 'C': cli.add_status('You fell into a crack and died.') elif cell == 'E': cli.add_status('An enemy killed you.') elif cell == 'R': cli.add_status('You walked into a deadly trap.') else: cli.add_status('You died.') if GAME['player'].win: cli.add_status('GAME WON') if not GAME['user_loop']: break display_all() cli.display("Press any key to continue.") cli.handle_action() cli.clear_status() display_all() cli.display("Press (e) to quit.") cli.wait_for_action('e')
def optimize_menu(): cli.add_action("1", start_value_iteration) cli.add_action("2", start_policy_iteration) cli.add_action("3", start_qlearning) cli.clear_status() cli.add_status("Press (1) to start Value Iteration algorithm.") cli.add_status("Press (2) to start Policy Iteration algorithm.") cli.add_status("Press (3) to start QLearning algorithm.") display_all() cli.wait_for_action('1', '2', '3', 'e') if __name__ == "__main__": cli = get_cli() cli.add_action('exit', quit_app, toolbar=True) cli.add_action('load level', load_level, toolbar=True) cli.add_action('play', user_play, toolbar=True) cli.add_action('optimize', optimize_menu, toolbar=True) GAME['level'] = Level() GAME['level'].load("instances/lvl-n8-0") GAME['player'] = Player2(GAME['level']) display_all() cli.display_toolbar() cli.wait_for_action('e', 'l', 'p', 'o')
def test_constructor(): gc = GameController(800, 800) b = Board(800, 800, gc) p2 = Player2(b, gc) assert p2.board is b assert p2.gc is gc
from player1 import Player1 from player2 import Player2 if __name__ == "__main__": engine = GameEngine(YELLOW, RED) engine.init_display() # TODO: Separate AgentGlobalParams (HyperParams?) and AgentTurnParams human_agent = HumanAgent(params={'display': engine.display}) random_agent = RandomAgent() minimax_agent = MiniMaxAgent(params={ 'depth': 5, 'alpha': -math.inf, 'beta': math.inf, 'maximizingPlayer': True }) human_player1 = Player1(human_agent, "Human 1") human_player2 = Player2(human_agent, "Human 2") minimax_player1 = Player1(minimax_agent, "MiniMax 1") minimax_player2 = Player2(minimax_agent, "MiniMax 2") random_player1 = Player1(random_agent, "Random 1") random_player2 = Player2(random_agent, "Random 2") # engine.start_game(minimax_player1, minimax_player2) engine.start_game(random_player1, random_player2) # engine.start_game(human_player1, random_player2) engine.main_loop()
def reset(self): """Resets the player and level objects used by the algorithm.""" self.player = Player2(self.level, HP=self.player_health) self.level.load(self.level_name)
def __init__(self,gamestate,score,ammo): # Konfuguracja random.seed() #inicjalizaja pygame.init() self.SCREEN_SIZE = (1280, 720) # grafiki dopasowane do tego self.screen = pygame.display.set_mode(self.SCREEN_SIZE) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.shot = 0.0 self.supertime = -2 self.player = Player(self) self.player2 = Player2(self) self.aliens = [] self.opp = 10 self.bullets = [] self.alienbulets = [] self.lives = Livesb(self) self.lives_number = 3 self.score = Score(self) self.score_number = 0 + score self.ammo = Ammo(self) self.walls = [] self.gameover = GameOver(self) self.gamestate = gamestate self.ammo_number = ammo + 5 self.nextlevel = NextLevel(self) self.tps_max = 300.0 self.superalien = [] self.tooClose = False self.pauseSign = Pause(self) self.pause = 1 for i in range(0,self.opp): self.aliens.append(Alien(self, i * 100 + 100, 100,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 150,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 200,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 250,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 300,self.gamestate-1)) self.aliens.append(Alien(self, i * 100 + 100, 350,self.gamestate-1)) self.rand_opp = 6*self.opp for i in range(0,5): self.walls.append(Wall(self,80+i*340)) channel_game = pygame.mixer.Channel(1) channel_game2 = pygame.mixer.Channel(2) channel_game3 = pygame.mixer.Channel(3) self.background = pygame.image.load("tlo3.jpg") while self.gamestate !=0: if self.rand_opp != 0: los = random.randrange(self.rand_opp) else: los = 0 # obsługa zdarzen for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player.pos[0]+23,self.player.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) elif (self.lives_number == 0 or self.ammo_number <= 0 or self.tooClose == True) and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate = 0 elif len(self.aliens) == 0 and event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.gamestate += 1 Game_b(self.gamestate,self.score_number,self.ammo_number) self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and self.pause == -1: self.gamestate = 0 elif event.type == pygame.KEYDOWN and event.key == pygame.K_p and self.pause == -1: self.pause *= -1 elif event.type == pygame.KEYDOWN and event.key == pygame.K_LCTRL and self.ammo_number != 0: self.bullets.append(Bullet(self,self.player2.pos[0]+23,self.player2.pos[1])) channel_game3.play(pygame.mixer.Sound("mygun.wav")) channel_game3.set_volume(0.5) #ticking self.tps_delta += self.tps_clock.tick() / 1000.0 self.shot += self.tps_clock.tick()+0.000000003*(self.gamestate-1) / 1.0 self.supertime += self.tps_clock.tick() / 1.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max while(self.shot >= 0.001 / self.tps_max and len(self.aliens)!=0 and (self.lives_number != 0 and self.ammo_number > 0) and self.tooClose == False and self.pause == 1): self.shot = 0 channel_game.play(pygame.mixer.Sound("shot.wav")) channel_game.set_volume(0.5) self.alienbulets.append(AlienBullet(self,self.aliens[los].x,self.aliens[los].y)) while self.supertime >= 0.001 / self.tps_max: self.supertime = -2 if(len(self.superalien)==0 and self.tooClose == False and self.lives_number !=0 and self.ammo_number > 0 and self.pause == 1): self.superalien.append(SuperAlien(self)) channel_game2.play(pygame.mixer.Sound("supersound.wav")) channel_game2.set_volume(0.3) #rendering self.screen.fill((0, 0, 0)) self.screen.blit(self.background, (0, 0)) self.draw() pygame.display.flip()
else: return 0 elif value1 == 2: if value2 == 0: return 1 elif value2 == 1: return 2 else: return 0 else: return 0 # インスタンス生成 player1 = Player1() player2 = Player2() for n in range(10): player1.janken_method() player2.janken_method(n) win_num = judge_method(player1.value, player2.value) if win_num == 1: player1.win_num = player1.win_num + 1 elif win_num == 2: player2.win_num = player2.win_num + 1 print("出した手:%d, %d" % (player1.value, player2.value)) print("勝ち数:%d, %d" % (player1.win_num, player2.win_num)) print("")