I made a loop to keep the "enemy" character moving to left and right, but for some reason that I really can't tell why, he just goes to the right and when he hits the border limit that I defined, he "teleports" to the left border and keeps going to the right forever. I even tried to make the "enemyX_change" beeing negative, but he just goes to the left, hit the border and stops. I'm using Python 3.8.
import pygame
import random
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemySprite = pygame.image.load('enemy.png')
enemyX = random.randint(0, 736)
enemyY = random.randint(50, 150)
enemyX_change = 0.3
enemyY_change = 0
def player(x, y):
screen.blit(playerSprite, (x, y))
def enemy(x, y):
screen.blit(enemySprite, (x, y))
# Game Loop
running = True
while running:
# Background color (RGB)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If a key is pressed, check if it's the right or left arrow key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.3
if event.key == pygame.K_RIGHT:
playerX_change = 0.3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Move the spaceship to the left or right
playerX += playerX_change
# Prevents the player from going off the border
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Moves the enemy
enemyX += enemyX_change
# Prevents the enemy from going off the border
if enemyX <= 0:
enemyX = 0.3
elif enemyX >= 736:
enemyX = -0.3
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
enemyXis greater or equal736you decreaseenemyXby-0.3but in your loop you always addenemyX_changewhich is0.3too, soenemyXis unchanged once it reaches736.