当 player2 与金钱发生碰撞时游戏崩溃。错误信息:unboundLocalError:

import random


WIDTH = 800

HEIGHT = 500


background = Actor("background")

player = Actor("player")

enemy = Actor("enemy")

money = Actor("money", pos=(300,300))

player2 = Actor("alien")

score = 0

score2 = 0

player.x = 200

player.y = 200

player2.x= 400

player2.y= 400


def draw():

    screen.clear()

    background.draw()

    player.draw()

    enemy.draw()

    money.draw()

    player2.draw()


def update():

    global score

    if keyboard.right:

        player.x = player.x + 4

    if keyboard.left:

        player.x = player.x - 4

    if keyboard.down:

        player.y = player.y + 4

    if keyboard.up:

        player.y = player.y - 4


    if player.x > WIDTH:

        player.x = WIDTH

    if player.x < 0:

        player.x = 0

    if player.y < 0:

        player.y = 0

    if player.y > HEIGHT:

        player.y = HEIGHT


    if keyboard.d:

        player2.x = player2.x + 4

    if keyboard.a:

        player2.x = player2.x - 4

    if keyboard.s:

        player2.y = player2.y + 4

    if keyboard.w:

        player2.y = player2.y - 4

    if player.colliderect(player2):

        exit()


    if player2.x > WIDTH:

        player2.x = WIDTH

    if player2.x < 0:

        player2.x = 0

    if player2.y < 0:

        player2.y = 0

    if player2.y > HEIGHT:

        player2.y = HEIGHT


   

这是一个用 mu editor 制作的 python 游戏。每当 player2 与钱发生碰撞时,player2 应该收集它并获得分数。每当 player2 与金钱发生碰撞时,它就会使游戏崩溃,并给我一个错误消息:UnboundLocalError:赋值前引用的局部变量“score2”。


梵蒂冈之花
浏览 81回答 1
1回答

千万里不及你

你错过了申报gloabl score2:def update():&nbsp; &nbsp; global score, score2 # <----&nbsp; &nbsp; # [...]&nbsp; &nbsp; if money.colliderect(player2):&nbsp; &nbsp; &nbsp; &nbsp; money.x = random.randint(0, WIDTH)&nbsp; &nbsp; &nbsp; &nbsp; money.y = random.randint(0, HEIGHT)&nbsp; &nbsp; &nbsp; &nbsp; score2 += 1请注意,如果您不声明score2为global变量,则scope2假定为 范围内的update变量,因为该变量是在score2 += 1. 但是,该语句score2 += 1会导致异常,因为它会在变量定义之前尝试读取它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python