简体   繁体   中英

How do I make autonomous movement in pygame?

I'm new to pygame and I'm trying to do the simplest thing ever here really, I just want to have a circle move across the screen with no input from the user. I only seem to find advice online on how to move an object using the keys which isn't what I want I just want it to move on its own and so that the user can watch it move.

Here's what I was trying to use to do this.

Code Start Here:

import pygame module in this program
import pygame
pygame.init()



white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
  

X = 400
Y = 400
  

display_surface = pygame.display.set_mode((X, Y ))
  

pygame.display.set_caption('Drawing')
  

display_surface.fill(white)
  
x,y=[300,50]
pygame.draw.circle(display_surface,green, (x, y), 20, 0)
  

clock = pygame.time.Clock()

def move():
    global y
    y=y+1
  
while True :
    clock.tick(30)
    move()
   
    for event in pygame.event.get() :
        # if event object type is QUIT
        # then quitting the pygame
        # and program both.
        if event.type == pygame.QUIT :



            pygame.quit()
           
            quit()

    pygame.display.update()

Code End Here:

You have to redraw the scene in every frame:

import pygame
pygame.init()

white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
X = 400
Y = 400

display_surface = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Drawing')
clock = pygame.time.Clock()

x,y=[300,50]
def move():
    global y
    y=y+1
  
# application loop  
run = True  
while run:

    # limit the frames per second 
    clock.tick(30)
   
    # event loop
    for event in pygame.event.get() :
        if event.type == pygame.QUIT:
            run = False

    # update the position of the object
    move()

    # clear disaply
    display_surface.fill(white)

    # draw scene
    pygame.draw.circle(display_surface,green, (x, y), 20, 0)

    # update disaply
    pygame.display.update()

pygame.quit()
quit()

The typical PyGame application loop has to:

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