繁体   English   中英

pygame中盒子的连续运动

[英]Continuous movement of a box in pygame

我编写了以下代码来创建一个简单的游戏,其中,当您单击键盘上的箭头时,盒子会在游戏中移动一个单位。

我正在尝试这样做,以便如果我按任意一个箭头按钮,该框将继续沿该方向移动,直到按下另一个箭头。 因此,如果我按一次向右箭头,而不是滑动+50像素,它将连续在屏幕上移动,直到单击了另一个箭头,然后它将按这种方式移动

import pygame #importing the pygame library

# some initializations
pygame.init()  # this line initializes pygame
window = pygame.display.set_mode( (800,600) ) # Create a window with   width=800 and height=600
pygame.display.set_caption( 'Rectangle move' ) # Change the window's name we create to "Rectangle move"
clock = pygame.time.Clock() # Clocks are used to track and control the frame-rate of a game (how fast and how slow the pace of the game)
                        # This line creates and initializes a clock.

# color definitions, using RBG color model.
black = (0,0,0)
white = (255,255,255)

# initial center position for the square (bob)
x,y = 0,0
lastKey=0
game_loop=True
while game_loop:
    for event in pygame.event.get():   # loop through all events
        if event.type == pygame.QUIT:
            game_loop = False # change the game_loop boolean to False to quit.
        if event.type == pygame.KEYDOWN: 
            lastKey = event.key
    #check last entered key
    #lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
    #set x coordinate minus 50 if left was pressed
    if lastKey == pygame.K_LEFT:
         x -= 50
    if lastKey == pygame.K_RIGHT:
         x += 50
    if lastKey == pygame.K_UP:
         y += 50
    if lastKey == pygame.K_DOWN:
         y -= 50
    if event.key == pygame.K_LEFT:
          x -= 50
    if event.key == pygame.K_RIGHT:
          x += 50
    if event.key == pygame.K_UP:
          y += 50
    if event.key == pygame.K_DOWN:
          y -= 50
 # draw and update screen
 window.fill( black ) # fill the screen with black overwriting even bob.
 pygame.draw.rect( window, white, (x, y, 50, 50) ) # draw bob on the screen with new coordinates after its movement.
                                                      # the parameters are as follows: window: is the window object you want to draw on. white: the object color used to fill the rectangle
                                                      # (x,y,50,50) x is the x position of the left side of the rectangle. y is the y position of the upper side of the rectangle. 
                                                      # In other words (x,y) is the coordinate of the top left point of the rectangle.
                                                      # 50 is the width, and 50 is the height
 pygame.display.update() #updates the screen with the new drawing of the rectangle.

#fps stuff:
 clock.tick(10) # this controls the speed of the game. low values makes the game slower, and large values makes the game faster.

 pygame.quit()

任何帮助将非常感激。

您想在按一个键时更改应用程序的状态 因此,您需要一个变量来跟踪该状态(状态为: 盒子应该向哪个方向移动? )。

这是一个完整的最小示例,可以满足您的需求。 注意注释。

import pygame, sys

pygame.init()
screen = pygame.display.set_mode((640, 480))
screen_r = screen.get_rect()
clock = pygame.time.Clock()
rect = pygame.rect.Rect(0, 0, 50, 50)

# let's start at the center of the screen
rect.center = screen_r.center

# a dict to map keys to a direction
movement = {pygame.K_UP:    ( 0, -1),
            pygame.K_DOWN:  ( 0,  1),
            pygame.K_LEFT:  (-1,  0), 
            pygame.K_RIGHT: ( 1,  0)}

move = (0, 0)

# a simple helper function to apply some "speed" to your movement
def mul10(x):
    return x * 10

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()
        # try getting a direction from our dict
        # if the key is not found, we don't change 'move'
        if e.type == pygame.KEYDOWN:
            move = movement.get(e.key, move)

    # move the rect by using the 'move_ip' function
    # but first, we multiply each value in 'move' with 10
    rect.move_ip(map(mul10, move))

    # ensure that 'rect' is always inside the screen
    rect.clamp_ip(screen_r)
    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('White'), rect)
    pygame.display.update()
    clock.tick(60)

我使用Rect而不是跟踪两个坐标xy ,因为这允许利用move_ipclamp_ip函数轻松在屏幕内移动rect。

尝试将输入的密钥保存到变量中,并在事件循环之后检查它。 像这样:

#...
lastKey = None
while game_loop:
    for event in pygame.event.get():   # loop through all events
        if event.type == pygame.QUIT:
            game_loop = False # change the game_loop boolean to False to quit.
        if event.type == pygame.KEYDOWN: 
            lastKey = event.key
    #check last entered key
    #lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
    #set x coordinate minus 50 if left was pressed
    if lastKey == pygame.K_LEFT
         x -= 50
    #<add the other statements here>
    #(...)

我建议不要使用那么多的if语句。 一段时间后,它可能会有些混乱。 请检查以下问题,以使您的代码简短:

在Python中替换switch语句?

这里有两个版本,第一个演示了如何利用事件循环来获得连续的运动(类似于Sloth的解决方案,但是对于还不知道字典的初学者来说要简单一些),第二个演示了如何使用pygame.key.get_pressed()实现这一点pygame.key.get_pressed()

解决方案1:检查事件循环中按下了哪个键,并将x和y速度更改为所需的值。 然后将速度添加到while循环中的rect.xrect.y位置。

实际上,我建议您使用向量而不是velocity_xvelocity_y变量,并使用另一个变量来表示精灵的实际位置。 pygame.Rect不能将float作为其坐标,因此该位置的向量或单独的变量将更加准确。

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    rect = pg.Rect(100, 200, 40, 60)
    velocity_x = 0
    velocity_y = 0
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_d:
                    velocity_x = 4
                elif event.key == pg.K_a:
                    velocity_x = -4
            elif event.type == pg.KEYUP:
                if event.key == pg.K_d and velocity_x > 0:
                    velocity_x = 0
                elif event.key == pg.K_a and velocity_x < 0:
                    velocity_x = 0

        rect.x += velocity_x
        rect.y += velocity_y

        screen.fill((40, 40, 40))
        pg.draw.rect(screen, (150, 200, 20), rect)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

解决方案2:调用pygame.key.get_pressed来检查当前按住哪个键。 检查是否按住了左,右,上或下键,然后在每帧中调整精灵的位置。

pygame.key.get_pressed的缺点是您不知道按键的顺序,但是代码看起来更简单。

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    rect = pg.Rect(100, 200, 40, 60)
    velocity = (0, 0)
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        keys = pg.key.get_pressed()
        if keys[pg.K_d]:
            rect.x += 4
        if keys[pg.K_a]:
            rect.x -= 4

        screen.fill((40, 40, 40))
        pg.draw.rect(screen, (150, 200, 20), rect)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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