So, I am python beginner and wanted to create a space invader game. But I’m facing an issue.
The player object escapes the pygame window if I press the left arrow key or the right arrow key for a longer duration of time.
Here’s my code –
JavaScript
x
41
41
1
import pygame
2
pygame.init()
3
4
5
window = pygame.display.set_mode((1200,800))
6
pygame.display.set_caption('RESCUE THE SPACESHIP')
7
8
close = False
9
10
spaceship_velocity = 0
11
spaceship_X = 550
12
spaceship_Y = 670
13
14
spacehip_img = pygame.image.load('spaceship.png')
15
16
17
while not close:
18
19
for event in pygame.event.get():
20
if event.type == pygame.QUIT:
21
quit()
22
if event.type == pygame.KEYDOWN:
23
if event.key == pygame.K_LEFT:
24
spaceship_velocity -= 1
25
if event.key == pygame.K_RIGHT:
26
spaceship_velocity += 1
27
28
#Doesn't seems to work
29
if spaceship_X < -25:
30
spaceship_X == -25
31
if spaceship_X > 1125:
32
spaceship_X == 1125
33
34
spaceship_X = spaceship_X + spaceship_velocity
35
print(spaceship_X)
36
37
window.fill((255,255,255))
38
window.blit(spacehip_img , (spaceship_X , spaceship_Y))
39
pygame.display.update()
40
41
Before asking this question I’ve tried this but it doesn’t seems to restrict the spaceship within the window
JavaScript
1
5
1
if spaceship_X < -25:
2
spaceship_X == -25
3
if spaceship_X > 1125:
4
spaceship_X == 1125
5
Any ideas how to fix it up?
Advertisement
Answer
I CHANGED
JavaScript
1
2
1
==
2
TO
JavaScript
1
2
1
=
2
AND IT WORKED PERFECTLY FOR ME
BEFORE
JavaScript
1
5
1
if spaceship_X < -25:
2
spaceship_X == -25
3
if spaceship_X > 1125:
4
spaceship_X == 1125
5
AFTER
JavaScript
1
5
1
if spaceship_X < -25:
2
spaceship_X = -25
3
if spaceship_X > 1125:
4
spaceship_X = 1125
5