一个简单的坦克大战脚本示例。这个脚本使用Python编写,利用了第三方库pygame来进行图像处理和游戏逻辑的实现。以下是示例代码:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 800
window_height = 600
screen = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('坦克大战')
# 设置游戏背景图片
background = pygame.image.load('background.png')
# 设置坦克图片
tank_image = pygame.image.load('tank.png')
# 设置子弹图片
bullet_image = pygame.image.load('bullet.png')
# 设置敌方坦克图片
enemy_tank_image = pygame.image.load('enemy_tank.png')
# 设置游戏结束图片
game_over_image = pygame.image.load('game_over.png')
# 设置游戏结束文字
game_over_text = pygame.font.SysFont('Arial', 50).render('游戏结束', True, (255, 255, 255))
# 设置游戏音效
explosion_sound = pygame.mixer.Sound('explosion.wav')
# 设置游戏主循环
game_running = True
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_tank_y -= 10
elif event.key == pygame.K_DOWN:
player_tank_y += 10
elif event.key == pygame.K_LEFT:
player_tank_x -= 10
elif event.key == pygame.K_RIGHT:
player_tank_x += 10
elif event.key == pygame.K_SPACE:
bullet_x = player_tank_x
bullet_y = player_tank_y
bullet_list.append((bullet_x, bullet_y))
# 绘制游戏背景
screen.blit(background, (0, 0))
# 绘制玩家坦克
player_tank_x = 350
player_tank_y = 300
screen.blit(tank_image, (player_tank_x, player_tank_y))
# 绘制敌方坦克
enemy_tank_list = []
for i in range(5):
enemy_tank_x = random.randint(0, window_width - 50)
enemy_tank_y = random.randint(0, window_height - 50)
enemy_tank_list.append((enemy_tank_x, enemy_tank_y))
screen.blit(enemy_tank_image, (enemy_tank_x, enemy_tank_y))
# 绘制子弹
bullet_list = []
for bullet_x, bullet_y in bullet_list:
screen.blit(bullet_image, (bullet_x, bullet_y))
# 检测碰撞
for bullet_x, bullet_y in bullet_list:
for enemy_tank_x, enemy_tank_y in enemy_tank_list:
if bullet_x < enemy_tank_x + 50 and bullet_x + 20 > enemy_tank_x and bullet_y < enemy_tank_y + 50 and bullet_y + 20 > enemy_tank_y:
explosion_sound.play()
enemy_tank_list.remove((enemy_tank_x, enemy_tank_y))
bullet_list.remove((bullet_x, bullet_y))
# 绘制游戏结束
if len(enemy_tank_list) == 0:
screen.blit(game_over_image, (window_width // 2 - game_over_image.get_width() // 2, window_height // 2 - game_over_image.get_height() // 2))
game_over_text_rect = game_over_text.get_rect(center=(window_width // 2, window_height // 2))
screen.blit(game_over_text, game_over_text_rect)
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
这个脚本实现了一个简单的坦克大战游戏,玩家可以控制一辆坦克,通过键盘方向键来移动,使用空格键发射子弹。游戏中有若干个敌方坦克,玩家需要消灭它们。如果玩家的坦克被敌方坦克击中或者碰到墙壁,游戏就会结束。