python坦克大战源代码
时间: 2023-11-03 21:58:00 浏览: 46
以下是一个简单的 Python 坦克大战游戏的源代码,供参考:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口的大小
screen_width = 640
screen_height = 480
# 颜色定义
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("坦克大战")
# 加载图片
tank_img = pygame.image.load("tank.png")
tank_img = pygame.transform.scale(tank_img, (50, 50))
bullet_img = pygame.image.load("bullet.png")
bullet_img = pygame.transform.scale(bullet_img, (15, 15))
# 定义坦克类
class Tank:
def __init__(self, x, y):
self.x = x
self.y = y
self.speed = 5
self.direction = "up"
self.image = tank_img
def update(self):
if self.direction == "up":
self.y -= self.speed
elif self.direction == "down":
self.y += self.speed
elif self.direction == "left":
self.x -= self.speed
elif self.direction == "right":
self.x += self.speed
def draw(self):
screen.blit(self.image, (self.x, self.y))
# 定义子弹类
class Bullet:
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.speed = 10
self.direction = direction
self.image = bullet_img
def update(self):
if self.direction == "up":
self.y -= self.speed
elif self.direction == "down":
self.y += self.speed
elif self.direction == "left":
self.x -= self.speed
elif self.direction == "right":
self.x += self.speed
def draw(self):
screen.blit(self.image, (self.x, self.y))
# 创建坦克和子弹对象
player_tank = Tank(300, 400)
enemy_tank = Tank(100, 100)
bullets = []
# 游戏循环
game_over = False
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_tank.direction = "up"
elif event.key == pygame.K_DOWN:
player_tank.direction = "down"
elif event.key == pygame.K_LEFT:
player_tank.direction = "left"
elif event.key == pygame.K_RIGHT:
player_tank.direction = "right"
elif event.key == pygame.K_SPACE:
bullet = Bullet(player_tank.x + 20, player_tank.y + 20, player_tank.direction)
bullets.append(bullet)
# 更新坦克和子弹状态
player_tank.update()
enemy_tank.update()
for bullet in bullets:
bullet.update()
# 绘制游戏元素
screen.fill(white)
player_tank.draw()
enemy_tank.draw()
for bullet in bullets:
bullet.draw()
# 判断是否击中敌人坦克
for bullet in bullets:
if bullet.x > enemy_tank.x and bullet.x < enemy_tank.x + 50 and bullet.y > enemy_tank.y and bullet.y < enemy_tank.y + 50:
bullets.remove(bullet)
enemy_tank.x = random.randint(0, screen_width - 50)
enemy_tank.y = random.randint(0, screen_height - 50)
# 刷新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
以上代码使用 Pygame 库实现了一个简单的坦克大战游戏,包括玩家坦克、敌人坦克和子弹的移动、绘制和碰撞检测等功能。如果需要更详细的代码解释和说明,请参考相关 Pygame 的教程或文档。