問題描述
import pygame
r_colour = (200, 100,100)
bg_colour = (0,175,200)
(width, height) = (600, 600)
screen = pygame.display.set_mode((width, height))
screen.fill(bg_colour)
pygame.draw.rect(screen, r_colour, (30, 30, 100, 100), 0)
pygame.display.flip()
running = True
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
screen.fill(bg_colour)
pygame.draw.rect(screen, r_colour, (20, 30, 100, 100), 0)
pygame.display.update()
if running == True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
screen.fill(bg_colour)
pygame.draw.rect(screen, r_colour, (20, 30, 100, 100), 0)
pygame.display.update()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
running = False
pygame.quit()
我試圖讓紅色方塊在按下s"鍵時移動,不知道為什么它只移動一次然后停止.對編程非常陌生,所以很抱歉,如果它很長或難以閱讀.
I am trying to get the red square to move when pressing the 's' key, not sure as to why it only moves once and then stops. Very new to programming, so I am sorry, if it's long or hard to read.
推薦答案
一個典型的應用程序有 1 個單一的應用程序循環.應用程序循環:
A typical application has 1 single application loop. The application loop does:
- 處理事件并根據事件更改狀態
- 清除顯示
- 繪制場景
- 更新顯示
KEYDOWY
事件在按下某個鍵時發生一次,但在按住某個鍵時不會連續發生.
對于連續運動,您可以通過 <代碼>pygame.key.get_pressed():
The KEYDOWY
event occurs once when a key is pressed, but it does not occur continuously when a key is hold down.
For a continuously movement you can get the state of the keys by pygame.key.get_pressed()
:
keys = pygame.key.get_pressed()
例如如果 s 的狀態被按下,可以通過 keys[pygame.K_s]
來評估.
e.g. If the state of s is pressed can be evaluated by keys[pygame.K_s]
.
為矩形的位置添加坐標(x
, y
).當按鍵被按下時,在主應用程序循環中不斷地操作位置.
Add coordinates (x
, y
) for the position of the rectangle. Continuously manipulate the position in the main application loop, when a key is pressed.
例如
如果按下 d,則增加 x
,如果按下 a,則減少 x
.
如果按下 s,則增加 y
,如果按下 w,則減少 y
:
e.g.
Increment x
if d is pressed and decrement x
if a is pressed.
Increment y
if s is pressed and decrement y
if w is pressed:
import pygame
r_colour = (200, 100,100)
bg_colour = (0,175,200)
(width, height) = (600, 600)
x, y = 20, 30
screen = pygame.display.set_mode((width, height))
running = True
while running:
# handle the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# change coordinates
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
x += 1
if keys[pygame.K_a]:
x -= 1
if keys[pygame.K_s]:
y += 1
if keys[pygame.K_w]:
y -= 1
# clear the display
screen.fill(bg_colour)
# draw the scene
pygame.draw.rect(screen, r_colour, (x, y, 100, 100), 0)
# update the display
pygame.display.update()
pygame.quit()
這篇關于Python只運行一次while循環的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!