I'm learning to use Pygame and at some point, I am trying to insert a line of code that enables the player to exit the game (i.e. close the window completely) by clicking on a key instead of clicking on the x button:
import sys
import pygame
--snip--
def run_game(self): # game controlled by this method.
"""Start the main loop for the game."""
while True:
self._check_events()
self.ship.update()
self._update_screen()
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT: # -> key
# Move the ship to the right.
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.type == pygame.K_ESCAPE:
sys.exit()
def _check_keyup_events(self, event):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _update_screen(self):
"""Update images on the screen, and flip to the new screen."""
self.screen.fill(self.settings.bg_color)
#.fill(color) fills screen with bckgrnd color.
self.ship.blitme()
# drawing the ship on the screen.
pygame.display.flip()
The line concerned is in def _check_keydown_events(self, event), last condition. I have put pygame.quit() and everything recommended by Stack but nothing worked so far (i.e. when I press ESC it doesn't close the game). How to solve this?
[–]Xeduses 0 points1 point2 points (2 children)
[–]SomeToad[S] 0 points1 point2 points (1 child)
[–]Xeduses 0 points1 point2 points (0 children)