I'm coding a game in pygame while learning OOP and the pygame.sprite.Sprite class, along with the attributes rect comes with, but for some reason, after coding this very simple code, the player doesn't move to the right, it only moves to the left, and without collision detection code, it stops moving once it's coordinates are equal to width. Why is that?
import pygame
import random
width = 800
height = 600
black = (0, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
white = (255, 255, 255)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shmup")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.centerx = width/2
self.rect.bottom = height - 10
self.x_change = 0
self.speedx = 0.2
def change_left(self):
self.x_change += -self.speedx
def change_right(self):
self.x_change += self.speedx
def move_left(self):
self.rect.x += self.x_change
def move_right(self):
self.rect.x += self.x_change
def stop_move_left(self):
self.x_change = 0
def stop_move_right(self):
self.x_change = 0
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
exitGame = False
while not exitGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player.change_left()
if event.key == pygame.K_d:
player.change_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player.stop_move_left()
if event.key == pygame.K_d:
player.stop_move_right()
player.move_left()
player.move_right()
screen.fill(white)
all_sprites.draw(screen)
pygame.display.update()
pygame.quit()
quit()