Home > front end >  Python won't run and says its unreferenced var
Python won't run and says its unreferenced var

Time:05-05

The error message is:

File "d:\import turtle.py", line 29, in player_animate
    attackangle = (math.atan(ey/ex)/(2* math.pi))*360
UnboundLocalError: local variable 'ey' referenced before assignment

I've tried rearanging the events of it here is the code

import time
import math
from turtle import Turtle, Screen
import os

wn = turtle.Screen()
import random
wn.title("Animation Demo")
wn.bgcolor("black")
ey = random.randint(-500,500)
ex = random.randint(-500,500)

player = turtle.Turtle()
enemey = turtle.Turtle()
player.shape("square")
player.color("green")
enemey.shape("arrow")
enemey.color("red")
player.turtlesize(2)
player.penup()
player.forward(50)
player.left(90)
enemey.penup()

enemey.goto(ex,ey)
time.sleep(1)
def player_animate():
    attackangle = (math.atan(ey/ex)/(2* math.pi))*360
    attackangle = int(attackangle)
    ey = enemey.ycor()
    ex = enemey.xcor()
    enemey.seth(attackangle)
    enemey.forward(5)
    if player.shape() == "square":
        player.shape("triangle")
    elif player.shape() == "triangle":
        player.shape("square")
        


    wn.ontimer(player_animate, 500)

def move_left():
    ex =- 10
def move_up():
    ey =  10
def move_down():
    ey =- 10
def move_right():
    ex =  10


player_animate() 

while True:
    wn.update()
    turtle.listen()
    turtle.onkey(move_left(),"Left")
    turtle.listen()
    turtle.onkey(move_up(),"Up")
    turtle.listen()
    turtle.onkey(move_down(),"Down")
    turtle.listen()
    turtle.onkey(move_right(),"Right")
    

any sugestions?

CodePudding user response:

def player_animate():
    attackangle = (math.atan(ey/ex)/(2* math.pi))*360
    attackangle = int(attackangle)
    ey = enemey.ycor()
    ex = enemey.xcor()

You're referring to ey and ex on the first line of this function, but they aren't defined until the third and fourth lines.

How do you expect them to have values before they are defined?

CodePudding user response:

The problem is that you're using the variables ey and ex before you define them inside your function. Keep in mind that your function is a black box and doesn't have access to the ey and ex variables defined outside of your function (unless they are global variables), or you're passing them to your function.

Try the following order of events inside your player_animate function instead:

def player_animate():
    ey = enemey.ycor()
    ex = enemey.xcor()
    attackangle = (math.atan(ey/ex)/(2* math.pi))*360
    attackangle = int(attackangle)
    ...
  • Related