Python写小鸟飞翔

 下载地址:飞行的小鸟.zip - 蓝奏云文件大小:87.8 K|icon-default.png?t=N7T8https://shunianssy.lanzouw.com/i3YOF1bus43i

代码如下;

import pgzrun
import random

# 设置窗口宽度和高度
WIDTH = 800
HEIGHT = 600

# 创建小鸟角色并设置初始位置
bird = Actor("bird.png")
bird.pos = (100, HEIGHT/2)

# 设置管道间隙和移动速度
pipe_gap = 200
pipe_speed = 4

# 创建上方管道和下方管道角色
top_pipe = Actor("pipe_up.png", anchor=("left", "bottom"))
bottom_pipe = Actor("pipe_down.png", anchor=("left", "top"))

# 初始化得分和游戏结束状态
score = 0
game_over = False

def update():
    global score, game_over
    
    if not game_over:
        # 小鸟下落
        bird.y += 2
        # 检查是否碰撞到管道或超出窗口
        if bird.y >= HEIGHT or check_collision():
            game_over = True
        else:
            # 检查是否通过了管道,更新得分
            check_score()
            # 更新管道位置
            update_pipes()

def on_key_down():
    if not game_over:
        # 按下键盘时,小鸟向上飞行
        bird.y -= 50

def draw():
    screen.clear()
    # 绘制角色和得分
    bird.draw()
    top_pipe.draw()
    bottom_pipe.draw()
    screen.draw.text("Score: " + str(score), (10, 10), color="white")
    if game_over:
        # 如果游戏结束,显示游戏结束文本
        screen.draw.text("Game Over", center=(WIDTH/2, HEIGHT/2), color="white")

def reset_game():
    global score, game_over
    # 重置得分和游戏结束状态
    score = 0
    game_over = False
    # 将小鸟位置恢复到初始位置
    bird.y = HEIGHT/2
    # 创建新的管道
    create_pipes()

def check_collision():
    # 检查小鸟是否与管道或超出窗口碰撞
    return bird.colliderect(top_pipe) or bird.colliderect(bottom_pipe) or bird.y >= HEIGHT

def check_score():
    global score
    if bird.x > top_pipe.x + top_pipe.width/2 and bird.x < top_pipe.x + top_pipe.width/2 + pipe_speed:
        # 小鸟通过一对管道,增加得分
        score += 1

def create_pipes():
    # 随机生成管道的高度
    pipe_gap_y = random.randint(200, 400)
    # 设置上下管道的位置
    top_pipe.pos = (WIDTH, pipe_gap_y - pipe_gap/2)
    bottom_pipe.pos = (WIDTH, pipe_gap_y + pipe_gap/2)

def update_pipes():
    global score
    # 移动管道
    top_pipe.x -= pipe_speed
    bottom_pipe.x -= pipe_speed
    if top_pipe.right < 0:
        # 管道超出窗口左侧,重置管道位置并增加得分
        top_pipe.x = WIDTH
        bottom_pipe.x = WIDTH
        create_pipes()
        score += 1

# 创建初始管道
create_pipes()

# 运行游戏
pgzrun.go()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值