我寫了下面的代碼來創建一個簡單的遊戲,當你點擊鍵盤上的箭頭時,一個盒子會在遊戲中移動一個單位。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()
任何幫助,將不勝感激。
im不知道我跟着,你能給我一個樣本嗎? –
@NoahDukehart我給你一個簡單的答案。 ;) 只需將事件處理中的if-else-block放在事件處理的下面,並將它放在for-event-statement之下,或者交替研究一下該鏈接中提到的目錄映射,以稍微減少一些代碼。 –
這是你在說什麼? –