流畅的连续运动

Smooth continuous movement

我用 pygame 做了一个小游戏,尽管我觉得它不错,但有一件事我想改进:我希望白色小方块在按下某个键时继续移动并停止移动当不再按下键时。

如何在按下箭头键(向下、向上、向左或向右)时连续移动?

到目前为止,这是我的代码:

import pygame

pygame.init()

# Setup
width,height = 500,500
screen = pygame.display.set_mode((width,height))

# Colors
WHITE = (255,255,255)
LGREY = (100,100,100)
DGREY = (50,50,50)

# Variables
x = y = 50

# Functions
def draw_box():
    global x,y
    if x > 425:
        x = 50
    if x <50:
        x = 425    
    if y > 425:
        y = 50
    if y < 50:
        y = 425    
    pygame.draw.rect(screen,WHITE,pygame.Rect(x+1,y+1,24,24),2)

def draw_grid():
    for i in range (1,16):
        pygame.draw.line(screen,DGREY,(50+i*25,50),(50+i*25,450),1)
        pygame.draw.line(screen,DGREY,(50,50+i*25),(450,50+i*25),1)
    pygame.draw.rect(screen,WHITE,pygame.Rect(50,50,25*16,25*16),1)

def main():
    global x, y
    
    running = True
    clock = pygame.time.Clock()

    while running:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                   y += 25
                if event.key == pygame.K_UP:
                    y -= 25
                if event.key == pygame.K_RIGHT:
                    x += 25
                if event.key == pygame.K_LEFT:  
                    x -= 25
            if event.type == pygame.KEYUP:
                if event.key in (pygame.K_DOWN, pygame.K_UP):
                    y +=  0
                elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                    x +=  0                
          
            screen.fill(LGREY)
            draw_grid()
            draw_box()
    
        pygame.display.update()
        clock.tick(50)
    pygame.quit()

if __name__ == '__main__':
    main()

这是因为 x 和 y 的值只会在按下某个键的时候被修改,所以你必须一直按下这些键。

例如,您需要一种方法将状态保存在 change_x 和 change_y 变量中,并降低滴答率。

在下面的示例代码中,我添加了这两个新变量并减慢了游戏速度。现在,当按下一个键时,状态会发生变化以更改 x 或 y,并且更新函数会将更新应用到 x 和 y 位置。

import pygame

pygame.init()

# Setup
width,height = 500,500
screen = pygame.display.set_mode((width,height))

# Colors
WHITE = (255,255,255)
LGREY = (100,100,100)
DGREY = (50,50,50)

# Variables
x = y = 50
change_x = 0
change_y = 0


# Functions
def draw_box():
    global x,y
    if x > 425:
        x = 50
    if x <50:
        x = 425    
    if y > 425:
        y = 50
    if y < 50:
        y = 425    
    pygame.draw.rect(screen,WHITE,pygame.Rect(x+1,y+1,24,24),2)

def draw_grid():
    for i in range (1,16):
        pygame.draw.line(screen,DGREY,(50+i*25,50),(50+i*25,450),1)
        pygame.draw.line(screen,DGREY,(50,50+i*25),(450,50+i*25),1)
    pygame.draw.rect(screen,WHITE,pygame.Rect(50,50,25*16,25*16),1)

def update_pos():
    global x, y, change_x, change_y
    x += change_x
    y += change_y

def main():
    global x, y, change_x, change_y
    
    running = True
    clock = pygame.time.Clock()

    while running:
        # event processing stage
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                   change_y = 25
                if event.key == pygame.K_UP:
                    change_y = -25
                if event.key == pygame.K_RIGHT:
                    change_x = 25
                if event.key == pygame.K_LEFT:  
                    change_x =- 25
            if event.type == pygame.KEYUP:
                if event.key in (pygame.K_DOWN, pygame.K_UP):
                    change_y =  0
                elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                    change_x =  0
        # update stage
        update_pos()
        
        # draw stage
        screen.fill(LGREY)
        draw_grid()
        draw_box()
    
        pygame.display.update()
        clock.tick(15)
    pygame.quit()

if __name__ == '__main__':
    main()

如果可能,最好避免使用全局变量。 我在学习 pygame 时发现以下站点非常有用,下面是该站点的代码示例:

"""
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
 
import pygame
 
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
 
 
def draw_stick_figure(screen, x, y):
    # Head
    pygame.draw.ellipse(screen, BLACK, [1 + x, y, 10, 10], 0)
 
    # Legs
    pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2)
    pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [x, 27 + y], 2)
 
    # Body
    pygame.draw.line(screen, RED, [5 + x, 17 + y], [5 + x, 7 + y], 2)
 
    # Arms
    pygame.draw.line(screen, RED, [5 + x, 7 + y], [9 + x, 17 + y], 2)
    pygame.draw.line(screen, RED, [5 + x, 7 + y], [1 + x, 17 + y], 2)
 
# Setup
pygame.init()
 
# Set the width and height of the screen [width,height]
size = [700, 500]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("My Game")
 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
 
# Hide the mouse cursor
pygame.mouse.set_visible(0)
 
# Speed in pixels per frame
x_speed = 0
y_speed = 0
 
# Current position
x_coord = 10
y_coord = 10
 
# -------- Main Program Loop -----------
while not done:
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
            # User pressed down on a key
 
        elif event.type == pygame.KEYDOWN:
            # Figure out if it was an arrow key. If so
            # adjust speed.
            if event.key == pygame.K_LEFT:
                x_speed = -3
            elif event.key == pygame.K_RIGHT:
                x_speed = 3
            elif event.key == pygame.K_UP:
                y_speed = -3
            elif event.key == pygame.K_DOWN:
                y_speed = 3
 
        # User let up on a key
        elif event.type == pygame.KEYUP:
            # If it is an arrow key, reset vector back to zero
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_speed = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_speed = 0
 
    # --- Game Logic
 
    # Move the object according to the speed vector.
    x_coord = x_coord + x_speed
    y_coord = y_coord + y_speed
 
    # --- Drawing Code
 
    # First, clear the screen to WHITE. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(WHITE)
 
    draw_stick_figure(screen, x_coord, y_coord)
 
 
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
 
    # Limit frames per second
    clock.tick(60)
 
# Close the window and quit.
pygame.quit()