import pygame
import sys
# 初始化pygame
pygame.init()
# 屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("打乒乓球")
?
# 顏色定義
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
?
# 球類
class Ball:
? ? def __init__(self, x, y, radius, color, x_vel, y_vel):
? ? ? ? self.x = x
? ? ? ? self.y = y
? ? ? ? self.radius = radius
? ? ? ? self.color = color
? ? ? ? self.x_vel = x_vel
? ? ? ? self.y_vel = y_vel
?
? ? def draw(self, screen):
? ? ? ? pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
?
? ? def move(self):
? ? ? ? self.x += self.x_vel
? ? ? ? self.y += self.y_vel
?
? ? ? ? # 碰到左右邊界反彈
? ? ? ? if self.x - self.radius < 0 or self.x + self.radius > screen_width:
? ? ? ? ? ? self.x_vel = -self.x_vel
?
? ? ? ? # 碰到上邊界增加速度,碰到下邊界游戲結束(這里簡單處理為碰到下邊界也反彈,用于演示)
? ? ? ? if self.y - self.radius < 0:
? ? ? ? ? ? self.y_vel = -self.y_vel
? ? ? ? ? ? self.x_vel *= 1.1 # 增加水平速度,使游戲更有挑戰性
? ? ? ? elif self.y + self.radius > screen_height:
? ? ? ? ? ? # 實際應用中可以在這里結束游戲
? ? ? ? ? ? self.y = screen_height - self.radius # 為了演示,讓球從底部反彈
? ? ? ? ? ? self.y_vel = -self.y_vel
? ? ? ? ? ? self.x_vel *= 0.9 # 減速,增加游戲難度
?
# 玩家類(這里只實現一個玩家,即左側玩家,使用鍵盤W和S鍵控制)
class Player:
? ? def __init__(self, x, y, width, height, color):
? ? ? ? self.x = x
? ? ? ? self.y = y
? ? ? ? self.width = width
? ? ? ? self.height = height
? ? ? ? self.color = color
? ? ? ? self.vel = 0
?
? ? def draw(self, screen):
? ? ? ? pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
?
? ? def move(self):
? ? ? ? keys = pygame.key.get_pressed()
? ? ? ? if keys[pygame.K_w] and self.y > 0:
? ? ? ? ? ? self.y -= 10
? ? ? ? if keys[pygame.K_s] and self.y < screen_height - self.height:
? ? ? ? ? ? self.y += 10
?
# 創建球和玩家對象
ball = Ball(screen_width // 2, screen_height // 2, 15, WHITE, 5, 5)
player = Player(10, screen_height // 2 - 20, 10, 40, WHITE)
?
# 游戲主循環
clock = pygame.time.Clock()
running = True
while running:
? ? for event in pygame.event.get():
? ? ? ? if event.type == pygame.QUIT:
? ? ? ? ? ? running = False
?
? ? # 移動球和玩家
? ? ball.move()
? ? player.move()
?
? ? # 檢測球是否碰到玩家(這里只檢測左側玩家)
? ? if (ball.x - ball.radius < player.x + player.width and
? ? ? ? ball.x + ball.radius > player.x and
? ? ? ? ball.y - ball.radius < player.y + player.height and
? ? ? ? ball.y + ball.radius > player.y):
? ? ? ? ball.y_vel = -ball.y_vel
?
? ? # 填充背景色
? ? screen.fill(BLACK)
?
? ? # 繪制球和玩家
? ? ball.draw(screen)
? ? player.draw(screen)
?
? ? # 更新屏幕顯示
? ? pygame.display.flip()
?
? ? # 控制幀率
? ? clock.tick(60)
?
pygame.quit()
sys.exit()