[C++] 纯文本查看 复制代码 import pygame
import random
# 初始化 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)
red = (255, 0, 0)
blue = (0, 0, 255)
# 玩家 1 的初始位置和尺寸
player1_x = 50
player1_y = screen_height // 2 - 50
player1_width = 30
player1_height = 110
# 玩家 2 的初始位置和尺寸
player2_x = screen_width - 100
player2_y = screen_height // 2 - 50
player2_width = 30
player2_height = 110
# 球的初始位置和尺寸
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_radius = 20
ball_speed_x = random.choice([-5, 5])
ball_speed_y = random.choice([-5, 5])
# 玩家得分
player1_score = 0
player2_score = 0
# 字体设置
font = pygame.font.Font(None, 36)
# 游戏循环
running = True
while running:
screen.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理玩家 1 的输入
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and player1_y > 0:
player1_y -= 5
if keys[pygame.K_s] and player1_y < screen_height - player1_height:
player1_y += 5
# 处理玩家 2 的输入
if keys[pygame.K_UP] and player2_y > 0:
player2_y -= 5
if keys[pygame.K_DOWN] and player2_y < screen_height - player2_height:
player2_y += 5
# 移动球
ball_x += ball_speed_x
ball_y += ball_speed_y
# 碰撞检测:球与边界的碰撞
if ball_y - ball_radius < 0 or ball_y + ball_radius > screen_height:
ball_speed_y = -ball_speed_y
if ball_x - ball_radius < 0:
# 玩家 2 得分,重置球
player2_score += 1
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = random.choice([-5, 5])
ball_speed_y = random.choice([-5, 5])
if ball_x + ball_radius > screen_width:
# 玩家 1 得分,重置球
player1_score += 1
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = random.choice([-5, 5])
ball_speed_y = random.choice([-5, 5])
# 碰撞检测:球与玩家的碰撞
if (ball_x - ball_radius < player1_x + player1_width and
ball_y > player1_y and ball_y < player1_y + player1_height):
ball_speed_x = abs(ball_speed_x)
if (ball_x + ball_radius > player2_x and
ball_y > player2_y and ball_y < player2_y + player2_height):
ball_speed_x = -abs(ball_speed_x)
# 绘制玩家 1
pygame.draw.rect(screen, red, (player1_x, player1_y,
player1_width, player1_height))
# 绘制玩家 2
pygame.draw.rect(screen, blue, (player2_x, player2_y,
player2_width, player2_height))
# 绘制球
pygame.draw.circle(screen, white, (ball_x, ball_y), ball_radius)
# 显示得分
player1_text = font.render(f"Player 1: {player1_score}", True, red)
player2_text = font.render(f"Player 2: {player2_score}", True, blue)
screen.blit(player1_text, (100, 50))
screen.blit(player2_text, (screen_width - 200, 50))
pygame.display.flip()
pygame.time.Clock().tick(60)
pygame.quit()
|