首页 > 解决方案 > 函数不会在python“未解析的引用”中检测到变量

问题描述

我开始玩海龟模块并开始太空入侵者类型的游戏,当我添加子弹时遇到问题,我想创建一个活动子弹列表,该列表中的每个条目都是一个名为 Shot 和创建了一个名为 shot_num 的变量,它基本上是每个镜头的 ID,这里是主类

import turtle
from shots import Shots


**** some code ****

# shot
shot = turtle.Turtle()
shot.speed(5)
shot.shape("square")
shot.color("white")
shot.shapesize(stretch_wid=2, stretch_len=0.2)
shot.penup()
shot.goto(1200, 1200)

# variables
active_shots = []


shot_num = 0


def gun_shot():
    temp_shot = Shots(shot_num, gun.xcor())
    shot_num += 1                             ###where the problem happends


main_win.listen()
main_win.onkeypress(gun_shot, "space")


while True:
    main_win.update()

这是Shot类

import turtle


    class Shots:
    def __init__(self, number, x_location):
        self.number = number
        self.x_location = x_location
        self.shot1 = turtle.Turtle()
        self.shot1.speed(5)
        self.shot1.shape("square")
        self.shot1.color("white")
        self.shot1.shapesize(stretch_wid=2, stretch_len=0.2)
        self.shot1.penup()
        self.shot1.goto(x_location, -200)



    def border_check(self):
        if self.x_location > 400:
            del self

它说“未解决的参考shot_num”,我真的不明白为什么当我删除这一行时它会起作用,谢谢

标签: pythonpython-turtle

解决方案


正如我在提交中所说,只需添加global shot_num

def gun_shot():
    global shot_num 
    temp_shot = Shots(shot_num, gun.xcor())
    shot_num += 1

似乎Python不想识别你的全局变量......


推荐阅读