用python实现打飞机游戏

2024-01-07 22:10:28

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://blog.csdn.net/ducanwang/article/details/135365485
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。