Python Forum

Full Version: Need Help With My PYgame Script
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import pygame

pygame.init()

display_width = 800
display_height = 600

Black = (0, 0, 0)
White = (255, 255, 255)
Red = (255, 0, 0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Racing Game')
clock = pygame.time.Clock()

ManImg = pygame.image.load('guy.jpg')

def Man(x,y):
        gameDisplay.blit(ManImg,(x,y))
x = (display_width * 0.45)
y = (display_height* 0.8)
x_change = 0

crashed = False

while not crashed:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        crashed = True
                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                                x_change = -5
                        elif event.key == pygame.K_RIGHT:
                                x_change = 5
                        if event.type == pygame.KEYUP:
                                event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT
                                x_change = 0
        x += x_change        
        gameDisplay.fill(White)                
        Man(x,y)
        pygame.display.update()
        clock.tick(60)

pygame.quit()
quit()

        
                
        
When I press left or right my character will constantly move in that direction. How can I make it where when i let go of right or left the character stops where it is? I've already tried but its not seeming to work.
1. indentation is off. KEYUP will never be called in KEYDOWN.
You should check into keys states.
# Keys state. still need pygame.event.get() or pygame.event.pump() before getting states.
keyspressed = pygame.key.get_pressed()
if keyspressed[pygame.LEFT]:
    x -=5
if keyspressed[pygame.RIGHT]:
    x += 5
# etc
2. pygame has builtin colors
import pygame
print(pygame.color.THECOLORS.keys())
print()
print(pygame.Color('red'))
Thank You Good Sir