Advertisement

Python/用 Pgzrun 库做一个简单小游戏

阅读量:

本游戏是一个简单的2D动作射击游戏,在一个宽700像素、高900像素的屏幕上进行。玩家 controls通过方向键移动人物(左/右键)和空格键发射武器(武器会垂直向下移动)。游戏背景中会有50个敌人从上方不断生成,并随机分布在屏幕底部。玩家需要用武器击倒这些敌人以得分,并在敌人接近时自动攻击。当遇到特定条件时(如被击中),角色会显示“输了。。。”动画并结束游戏。代码部分展示了如何创建角色、管理列表以及更新循环中的各种事件处理机制(如移动、攻击和碰撞检测)。

enemies are approaching you from the screen above. Use the arrow keys to maneuver the character and press the spacebar to fire.

复制代码
    '_Henry原创_'
    
    import pgzrun
    import random
    
    # 设置窗口宽和高
    WIDTH = 700
    HEIGHT = 900
    
    # 设置人物
    player = Actor('人物')
    player.x = 250
    player.y = 650
    
    # 建立武器和敌人存储的列表
    weapons = []
    enemy = []
    
    # 生成敌人
    for i in range(50):
    b = Actor('敌人')
    b.x = random.randint(0, 500)
    enemy.append(b)
    
    # 绘制背景
    def draw():
    screen.blit('背景', [0, 0])
    player.draw()
    if player.image != '输了。。。':
    
    	# 绘制武器和敌人
        for w in weapons:
            w.draw()
        for b in enemy:
            b.draw()
    
    def update():
    
    	# 上下左右移动
    if keyboard.left:
        player.x -= 10
    if keyboard.right:
        player.x += 10
    if keyboard.up:
        player.y -= 10
    if keyboard.down:
        player.y += 10 
        
    # 发射武器击倒敌人
    if keyboard.space:
        weapon = Actor('武器')
        weapon.x = player.x
        weapon.y = player.y - 100
        weapons.append(weapon)
        
    for w in weapons:
    	# 设置武器移动速度
        w.y -= 50 
        
    for w in weapons:
    	# 武器碰到窗口地下消失
        if w.y <= 0:
            weapons.remove(w)
            
        # 生成新的敌人
    for b in enemy:
        b.y += 1
        if b.y > 700:
            b.x = random.randint(0, 500)
            b.y = 0
            
        # 检测武器和敌人相碰撞
    for b in enemy:
        for w in weapons:
            if b.colliderect(w):
                b.x = random.randint(0, 500)
                b.y = 0
                
        # 检测输局
        if b.colliderect(player):
            player.image = '输了。。。'
            
    # 运行全部程序
    pgzrun.go()

全部评论 (0)

还没有任何评论哟~