Spaces:
Sleeping
Sleeping
import arcade | |
# Set up constants | |
SCREEN_WIDTH = 800 | |
SCREEN_HEIGHT = 600 | |
PADDLE_WIDTH = 10 | |
PADDLE_HEIGHT = 80 | |
BALL_RADIUS = 10 | |
PADDLE_SPEED = 5 | |
BALL_SPEED = 3 | |
class PongGame(arcade.Window): | |
def __init__(self): | |
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "Pong Game") | |
self.player_paddle = None | |
self.opponent_paddle = None | |
self.ball = None | |
self.player_score = 0 | |
self.opponent_score = 0 | |
def setup(self): | |
self.player_paddle = arcade.SpriteSolidColor(PADDLE_WIDTH, PADDLE_HEIGHT, arcade.color.WHITE) | |
self.player_paddle.center_x = PADDLE_WIDTH // 2 | |
self.player_paddle.center_y = SCREEN_HEIGHT // 2 | |
self.opponent_paddle = arcade.SpriteSolidColor(PADDLE_WIDTH, PADDLE_HEIGHT, arcade.color.WHITE) | |
self.opponent_paddle.center_x = SCREEN_WIDTH - PADDLE_WIDTH // 2 | |
self.opponent_paddle.center_y = SCREEN_HEIGHT // 2 | |
self.ball = arcade.SpriteSolidColor(BALL_RADIUS * 2, BALL_RADIUS * 2, arcade.color.WHITE) | |
self.ball.center_x = SCREEN_WIDTH // 2 | |
self.ball.center_y = SCREEN_HEIGHT // 2 | |
self.ball.change_x = BALL_SPEED | |
self.ball.change_y = BALL_SPEED | |
def on_draw(self): | |
arcade.start_render() | |
self.player_paddle.draw() | |
self.opponent_paddle.draw() | |
self.ball.draw() | |
arcade.draw_text(f"Player: {self.player_score}", 10, SCREEN_HEIGHT - 20, arcade.color.WHITE, 14) | |
arcade.draw_text(f"Opponent: {self.opponent_score}", SCREEN_WIDTH - 100, SCREEN_HEIGHT - 20, arcade.color.WHITE, 14) | |
def on_update(self, delta_time): | |
self.player_paddle.center_y += self.player_paddle.change_y | |
self.opponent_paddle.center_y = self.ball.center_y | |
if self.player_paddle.top > SCREEN_HEIGHT: | |
self.player_paddle.top = SCREEN_HEIGHT | |
if self.player_paddle.bottom < 0: | |
self.player_paddle.bottom = 0 | |
self.ball.update() | |
if self.ball.collides_with_sprite(self.player_paddle) or self.ball.collides_with_sprite(self.opponent_paddle): | |
self.ball.change_x *= -1 | |
if self.ball.top > SCREEN_HEIGHT or self.ball.bottom < 0: | |
self.ball.change_y *= -1 | |
if self.ball.left < 0: | |
self.opponent_score += 1 | |
self.ball_restart() | |
elif self.ball.right > SCREEN_WIDTH: | |
self.player_score += 1 | |
self.ball_restart() | |
def on_key_press(self, key, modifiers): | |
if key == arcade.key.UP: | |
self.player_paddle.change_y = PADDLE_SPEED | |
elif key == arcade.key.DOWN: | |
self.player_paddle.change_y = -PADDLE_SPEED | |
def on_key_release(self, key, modifiers): | |
if key == arcade.key.UP or key == arcade.key.DOWN: | |
self.player_paddle.change_y = 0 | |
def ball_restart(self): | |
self.ball.center_x = SCREEN_WIDTH // 2 | |
self.ball.center_y = SCREEN_HEIGHT // 2 | |
self.ball.change_x *= -1 | |
self.ball.change_y *= -1 | |
def main(): | |
game = PongGame() | |
game.setup() | |
arcade.run() | |
if __name__ == "__main__": | |
main() |