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.
Related
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 a class called Stone, inside I have a function called return_coordinates(self), which returns the coordinates of a stone. When I print the coordinates I can see them perfectly but when I try to use them, it prints the error: TypeError: 'module' object is not callable
Here's the class:
class Stone:
def __init__(self, image, x, y):
self.image = image
self.x = x
self.y = y
def draw_stone(self):
image = pygame.image.load(self.image)
screen.blit(image, (self.x, self.y))
def return_id(self):
return self.image.replace("image", "").replace(".png", "")
def return_coordinates(self):
return [self.x, self.y]
Now I have created some class Stone objects and stored them in a list. When I access the object in a list and try to use its function return_coordinates(), it prints the error.
Here's the code:
if draw_selected == True:
coordinates = selected[3].return_coordinates()
selection_box = pygame.rect(coordinates[0], coordinates[1], 57, 80)
pygame.draw.rect(screen, [21, 146, 146], selection_box, 2)
if i print the coordinates then it prints a list with numerical values just like it's supposed to but when I want to access a specific coordinate inside the list like coordinates[0], then I get the error. All the code is inside the same file.
Any ideas on how to fix it?
Full error message:
Traceback (most recent call last):
File "C:\Users\Gabriel\Desktop\tech\project_m\mahjong.py", line 198, in <module>
selection_box = pygame.rect(coordinates[0], coordinates[1], 57, 80)
TypeError: 'module' object is not callable
Please note that Python is a case-sensitive language. Your code works with pygame.Rect:
if draw_selected == True:
coordinates = selected[3].return_coordinates()
selection_box = pygame.Rect(coordinates[0], coordinates[1], 57, 80)
pygame.draw.rect(screen, [21, 146, 146], selection_box, 2)
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
I've been trying to get my Tkinter wrapper (specialised to make a game out of) to work, but it keeps throwing up an error when it tries to draw a rectangle.
Traceback:
Traceback (most recent call last):
File "C:\Users\William\Dropbox\IT\Thor\test.py", line 7, in <module>
aRectangle = thorElements.GameElement(pling,rectangleTup=(True,295,195,305,205,"blue"))
File "C:\Users\William\Dropbox\IT\Thor\thorElements.py", line 79, in __init__
self.rectangle = self.area.drawRectangle(self)
File "C:\Python33\lib\tkinter\__init__.py", line 1867, in __getattr__
return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'drawRectangle'
The sections of the code that are relevant to the question,
class GameElement():
def __init__(self,area,rectangleTup=(False,12,12,32,32,"red")):
self.area = area
self.lineTup = lineTup #Tuple containing all the data needed to create a line
if self.lineTup[0] == True:
self.kind = "Line"
self.xPos = self.lineTup[1]
self.yPos = self.lineTup[2]
self.line = self.area.drawLine(self)
And here's the actual method that draws the rectangle onto the canvas (in the class that manages the Canvas widget), earlier in the same file:
class Area():
def drawLine(self,line):
topX = line.lineTup[1]
topY = line.lineTup[2]
botX = line.lineTup[3]
botY = line.lineTup[4]
colour = line.lineTup[5]
dashTuple = (line.lineTup[6][0],line.lineTup[6][1])
return self.canvas.create_line(topX,topY,botX,botY,fill=colour,dash=dashTuple)
print("Drew Line")
All input is greatly appreciated.
The error message is meant to be self explanatory. When it says AttributeError: 'tkapp' object has no attribute 'drawRectangle', it means that you are trying to do tkapp.drawRectangle or tkapp.drawRectangle(...), but tkapp doesn't have an attribute or method named drawRectangle.
Since your code doesn't show where you create tkapp or how you created it, or where you call drawRectangle, it's impossible for us to know what the root of the problem is. Most likely it's one of the following:
tkapp isn't what you think it is
you have a typo, and meant to call drawLine rather than drawRectangle,
you intended to implement drawRectangle but didn't
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()