Python Forum
[PyGame] Need Help With My PYgame Script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Need Help With My PYgame Script
#1
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.
Reply
#2
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'))
99 percent of computer problems exists between chair and keyboard.
Reply
#3
Thank You Good Sir
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020