python坦克大战游戏代码,要求有游戏积分,游戏关卡,游戏界面,还有游戏状态
时间: 2023-08-21 12:05:36 浏览: 93
坦克大战.zip_Python游戏_castvm4_python_坦克大战_坦克大战gif
好的,以下是一个基于 Pygame 的简单坦克大战游戏代码,包含了游戏积分、游戏关卡、游戏界面和游戏状态。您可以根据需要进行修改和扩展:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏界面大小和标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Tank Battle")
# 游戏状态
game_over = False
game_win = False
# 游戏积分和关卡
score = 0
level = 1
# 玩家坦克
player_tank = pygame.image.load("player_tank.png")
player_tank_rect = player_tank.get_rect()
player_tank_rect.centerx = screen_width / 2
player_tank_rect.bottom = screen_height - 10
player_speed = 5
# 子弹
bullet = pygame.image.load("bullet.png")
bullet_rect = bullet.get_rect()
bullet_speed = 10
bullet_state = "ready"
# 敌方坦克
enemy_tank = pygame.image.load("enemy_tank.png")
enemy_tank_rect = enemy_tank.get_rect()
enemy_tank_rect.centerx = random.randint(0, screen_width)
enemy_tank_rect.top = 0
enemy_speed = 3
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 玩家移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_tank_rect.left -= player_speed
if event.key == pygame.K_RIGHT:
player_tank_rect.right += player_speed
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bullet_rect.centerx = player_tank_rect.centerx
bullet_rect.bottom = player_tank_rect.top
bullet_state = "fire"
# 更新游戏状态
if bullet_state == "fire":
bullet_rect.top -= bullet_speed
if bullet_rect.top <= 0:
bullet_state = "ready"
enemy_tank_rect.top += enemy_speed
if enemy_tank_rect.top >= screen_height:
enemy_tank_rect.centerx = random.randint(0, screen_width)
enemy_tank_rect.top = 0
score += 1
if player_tank_rect.colliderect(enemy_tank_rect):
game_over = True
game_win = False
if score >= 10:
level += 1
score = 0
enemy_speed += 1
# 绘制游戏界面
screen.fill((255, 255, 255))
screen.blit(player_tank, player_tank_rect)
screen.blit(enemy_tank, enemy_tank_rect)
if bullet_state == "fire":
screen.blit(bullet, bullet_rect)
font = pygame.font.SysFont("arial", 36)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
level_text = font.render("Level: " + str(level), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
screen.blit(level_text, (10, 50))
pygame.display.flip()
# 游戏结束界面
if game_win:
game_over_text = font.render("You Win!", True, (0, 0, 0))
else:
game_over_text = font.render("Game Over!", True, (0, 0, 0))
screen.blit(game_over_text, (screen_width/2 - game_over_text.get_rect().width/2, screen_height/2 - game_over_text.get_rect().height/2))
pygame.display.flip()
# 等待玩家退出游戏
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
```
请注意,这是一个简单的示例代码,您可以根据自己的需要对其进行修改和扩展。例如,您可以添加更多的关卡、敌人和玩家武器,或者改变游戏规则和玩法。
阅读全文