GPIO 引脚和 pygame
GPIO pins and pygame
我打算用 pygame 使用 gpio 按钮制作游戏。这是代码:
from gpiozero import Button
import pygame
from time import sleep
from sys import exit
up = Button(2)
left = Button(3)
right = Button(4)
down = Button(14)
fps = pygame.time.Clock()
pygame.init()
surface = pygame.display.set_mode((1300, 700))
x = 50
y = 50
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if up.is_pressed:
y -= 5
if down.is_pressed:
y += 5
if left.is_pressed:
x -= 5
if right.is_pressed:
x += 5
surface.fill((0, 0, 0))
pygame.draw.circle(surface, (255, 255, 255), (x, y), 20, 0)
pygame.display.update()
fps.tick(30)
但是,当我按下 window 顶部的 X 按钮时,它并没有关闭。有没有可能的解决方案?
编辑: 每个人都给出了相同的答案,我没有添加 for 循环来检查事件并退出。我确实把它放在了我的代码中:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
我也试过sys.exit()
.
编辑 2:@Shahrukhkhan 让我在 for event in pygame.event.get():
循环中放置一个 print 语句,这使得循环像这样:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print "X pressed"
break
root@raspberrypi:~/Desktop# python game.py
X pressed
X pressed
您需要创建一个事件并在其中退出 pygame
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
有两种方法可以关闭 pygame window .
- while循环结束后简单写
import sys
while 1:
.......
pygame.quit()
sys.exit()
</pre>
2.instead of 放一个break语句,在while as
之后立即替换break in for循环
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
......
我打算用 pygame 使用 gpio 按钮制作游戏。这是代码:
from gpiozero import Button
import pygame
from time import sleep
from sys import exit
up = Button(2)
left = Button(3)
right = Button(4)
down = Button(14)
fps = pygame.time.Clock()
pygame.init()
surface = pygame.display.set_mode((1300, 700))
x = 50
y = 50
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if up.is_pressed:
y -= 5
if down.is_pressed:
y += 5
if left.is_pressed:
x -= 5
if right.is_pressed:
x += 5
surface.fill((0, 0, 0))
pygame.draw.circle(surface, (255, 255, 255), (x, y), 20, 0)
pygame.display.update()
fps.tick(30)
但是,当我按下 window 顶部的 X 按钮时,它并没有关闭。有没有可能的解决方案?
编辑: 每个人都给出了相同的答案,我没有添加 for 循环来检查事件并退出。我确实把它放在了我的代码中:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
我也试过sys.exit()
.
编辑 2:@Shahrukhkhan 让我在 for event in pygame.event.get():
循环中放置一个 print 语句,这使得循环像这样:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print "X pressed"
break
root@raspberrypi:~/Desktop# python game.py
X pressed
X pressed
您需要创建一个事件并在其中退出 pygame
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
有两种方法可以关闭 pygame window .
- while循环结束后简单写
import sys while 1: ....... pygame.quit() sys.exit() </pre>
2.instead of 放一个break语句,在while as
之后立即替换break in for循环while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
......