用python实现打飞机游戏

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)

  • 16
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数字化信息化智能化解决方案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值