Reputation: 93
I am creating a game using pygame and want to restrict the user to only being able to move left, right, up, down but not diagonally. The code I have supplied below allows the player to move within the screen bounds. How do I stop diagonal movement?
class player:
def __init__(self, x, y, width, height, colour):
self.width = width # dimensions of player
self.height = height # dimensions of player
self.x = x # position on the screen
self.y = y # position on the screen
self.colour = colour # players colour
self.rect = (x, y, width, height) # all the players properties in one
self.vel = 1 # how far/fast you move with each key press
def draw(self, win):
pygame.draw.rect(win, self.colour, self.rect)
def move(self):
keys = pygame.key.get_pressed() # dictionary of keys - values of 0/1
if keys[pygame.K_LEFT]: # move left: minus from x position value
if self.x <= 5: # if player tries to go too far left
pass
else:
self.x -= self.vel
if keys[pygame.K_RIGHT]: # move right: add to x position value
if self.x == 785: # if player tries to go too far right
pass
else:
self.x += self.vel
if keys[pygame.K_UP]: # move up: minus from y position value
if self.y <= 105: # if player tries to go too far up
pass
else:
self.y -= self.vel
if keys[pygame.K_DOWN]: # move down from
if self.y >= 785: # if player tries to go too far down
pass
else:
self.y += self.vel
self.update()
def update(self):
self.rect = (self.x, self.y, self.width, self.height) # redefine where the player is
Upvotes: 3
Views: 225
Reputation: 595
Make the if blocks for control mapping an if-else chain to prevent multiple keys registering each update.
def move(self):
keys = pygame.key.get_pressed() # dictionary of keys - values of 0/1
if keys[pygame.K_LEFT]: # move left: minus from x position value
if self.x <= 5: # if player tries to go too far left
pass
else:
self.x -= self.vel
elif keys[pygame.K_RIGHT]: # move right: add to x position value
if self.x == 785: # if player tries to go too far right
pass
else:
self.x += self.vel
elif keys[pygame.K_UP]: # move up: minus from y position value
if self.y <= 105: # if player tries to go too far up
pass
else:
self.y -= self.vel
elif keys[pygame.K_DOWN]: # move down from
if self.y >= 785: # if player tries to go too far down
pass
else:
self.y += self.vel
self.update()
Upvotes: 3