简体   繁体   中英

Python PyGame Moving Rectangle

I am struggling with moving a drawn rectangle on the screen in pygame, I am trying to create a Snake game. I am very new to Python and object oriented programming in general so it is probably a stupid mistake. Code below.

#X coordinate of snake
lead_x = 300


#sets window position on screen
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (320,240)


#imports pygame module
import sys, pygame

#initialises pygame module
pygame.init()

#changes background colour to green
background_colour = 155, 188, 15
blue =(0,0,255)
red = (100,40,20)
#sets screen size 
screen = pygame.display.set_mode((640, 480))

#changes the background colour
screen.fill(background_colour)

#creates rectangle on the screen
pygame.draw.rect(screen, blue, [lead_x,lead_x,10,10])



#updates display to show new background colour
pygame.display.update()

#Sets the window title to 'Python'
pygame.display.set_caption('Python')

#closes the window when user presses X
running = True



#if cross is clicked set running = False
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

            #Controls

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x -= 10

            if event.key == pygame.K_RIGHT:
                lead_x += 10


  #if running = False close pygame window          
if running == False:
    pygame.quit()

You need to put pygame.draw.rect(screen, blue, [lead_x, lead_y, 10, 10]) in your game loop. As of right now you're drawing the rect on the screen only once, and that's in the beginning of the program. You want to continuously draw the rect at different lead_x and lead_y positions in order for a rect to move on the screen.

You should also put a screen.fill(background_colour) (to clear the previous drawing) and pygame.display.update() (to update the changes) in your loop as well.

EDIT: I noticed something: you probably want to create a variable lead_y and use pygame.draw.rect(screen, blue, [lead_x, lead_y, 10, 10]) so you don't move diagonally every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM