From 53dc8464e98d8b1953f015d3b37c86f1267f4a6f Mon Sep 17 00:00:00 2001 From: Theouche Date: Wed, 31 Jul 2024 15:19:15 +0200 Subject: [PATCH] merge avec chakib, pb duration --- pong/game/game.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/pong/game/game.py b/pong/game/game.py index fc234ec..f9f70c8 100644 --- a/pong/game/game.py +++ b/pong/game/game.py @@ -4,6 +4,51 @@ import json import asyncio import random +class BotPlayer: + def __init__(self, game_state, speed): + self.game_state = game_state + self.speed = speed + + async def update_bot_position(self): + print("Update bot position started") + try: + target_y = self.predict_ball_position() + #print(f"Target Y: {target_y}") + player2_position = self.game_state['player2_position'] + #print(f"Player2 Position: {player2_position}") + + if player2_position < target_y < player2_position + 80: + print("Bot is already aligned with the ball, no move needed.") + elif player2_position < target_y: + new_position = min(player2_position + (5 * self.speed), 300) + print(f"Moving bot down to {new_position}") + self.game_state['player2_position'] = new_position + elif player2_position + 80 > target_y: + new_position = max(player2_position - (5 * self.speed), 0) + print(f"Moving bot up to {new_position}") + self.game_state['player2_position'] = new_position + + #await asyncio.sleep(1) # Rafraîchir toutes les secondes + except Exception as e: + print(f"Error in BotPlayer.update_bot_position: {e}") + + + def predict_ball_position(self): + # Prédire la future position de la balle en tenant compte de sa vitesse + ball_y = self.game_state['ball_position']['y'] + ball_speed_y = self.game_state['ball_velocity']['y'] + # Prédiction simple, peut être améliorée pour plus de précision + future_ball_y = ball_y + ball_speed_y * 1 # prédire pour la prochaine seconde + + # Gérer les rebonds sur les limites + if future_ball_y < 0: + future_ball_y = -future_ball_y + elif future_ball_y > 300: + future_ball_y = 600 - future_ball_y + + return future_ball_y + + class Game: def __init__(self, game_id, player1, player2): self.game_id = game_id @@ -24,14 +69,21 @@ class Game: self.game_loop_task = None self.ended = False + if self.botgame: + self.bot_player = BotPlayer(self.game_state, self.speed) + async def start_game(self): print(f"- Game #{self.game_id} STARTED") self.game_loop_task = asyncio.create_task(self.game_loop()) async def game_loop(self): + #print("Here, ok") while True: if self.botgame: - await self.update_bot_position() + #print('still ok') + await self.bot_player.update_bot_position() + #await self.update_bot_position() + #print('is it ok ?? ') self.update_game_state() await self.send_game_state() await asyncio.sleep(1/60) # Around 60 FPS