Debugging sample pygame code. Possibly error with super(), yet again - python

Can't figure out what's wrong. All I know is that it doesn't execute. Find the trackback at the bottom.
EDIT: UPDATED, still doesn't run as should...
from livewires import games
SCREENWIDTH = 666
SCREENHEIGHT = 461
games.init (screen_width = SCREENWIDTH, screen_height = SCREENHEIGHT, fps = 100)
backgroundimage = games.load_image ("canvas.jpg", transparent = False)
games.screen.background = backgroundimage
class PhelpsAnimation(games.Animation):
thePhelpsFiles = ["Phelps1.jpg",
"Phelps2.jpg",
"Phelps3.jpg",
"Phelps4.jpg",
"Phelps5.jpg",
"Phelps6.jpg",
"Phelps7.jpg"]
def __init__(self, x = 333, y = 230.5):
super (PhelpsAnimation, self).__init__(x = x,
y = y,
images = PhelpsAnimation.images,
n_repeats = 1,
repeat_interval = 5)
games.screen.add(PhelpsAnimation())
games.screen.mainloop()
TRACEBACK:
Traceback (most recent call last):
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\PygameProject2\AstrocrashSoundandExplosion.py", line 28, in <module>
games.screen.add(PhelpsAnimation())
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\PygameProject2\AstrocrashSoundandExplosion.py", line 25, in __init__
images = PhelpsAnimation.images,
AttributeError: type object 'PhelpsAnimation' has no attribute 'images'
Exception AttributeError: "'PhelpsAnimation' object has no attribute '_gone'" in <bound method PhelpsAnimation.__del__ of <__main__.PhelpsAnimation object at 0x02600C90>> ignored

It's the images = PhelpsAnimation.thePhelpsfiles parameter. thePhelpsfiles is not an attribute of the PhelpsAnimation class you've defined. It should work if you change that to just images=thePhelpsfiles.

Related

Space Invaders: Loading Images

