Search code examples
python-2.7raspberry-pipygameraspbiangpio

GPIO pins and pygame


I am planning on making a game with pygame using gpio buttons. Here is the code:

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)

However, when I press on the X button on the top of the window, it doesn't close. Is there a possible solution for this?

EDIT: Everyone is giving the same answer, that I am not adding a for loop to check events and quit. I did put that, here in my code:

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break

I have also tried sys.exit().

EDIT 2: @Shahrukhkhan asked me to put a print statement inside the for event in pygame.event.get(): loop, which made the loop like this:

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

Solution

  • There are two possible ways to close the pygame window .

    1. after the end of while loop simply write
       
      import sys
      while 1:
           .......
      pygame.quit()
      sys.exit()
      

    2.instead of putting a break statement ,replace break in for loop immediately after while as

    while 1:
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
    ......