用python代码做一个打飞机的游戏
时间: 2023-06-11 17:04:57 浏览: 158
好的,下面是用Python和Pygame库制作打飞机游戏的代码,供您参考:
```python
# 导入需要的库
import pygame
import random
# 初始化pygame库
pygame.init()
# 颜色的定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (50, 153, 213)
RED = (255, 0, 0)
# 设置屏幕的大小
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置窗口标题
pygame.display.set_caption("打飞机游戏")
# 加载背景图片
background = pygame.image.load('images/background.png')
# 加载飞机图片
player_img = pygame.image.load('images/player.png')
# 加载敌机图片
enemy_img = pygame.image.load('images/enemy.png')
# 加载子弹图片
bullet_img = pygame.image.load('images/bullet.png')
# 定义游戏结束的函数
def game_over():
font = pygame.font.SysFont(None, 48)
text = font.render("游戏结束", True, RED)
screen.blit(text, (screen_width/2-100, screen_height/2-24))
pygame.display.update()
pygame.time.wait(3000)
# 定义游戏主循环
def game_loop():
# 初始化游戏变量
player_x = 220
player_y = 580
player_speed = 5
bullet_speed = 10
bullet_list = []
enemy_list = []
enemy_speed = 3
enemy_spawn_rate = 60
score = 0
font = pygame.font.SysFont(None, 36)
game_exit = False
# 游戏循环,按下关闭按钮时退出
while not game_exit:
# 获取所有事件
for event in pygame.event.get():
# 判断事件类型
if event.type == pygame.QUIT:
game_exit = True
# 判断是否按下了键盘按键
if event.type == pygame.KEYDOWN:
# 判断按下的是哪个键位
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
elif event.key == pygame.K_SPACE:
bullet_x = player_x + 43
bullet_y = player_y - 34
bullet_list.append([bullet_x, bullet_y])
# 绘制背景图片
screen.blit(background, (0, 0))
# 绘制玩家飞机
screen.blit(player_img, (player_x, player_y))
# 移动子弹,遍历所有子弹
for bullet in bullet_list:
bullet_y -= bullet_speed
screen.blit(bullet_img, (bullet[0], bullet_y))
# 判断子弹是否超出了屏幕范围,是则从列表中移除该子弹
if bullet_y < -20:
bullet_list.remove(bullet)
# 每隔一段时间生成敌机,增加难度
if random.randint(0, enemy_spawn_rate) == 0:
enemy_x = random.randint(0, screen_width-51)
enemy_y = -50
enemy_list.append([enemy_x, enemy_y])
# 移动敌机,遍历所有敌机
for enemy in enemy_list:
enemy_y += enemy_speed
screen.blit(enemy_img, (enemy[0], enemy_y))
# 判断敌机是否撞到玩家飞机
if enemy_y > player_y-51 and enemy_y < player_y+51 and enemy[0] > player_x-51 and enemy[0] < player_x+51:
game_over()
game_exit = True
# 判断敌机是否超出了屏幕范围,是则从列表中移除该敌机
if enemy_y > screen_height+50:
enemy_list.remove(enemy)
# 玩家得分加一,并显示到屏幕上
score += 1
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
pygame.time.Clock().tick(60)
# 退出pygame库
pygame.quit()
# 运行游戏主循环函数
game_loop()
```
保存以上代码为.py文件并运行,即可在Pygame窗口中开始打飞机游戏啦。注意,为了将代码整体作为Python程序运行,需要将保存的.py文件中,第一行的注释#coding:utf-8去掉。
当然,游戏的具体规则还需要您自己制定。希望以上代码能帮到您!
阅读全文