I'm trying to make Space Invaders as a project, I've watched videos on creating it and I have done quite a bit.
I've played around with it a lot, but there's always that one thing that goes wrong which messes up the entire thing.
This is my first post here, I'm not quite sure how to do this... let's see...
I keep facing this error, and it's not budging:
C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py:198: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
pygame.draw.rect(window, (0, 255, 0), (
Traceback (most recent call last):
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 415, in <module>
main_menu()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 410, in main_menu
main()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 377, in main
boss.shoot()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 90, in shoot
laser = Laser(self.x - 20, self.y, self.laser_img)
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 109, in __init__
self.mask = pygame.mask.from_surface(self.img)
TypeError: argument 1 must be pygame.Surface, not None
Can anyone help me fix it? I'm not sure what to do here.
Look at this line here
boss = Boss(random.randrange(340, 360), random.randrange(-700, -100))
This is how you are instantiating your Boss
Now look at how you defined the init of your Boss class
def __init__(self, x, y, health=200):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
Notice that self.laser_img = None.
Now notice the error you have:
laser = Laser(self.x - 20, self.y, self.laser_img)
Your 3rd argument is None. Now look at the next part of your error:
self.mask = pygame.mask.from_surface(self.img)
self.img is actually None that is why you are getting an error.

bbox works when inputting exact coordinates within module but fails with variable containing identical data

I'm having an issue trying to make a screen grab of an area defined by lines in a config file:
The following code:
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1,coordstore.y1,coordstore.x2,coordstore.y2 = (line[4]).strip(),(line[5]).strip(),(line[6]).strip(),(line[7]).strip() # note: confusing. 0=line 1, 1=line2 etc.
coordstore.coords = coordstore.x1+',',coordstore.y1+',',coordstore.x2+',',coordstore.y2
coordstore.stripped = ' '.join((coordstore.coords))
print(coordstore.stripped)
return(coordstore.stripped)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
prints exactly this value: 10, 20, 100, 300
it then fails with this Traceback:
Traceback (most recent call last):
File "file location", line 82, in <module>
screenshot()
File "file location", line 80, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 38, in _grab
x1, y1, x2, y2 = bbox
ValueError: too many values to unpack (expected 4)
If I manually replace (bbox=(coordstore.stripped)) with (bbox=(10, 20, 100, 300)) which is literally identical to what the variable prints, the code works perfectly but is not useful for my needs. What am I not seeing? Thanks for the help!
UPDATE:
I have tried another approach.
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1 = (line[4]).strip()
coordstore.y1 = (line[5]).strip()
coordstore.x2 = (line[6]).strip()
coordstore.y2 = (line[7]).strip()
print(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2)
return(coordstore.x1, coordstore.y1, coordstore.x2, coordstore.y2)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
This prints
10, 20, 100, 300
but returns the following Traceback errors:
Traceback (most recent call last):
File "module location", line 84, in <module>
screenshot()
File "module location", line 82, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 42, in _grab
raise ValueError('bbox y2<=y1')
ValueError: bbox y2<=y1
As you have mentioned in comments the value of coordstore.stripped is string. And expected argument by ImageGrab2.grab is type of tuple so, first you have to convert it into tuple.
Update the method like this:
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=tuple(map(int, coordstore.stripped.split(', ')))) # X1,Y1,X2,Y2
im.save('tc.png')

AttributeError: 'int' object has no attribute '_erase' Python 3.1

I am working in Python 3.1 and I want to make a game of avoiding falling objects. I always get a module error.
My livewires is 1.9.1..
games.screen.background = games.load_image("boaj.jpg")
budala = Budala()
games.screen.add(budala)
games.screen.add(Covjek(image = games.load_image("kamijonhehe.jpg"),
x = games.screen.width/2,
bottom = 720))
games.screen.event_grab = True
games.mouse.is_visible = False
games.music.load("smukwed.mp3")
games.music.play()
games.music.play()
games.screen.mainloop()
full error code:
Traceback (most recent call last):
File "C:\Users\nikol\Desktop\Python\prugrami limun\izbegavalje.py", line
71, in <module>
games.screen.mainloop()
File "C:\Python31\lib\site-packages\livewires\games.py", line 303, in
mainloop
object._erase()
AttributeError: 'int' object has no attribute '_erase'
if you need a full code ask in the comments

Python/Tkinter Event Argument Issue

my code seems to run fine with the brown square appearing in the blank window until I try and press one of the keys, when I do that nothing happens apart from an error message appearing. Any ideas?
from tkinter import *
x, y, a, b = 50, 50, 100, 100
d = None
vel_dic = {
"Left": ("left", -4, 0),
"Right": ("right", 4, 0),
"Down": ("down", 0, 4),
"Up": ("up", 0, -4)}
class Sprite:
def __init__(self):
self.move
self.x, self.y, self.a, self.b = 50, 50, 100, 100
self.d = 0
self.canvas = Canvas(tk, height = 600, width = 600)
self.canvas.grid(row=0, column=0, sticky = W)
self.coord = [self.x, self.y, self.a, self.b]
self.shape = self.canvas.create_rectangle(*self.coord, outline = "#cc9900", fill = "#cc9900")
def move():
if self.direction != 0:
self.canvas.move(self.rect, self.xv, self.yv)
tk.after(33, move)
def on_keypress(event):
self.direction, self.xv, self.yv = vel_dic[event.keysym]
def on_keyrelease(event):
self.direction = 0
tk = Tk()
tk.geometry("600x600")
sprite1 = Sprite()
tk.bind_all('<KeyPress>', sprite1.on_keypress)
tk.bind_all('<KeyRelease>', sprite1.on_keyrelease)
Error message when I press the right arrow key:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keypress() takes 1 positional argument but 2 were given
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keyrelease() takes 1 positional argument but 2 were given
When calling to function inside an object, self (the instance of the object) is sent as a first argument. You can undo that with some methods, staticmethod as the most common one, but that is not what you look for in that case.
The error you get indicates the interpreter sent this self parameter and the regular event parameter, but your method gets only one parameter, and can not handle them.
Make sure all your functions gets self (or any name you choose like inst) as a first parameter in addition to the other parameters:
def on_keyrelease(self, event):
Same goes for move and on_keypress.

TypeError: 'module' object not callable

I have searched thoroughly before posting this. I seem to have a 'module' object not callable error. Here is my code:
""" Create Snake """
def createSnake():
x = randrange(0, 720, 20)
y = randrange(0, 480, 20)
size = 3
snakeBox = ""
snake = []
for i in range(size):
snakeBox = pygame.rect((x + 20*size, y + 20*size), (20, 20))
snake.append(snakeBox)
return snake
This is the error I recieve on execution:
root#raspberrypi:/home/pi/Codes/Snake# python Snake.py
Traceback (most recent call last):
File "Snake.py", line 108, in <module>
if __name__ == '__main__': main()
File "Snake.py", line 106, in main
gameScreen()
File "Snake.py", line 95, in gameScreen
game()
File "Snake.py", line 57, in game
snake = createSnake()
File "Snake.py", line 49, in createSnake
snakeBox = pygame.rect((x + 20*size, y + 20*size), (20, 20))
TypeError: 'module' object is not callable
I cannot seem to figure out what the error is as I think I have imported my modules correctly
from pygame.locals import *
Thank you for your help :')
It seems likes a simple typo of pygame.Rect.
Replace:
pygame.rect
with:
pygame.Rect

Categories

Resources