python坦克大战的代码
时间: 2023-10-04 16:12:27 浏览: 99
以下是一个简单的 Python 坦克大战游戏的代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("坦克大战")
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
# 定义坦克类
class Tank(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 30))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed_x = 0
self.speed_y = 0
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
def move_left(self):
self.speed_x = -3
def move_right(self):
self.speed_x = 3
def move_up(self):
self.speed_y = -3
def move_down(self):
self.speed_y = 3
def stop(self):
self.speed_x = 0
self.speed_y = 0
# 创建玩家坦克对象
player_tank = Tank(window_width // 2, window_height // 2)
# 创建精灵组
all_sprites = pygame.sprite.Group()
all_sprites.add(player_tank)
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_tank.move_left()
elif event.key == pygame.K_RIGHT:
player_tank.move_right()
elif event.key == pygame.K_UP:
player_tank.move_up()
elif event.key == pygame.K_DOWN:
player_tank.move_down()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_tank.stop()
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_tank.stop()
all_sprites.update()
window.fill(black)
all_sprites.draw(window)
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
这只是一个简单的示例,你可以根据自己的需求进行扩展和修改。希望对你有所帮助!
阅读全文