import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置飞机和障碍物的图片
plane_img = pygame.image.load('plane.png')
obstacle_img = pygame.image.load('obstacle.png')
coin_img = pygame.image.load('coin.png')
# 定义飞机和障碍物的初始位置和速度
plane_x = screen_width // 2
plane_y = screen_height - 30
plane_speed = 5
obstacle_speed = 3
obstacle_x = random.randint(0, screen_width)
obstacle_y = -100
coin_speed = 2
coin_x = random.randint(0, screen_width)
coin_y = random.randint(0, screen_height)
# 游戏主循环
running = True
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:
plane_x -= plane_speed
elif event.key == pygame.K_RIGHT:
plane_x += plane_speed
# 更新飞机和障碍物的位置
plane_y += plane_speed
obstacle_y += obstacle_speed
coin_y += coin_speed
# 检查飞机是否碰到障碍物或屏幕边缘
if (plane_x < 0 or plane_x > screen_width - 30) or (plane_y < 30 and plane_y > screen_height):
running = False
if obstacle_y > screen_height or (obstacle_x < plane_x and obstacle_x + 64 > plane_x):
running = False
# 检查是否吃到金币
if coin_x < plane_x and coin_x + 32 > plane_x and coin_y < plane_y and coin_y + 32 > plane_y:
print('吃到金币!')
coin_speed = random.randint(1, 3)
coin_x = random.randint(0, screen_width)
coin_y = random.randint(0, screen_height)
# 绘制屏幕上的元素
screen.fill((0, 0, 0))
screen.blit(plane_img, (plane_x, plane_y))
pygame.draw.rect(screen, (255, 0, 0), (obstacle_x, obstacle_y, 64, 64))
pygame.draw.rect(screen, (0, 255, 0), (coin_x, coin_y, 32, 32))
pygame.display.flip()
# 控制帧率
pygame.time.Clock().tick(60)文章来源地址https://www.toymoban.com/news/detail-776496.html
文章来源:https://www.toymoban.com/news/detail-776496.html
到了这里,关于用python实现打飞机游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!