请用python输出一个塔防游戏
时间: 2024-05-13 22:20:17 浏览: 81
好的,以下是一个简单的塔防游戏的 Python 代码示例:
```python
import pygame
import random
# 定义一些常量
WIDTH = 600
HEIGHT = 600
FPS = 30
# 初始化 Pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tower Defense")
# 创建游戏时钟
clock = pygame.time.Clock()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义游戏角色和其他变量
player = pygame.Rect(50, 50, 50, 50)
enemies = []
enemy_speed = 3
tower_image = pygame.image.load("tower.png")
towers = []
# 定义敌人类
class Enemy:
def __init__(self):
self.rect = pygame.Rect(random.randint(0, WIDTH), -50, 25, 25)
self.speed = enemy_speed
def update(self):
self.rect.y += self.speed
def draw(self):
pygame.draw.rect(screen, RED, self.rect)
# 定义塔类
class Tower:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, 50, 50)
self.target = None
self.target_rect = None
def update(self):
if self.target is None:
for enemy in enemies:
if self.rect.colliderect(enemy.rect):
self.target = enemy
self.target_rect = pygame.Rect(self.target.rect.x, self.target.rect.y, 10, 10)
break
else:
if self.target_rect.colliderect(self.target.rect):
self.target_rect = pygame.Rect(self.target.rect.x, self.target.rect.y, 10, 10)
else:
self.target_rect.x += 1 if self.target_rect.x < self.target.rect.x else -1
self.target_rect.y += 1 if self.target_rect.y < self.target.rect.y else -1
if not self.rect.colliderect(self.target_rect):
self.target = None
self.target_rect = None
def draw(self):
screen.blit(tower_image, self.rect)
# 游戏循环
running = True
while running:
# 设置游戏帧率
clock.tick(FPS)
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
towers.append(Tower(event.pos[0] - 25, event.pos[1] - 25))
# 更新游戏中的敌人
for enemy in enemies:
enemy.update()
# 更新游戏中的塔
for tower in towers:
tower.update()
# 绘制游戏界面
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, player)
for enemy in enemies:
enemy.draw()
for tower in towers:
tower.draw()
# 生成新的敌人
if random.randint(0, 100) < 5:
enemies.append(Enemy())
# 更新屏幕
pygame.display.flip()
# 关闭 Pygame
pygame.quit()
```
注意:此代码未经测试,不保证可以正常运行。您可能需要添加更多的代码来完善游戏。
阅读全文