I keep getting a UnboundLocalError when I try assigning turtle to turtle.Turtle() in a function. Why is it? Is the name used in turtle.py?
import turtle
def make_turtle():
turtle = turtle.Turtle()
return turtle
eu = make_turtle()
Traceback (most recent call last):
File "/home/usr/PycharmProjects/LearningToThinkLikeAComputerScientist/c4 - Functions/test.py", line 6, in <module>
eu = make_turtle()
File "/home/luis/PycharmProjects/LearningToThinkLikeAComputerScientist/c4 - Functions/test.py", line 3, in make_turtle
turtle = turtle.Turtle()
UnboundLocalError: local variable 'turtle' referenced before assignment
In the import statement you assign the name turtle.
Then you assign to it in the function. If I have understood this correctly, the python parser first esttablishes thet the name turtle is assigned which makes it local. Then it processes the line turtle = turtle.Turtle() fron right to left. On discovering that you try to retrieve the value pointed to by turtle it is not assigned, you get an error.
Instead try another name:
import turtle
def make_turtle():
cat = turtle.Turtle()
return cat
eu = make_turtle()
Related
When I create an ordinary object, like below, I can assign different variables to it that hasn’t been defined in the __init__() method:
class Test:
pass
test = Test()
test.Something = 0
but in the code below, I can't.
import pygame
pygame.init()
screen = pygame.display.set_mode()
print(type(screen))
red = (255, 0, 0)
blue = (0, 0, 255)
screen.turn = 0
while True:
if (screen.turn):
screen.fill(blue)
else:
screen.fill(red)
screen.turn = 1 - screen.turn
pygame.event.pump()
pygame.display.update()
Instead, an AttributeError exception is raised and the program gives the output below:
pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "/Users/armaho/Programs/Python/main.py", line 10, in <module>
screen.turn = 0
AttributeError: 'pygame.Surface' object has no attribute 'turn'
<class 'pygame.Surface'>
Why is that?
Much of PyGame is written in C. The default object type does not have a namespace dictionary and does not allow python level set attribute. A python class written in C can implement a setattr call, but they usually don't. An extra namespace dict and the extra weight needed to support arbitrary attribute assignment is not usually necessary.
You can see the default object class in action
>>> o = object()
>>> o.turn = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'turn'
So I've just started with "Ursina" Engine, I'm still very new to it. I'm trying to make a Minecraft game on Youtube tutorial with this Engine. And for some reason, the program keeps giving me the error name "Name 'render' is not defined". And I don't understand what that's saying. I tried to fix my code and skimmed over the code but couldn't find the answer.
This is all my code:
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
Sky(texture = 'sky.jpg')
class Voxel(Button):
def __init__(self, position = (0,0,0)):
super().__init__(
model = 'cube',
texture = 'white_cube',
position = position,
color = color.white,
parent = scene,
origin_y = 0.5,
highlight_color = color.lime,
)
app = Ursina()
player = FirstPersonController()
for x in range(12):
for y in range(12):
voxel = Voxel(position = (y,0,x))
app.run()
This is the Traceback of the code:
PS C:\Users\lhnguyen1029> & "C:/Program Files (x86)/Python39-
32/python.exe" "c:/Users/lhnguyen1029/OneDrive - Mesa Public
Schools/Documents/CTE- Computer Science Principles/Ursina
practice/ursina_practice(2).py"
package_folder:
C:\Users\lhnguyen1029\AppData\Roaming\Python\Python39\site-
packages\ursina
asset_folder: c:\Users\lhnguyen1029\OneDrive - Mesa Public
Schools\Documents\CTE- Computer Science Principles\Ursina practice
screen resolution: (1366, 768)
Traceback (most recent call last):
File "c:\Users\lhnguyen1029\OneDrive - Mesa Public
Schools\Documents\CTE- Computer Science Principles\Ursina
practice\ursina_practice(2).py", line 7, in <module>
Sky(texture = 'sky.jpg')
File "C:\Users\lhnguyen1029\AppData\Roaming\Python\Python39\site-
packages\ursina\prefabs\sky.py", line 8, in __init__
parent = render,
NameError: name 'render' is not defined
PS C:\Users\lhnguyen1029>
Instantiate Ursina() before instantiating entities.
I have my code for a game here. I have commented out the displayScore(score) call in the main function to allow the program to run. When that call is uncommented the program window closes immediately after opening.
The objective of the function displayScore is to display the game score in the top left corner. Which also needs to be displayed in the right corner for the opposing player's score.
Here is the code for the game with displayScore commented out in the main function so you can run the game and everything will work. Uncomment it to see where the problem is:
ball = ballmovement(ball, ballDirX, ballDirY)
ballDirX, ballDirY = collisionwithedges(ball, ballDirX, ballDirY)
score = checkscore(paddle1, ball, score, ballDirX)
ballDirX = ballDirX * collisionwithpaddles(ball, paddle1, paddle2, ballDirX)
pygame.display.update() #updates the display to clear surface per the frame rate
FRAMECLOCK.tick(FRAMERATE) #Sets the Frames of program to defined rate
if __name__=='__main__':
main()
Just replace the line
displayScore(score)
By:
displayScore(str(score))
You are trying to use a number instead of a string to the argument of render ;) Score is an int and BASICFONT.render((score), True, WHITE)
asks for score to be a string or an array of bytes :)
I found the solution only by reading the console output which was a good indication ^^
Traceback (most recent call last):
File "test.py", line 130, in <module>
main()
File "test.py", line 118, in main
displayScore(score)
File "test.py", line 71, in displayScore
resultSurf = BASICFONT.render((score), True, WHITE)
TypeError: text must be a unicode or bytes
Im currently in an intro coding class and for my final project, i am trying to learn the pyglet module to create a game with a picture in the background, and have a character on the left that a user can make jump, and then have jumps come from the right at a set speed that the user will jump over. i need to use classes for the assignment, and im really having a hard time using creating a sprite class. heres my current code:
import pyglet
window = pyglet.window.Window(700,700)
image = pyglet.image.load('IMG_3315.jpg')#use 10x10 in. image
#image_2 = pyglet.image.load('IMG_3559.jpg')
main_batch = pyglet.graphics.Batch()
score_label = pyglet.text.Label(text="Score: 0", x=570, y=650, batch=main_batch)
the_jump = pyglet.image.load("jumpsi.png")
#horse = pyglet.sprite.Sprite(image_2, x = 50, y = 50)
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class Jump(pyglet.sprite.Sprite):
def __init__(self, img, x=0, y=0, blend_src=770, blend_dest=771, batch=None, group=None, usage='dynamic', subpixel=False):
self.img = the_jump
self.x = 50
self.y = 50
def draw(self):
self.draw()
# verticle = Jump('verticle')
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
main_batch.draw()
window = Jump()
#horse.draw()
#background_sound.play()
if __name__ == "__main__":
sprite = Jump()
pyglet.app.run()
i know its probably wrong but everything else i have tried (using preexisting games as examples) hasn't worked either.
my current error message is:
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump()
TypeError: __init__() takes at least 2 arguments (1 given)
im just really stuck and have been trying to figure this out for hours and not made any leeway. any help you can offer would be greatly appreciated. Thanks so much!
UPDATE: i recently changed the code, noticing the problem that Gustav pointed out, and change the end call to
if __name__ == "__main__":
sprite = Jump(the_jump)
pyglet.app.run()
but now i get the error
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump(the_jump)
File "jumper.py", line 21, in __init__
self.x = 50
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 459, in _set_x
self._update_position()
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 393, in _update_position
img = self._texture
AttributeError: 'Jump' object has no attribute '_texture'
The error message is telling you exactly which line the error is in and exactly what is wrong. You are initializing the Jump class without passing in an argument for the required parameter img.
You can fix this by either changing the initialization method or your call to Jump().
Here's an example for how to read Python's traceback.
Hello all I am working with ncurses (my first time working with a cli) and I keep getting this error
Traceback (most recent call last):
File "cursesDemo1.py", line 5, in <module>
screen.start_color()
AttributeError: start_color
Here is my code:
import curses
import time
screen = curses.initscr()
screen.start_color()
def maketextbox(h,w,y,x,value="",deco=None,underlineChr=curses.ACS_HLINE,textColorpair=0,decoColorpair=0):
nw = curses.newwin(h,w,y,x)
txtbox = curses.textpad.Textbox(nw)
if deco=="frame":
screen.attron(decoColorpair)
curses.textpad.rectangle(screen,y-1,x-1,y+h,x+w)
screen.attroff(decoColorpair)
elif deco=="underline":
screen.hline(y+1,x,underlineChr,w,decoColorpair)
nw.addstr(0,0,value,textColorpair)
nw.attron(textColorpair)
screen.refresh()
return txtbox
try:
screen.border(0)
box1 = curses.newwin(22, 50, 3, 5)
box1.box()
box2 = curses.newwin(22, 50, 3, 65)
box2.box()
box3 = maketextbox(1,40, 10,20,"foo",deco="underline",textColorpair=curses.color_pair (0),decoColorpair=curses.color_pair(1))
textInput = box3.edit()
It has more errors when I take start_color() out can anyone please advise as to a better course of action? Thanks!!!!
Check manual on curses and be sure to call right methods on right objects.
curses.initscr() Initialize the library. Return a WindowObject which
represents the whole screen.
So, curses.initscr() returns WindowObject but start_color() is in curses module itself. You ought to init colors this way
curses.start_color()