Python Forum
[PyGame] Space Invaders in PyGame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Space Invaders in PyGame
#6
I ran the code that you've pasted above and it works fine here, but I'm wondering if you have got the "update" method indented correctly within the spaceship class.

it should be:
#create spaceship class
class Spaceship(pygame.sprite.Sprite):
	def __init__(self, x, y):
		pygame.sprite.Sprite.__init__(self)
		self.image = pygame.image.load("img/spaceship.png") # load image
		self.rect = self.image.get_rect() # force image to rectangle
		self.rect.center = [x, y]

	def update(self):
		# set movement speed
		speed = 8

		# get key press
		key = pygame.key.get_pressed()
		if key[pygame.K_LEFT] and self.rect.left > 0:
			print('Move Left')
			self.rect.x -= speed
		if key[pygame.K_RIGHT] and self.rect.right < screen_width:
			self.rect.x += speed
This ensures the update method is part of that class rather than a method on its own.

Also, if you want to troubleshoot and check whether something is working as it should, you can print it. In the code above I've put a print statement which will say 'Move Left' when the conditions are met. It's a quick way to see what's going on and where the problems might be. Of course you'll want to remove that once you get it working :)
Reply


Messages In This Thread
Space Invaders in PyGame - by Russ_CW - Oct-30-2020, 04:51 PM
RE: Space Invaders in PyGame - by michael1789 - Nov-08-2020, 10:37 PM
RE: Space Invaders in PyGame - by joe_momma - Nov-10-2020, 09:37 PM
RE: Space Invaders in PyGame - by Russ_CW - Nov-15-2020, 11:05 AM
RE: Space Invaders in PyGame - by luke83 - Nov-22-2020, 05:28 AM
RE: Space Invaders in PyGame - by Russ_CW - Nov-22-2020, 12:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  question about my pygame code for space shooter Than999 4 2,541 Feb-07-2022, 03:55 AM
Last Post: metulburr
  [PyGame] newbie needs help with space invaders n0x 2 2,193 Jul-04-2020, 11:32 AM
Last Post: n0x
  [PyGame] Space Invaders Python Bug? CJMinecraft 2 4,447 Mar-31-2017, 03:37 PM
Last Post: georgecoopers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020