Skip to content
Advertisement

Object escapes the window in pygame . How to prevent it from doing so?

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 –

import pygame
pygame.init()


window = pygame.display.set_mode((1200,800))
pygame.display.set_caption('RESCUE THE SPACESHIP')

close = False

spaceship_velocity = 0
spaceship_X = 550
spaceship_Y = 670

spacehip_img = pygame.image.load('spaceship.png')


while not close:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                spaceship_velocity -= 1
            if event.key == pygame.K_RIGHT:
                spaceship_velocity += 1

    #Doesn't seems to work
    if spaceship_X < -25:
        spaceship_X == -25
    if spaceship_X > 1125:
        spaceship_X == 1125

    spaceship_X = spaceship_X + spaceship_velocity
    print(spaceship_X)

    window.fill((255,255,255))
    window.blit(spacehip_img , (spaceship_X , spaceship_Y))
    pygame.display.update()

Before asking this question I’ve tried this but it doesn’t seems to restrict the spaceship within the window

if spaceship_X < -25:
    spaceship_X == -25
if spaceship_X > 1125:
    spaceship_X == 1125

Any ideas how to fix it up?

Advertisement

Answer

I CHANGED

==

TO

=

AND IT WORKED PERFECTLY FOR ME

BEFORE

if spaceship_X < -25:
    spaceship_X == -25
if spaceship_X > 1125:
    spaceship_X == 1125

AFTER

if spaceship_X < -25:
    spaceship_X = -25
if spaceship_X > 1125:
    spaceship_X = 1125
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement