Space Invaders: Loading Images - python

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.

Related

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.

Strange pygame Rect glitch in python 3

I'm currently making a game on pygame in Python 3. One part of my code is:
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= left):
where ballrect and brick are pygame.Rect variables. When ran, the program crashes and I get the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "E:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "E:/Comp_Sci/game-balls/pad_bounce_3.py", line 158, in <module>
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= left):
NameError: name 'left' is not defined
and 'left' is supposed to be an attribute of the pygame.Rect class. Even more interestingly, I use the 'left' attribute several times in my code and it works fine...
What am I doing terribly wrong?
EDIT: I found the issue. What was happening is that, at times, ballrect would sometimes not be defined.
The variable 'left' at the end of the condition, is it defined? and (ballrect.right <= left): Did you mean brick.left? Try:
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= brick.left):
From what I can tell it might be better to use brick.collidepoint(ballrect)
I found the issue. What was happening is that, at times, ballrect would sometimes not be defined.

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

Weird error with .addstr() in a derwin()-object in Python Curses

I'm trying to segment one window in curses into several sub-windows (with derwin()).
The code creates two sub-windows and I can add a string; no problem with the first function. The second one is pretty much exactly the same but gives me an error when I try to add a string with addstr()
class Window(GUI):
'''
Window-object
'''
def __init__(self, y_max , x_max, y_pos , x_pos, Target, screen):
self.Win_Count = 0
self.y_pos = y_pos
self.x_pos = x_pos
self.y_max = y_max
self.x_max = x_max
self.parent = screen
self.Target = Target
#Window-Objects
self.Win = self.create_win_parent(y_pos)
self.Name_Win = self.create_name_win(self.Win)
self.IP_Win = self.create_ip_win(self.Win)
def create_win_parent(self, y_pos):
y_size = 1
x_size = self.x_max - self.x_pos
new_win_obj = self.parent.derwin(y_size, x_size, self.y_pos, 0)
self.Win_Count += 1
return new_win_obj
def create_name_win(self, Win_Obj):
x = Win_Obj.derwin(1,40, 0,0)
x.box()
x.addstr(0,5," CUSTOMER NAME ")
return x
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
I'm getting this vague error:
Traceback (most recent call last):
File "./2pollng.py", line 229, in <module>
wrapper(main) # Enter the main loop
File "/usr/lib/python2.6/curses/wrapper.py", line 43, in wrapper
return func(stdscr, *args, **kwds)
File "./2pollng.py", line 222, in main
Main_App.Run(screen)
File "./2pollng.py", line 106, in Run
self.Create_Win(self.Inv.index(e), e)
File "./2pollng.py", line 90, in Create_Win
Win_Obj = Window(self.y_max, self.x_max, y_pos, x_pos, Target_x, self.screen)
File "./2pollng.py", line 141, in __init__
self.IP_Win = self.create_ip_win(self.Win)
File "./2pollng.py", line 160, in create_ip_win
x.addstr(0,5," IPADDRESS ")
_curses.error: addstr() returned ERR
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
In this function Win_Obj.derwin(1,15, 0,41) shows that x-pos should between 0 and 14. While in the code addstr(0,5," IP-ADDRESS ") x starts at 5 and the length of string " IP-ADDRESS " is greater than (15-5). So you got the ERROR.
Not really sure about the specifics but it had ( as indicated by the interpreter, duh) something to do with the strings and them not having enough space in the subwindows i created.

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

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.

Categories

Resources