用python使用pygame模块写一个坦克大战
时间: 2023-03-01 09:45:02 浏览: 235
下面是使用Pygame模块编写坦克大战游戏的一个示例代码:
```python
import pygame
import random
# initialize pygame
pygame.init()
# set window size
screen = pygame.display.set_mode((800, 600))
# set title
pygame.display.set_caption("Tank War")
# load tank image
tank_img = pygame.image.load("tank.png")
# set tank starting position
tank_x = 400
tank_y = 500
# set enemy tank starting position
enemy_x = random.randint(0, 800)
enemy_y = random.randint(50, 150)
# load enemy tank image
enemy_img = pygame.image.load("enemy.png")
# set bullet starting position
bullet_x = 0
bullet_y = 0
# load bullet image
bullet_img = pygame.image.load("bullet.png")
# game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# move tank
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
tank_x -= 5
if keys[pygame.K_RIGHT]:
tank_x += 5
if keys[pygame.K_UP]:
tank_y -= 5
if keys[pygame.K_DOWN]:
tank_y += 5
# fire bullet
if keys[pygame.K_SPACE]:
bullet_x = tank_x + 20
bullet_y = tank_y - 20
# move bullet
bullet_y -= 5
# check if bullet hit enemy
if bullet_x >= enemy_x and bullet_x <= enemy_x + 40 and bullet_y >= enemy_y and bullet_y <= enemy_y + 40:
enemy_x = random.randint(0, 800)
enemy_y = random.randint(50, 150)
bullet_x = 0
bullet_y = 0
# redraw screen
screen.fill((0, 0, 0))
screen.blit(tank_img, (tank_x, tank_y))
screen.blit(enemy_img, (enemy_x, enemy_y))
screen.blit(bullet_img, (bullet_x, bullet_y))
pygame.display.update()
# quit game
pygame.quit()
```
这个代码实现了一个简单的坦克大战游戏,其中包括操纵坦克移动和开火、敌方坦克随机生成和碰撞检测等功能
阅读全文