在pygame中连续移动一个盒子

时间:2015-11-05 06:26:46

标签: python 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()

任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:2)

您想要在按某个键时更改应用程序的状态。所以你需要一个变量来跟踪那个状态(状态是:框应该移动什么方向?)。

这是一个完整的,最小的例子,可以满足您的需求。请注意评论。

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函数轻松移动屏幕内的矩形。

答案 1 :(得分:1)

尝试将输入的密钥保存到变量中,并在Event-Loop之后进行检查。 像这样:

#...
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语句。一段时间后,它可能会有点混乱。 请检查以下问题以保持代码简短:

Replacements for switch statement in Python?

答案 2 :(得分:0)

以下是两个版本,第一个演示了如何利用事件循环来获得连续的移动(类似于Sloth的解决方案,但对于不熟悉字典的初学者来说有点简单),第二个一个展示如何使用pygame.key.get_pressed()实现此目的。

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

我实际上建议使用vectors而不是velocity_xvelocity_y变量,而另一个变量用于精灵的实际位置。 pygame.Rect不能将浮点数作为坐标,因此位置的向量或单独变量会更准确。

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()