找回密码
 中文实名注册
搜索
查看: 633|回复: 0

坦克对战游戏(下)

[复制链接]

23

主题

12

回帖

793

积分

高级会员

积分
793
发表于 2025-7-17 10:50:05 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
# 创建地图
global obstacles
obstacles = create_map()

# 子弹列表
player1_bullets = []
player2_bullets = []

# 游戏变量
game_over = False
winner = None

# 游戏主循环
while True:
clock.tick(60)
current_time = pygame.time.get_ticks()

# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r and game_over:
# 重新开始游戏
player1 = Tank(100, HEIGHT // 2, BLUE, {
"up": pygame.K_w,
"down": pygame.K_s,
"left": pygame.K_a,
"right": pygame.K_d,
"shoot": pygame.K_f
})

player2 = Tank(WIDTH - 100, HEIGHT // 2, RED, {
"up": pygame.K_UP,
"down": pygame.K_DOWN,
"left": pygame.K_LEFT,
"right": pygame.K_RIGHT,
"shoot": pygame.K_RCTRL
})

obstacles = create_map()
player1_bullets = []
player2_bullets = []
game_over = False
winner = None

if not game_over:
# 获取按键状态
keys = pygame.key.get_pressed()

# 移动玩家坦克
player1.move(keys)
player2.move(keys)

# 射击
if keys[player1.controls["shoot"]]:
player1.shoot(current_time, player1_bullets, BLUE)

if keys[player2.controls["shoot"]]:
player2.shoot(current_time, player2_bullets, RED)

# 移动子弹
for bullet in player1_bullets[:]:
bullet.move()
if bullet.off_screen() or bullet.check_obstacle_collision(obstacles):
player1_bullets.remove(bullet)
elif bullet.check_collision(player2):
player2.health -= 25
player1_bullets.remove(bullet)
if player2.health <= 0:
game_over = True
winner = "Player 1"

for bullet in player2_bullets[:]:
bullet.move()
if bullet.off_screen() or bullet.check_obstacle_collision(obstacles):
player2_bullets.remove(bullet)
elif bullet.check_collision(player1):
player1.health -= 25
player2_bullets.remove(bullet)
if player1.health <= 0:
game_over = True
winner = "Player 2"

# 绘制游戏
win.fill(BLACK)

# 绘制障碍物
for obstacle in obstacles:
obstacle.draw(win)

# 绘制玩家坦克
player1.draw(win)
player2.draw(win)

# 绘制子弹
for bullet in player1_bullets:
bullet.draw(win)
for bullet in player2_bullets:
bullet.draw(win)

# 显示游戏状态
draw_text(win, f"玩家1生命值: {player1.health}", 24, 100, 10)
draw_text(win, f"玩家2生命值: {player2.health}", 24, WIDTH - 100, 10)

# 游戏结束画面
if game_over:
draw_text(win, f"{winner} 获胜!", 64, WIDTH // 2, HEIGHT // 3)
draw_text(win, "按 R 键重新开始", 24, WIDTH // 2, HEIGHT // 2)

pygame.display.flip()


if __name__ == "__main__":
main()

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

快速回复 返回顶部 返回列表