2015-11-05 65 views
2

我寫了下面的代碼來創建一個簡單的遊戲,當你點擊鍵盤上的箭頭時,一個盒子會在遊戲中移動一個單位。pygame中的一個盒子的連續移動

我想讓它如此,如果我推動任何箭頭按鈕,方框將繼續朝那個方向移動,直到另一個箭頭被按下。所以,如果我推右箭頭一次,而scooting +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() 

任何幫助,將不勝感激。

回答

1

嘗試將輸入的密鑰保存到變量中,並在事件循環之後檢查它。 像這樣:

#... 
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?

+0

im不知道我跟着,你能給我一個樣本嗎? –

+0

@NoahDukehart我給你一個簡單的答案。 ;) 只需將事件處理中的if-else-block放在事件處理的下面,並將它放在for-event-statement之下,或者交替研究一下該鏈接中提到的目錄映射,以稍微減少一些代碼。 –

+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功能,能夠輕鬆移動矩形裏面的畫面。

+0

我問了一個新問題 –

+0

如何找到矩形的中心,以便我可以讓我的代碼清潔 –

0

這裏有兩個版本,第一個演示如何利用事件循環獲得持續運動(類似於Sloth的解決方案,但對於尚不知字典的初學者來說更簡單),第二個演示如何實現這一點與pygame.key.get_pressed()

按鍵將速度設置爲在while循環中用於更改矩形的x和y位置的新值。我還建議使用pygame.math.Vector2而不是velocity_xvelocity_y變量。

import sys 
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() 
    sys.exit() 

pygame.key.get_pressed的缺點是,你可以不知道該按鍵的順序,但代碼看起來有點簡單。

import sys 
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() 
    sys.exit()