NotAName
NotAName

Reputation: 4347

Pygame freezes and doesn't react to keypresses or trying to close the window

I have checked other similar questions but couldn't find the answer to my problem. I'm trying to make a simple chess game in pygame to practice some AI coding, but I've run into a bit of trouble with pygame window refusing to close or react to inputs in any way.

I get chess board on screen, but then everything just hangs. It's strange because I thought that I have set up methods to terminate the game properly, but for some reason they don't work.

My code so far is:

import pygame
import sys

class ChessGame():
    '''An overall class controlling a chess game'''

    def __init__(self):
        '''Initialise the class and set up variables'''

        pygame.init()
        self.screen = pygame.display.set_mode((600, 600))
        self.bg = pygame.image.load('images/board.jpg')


    def _check_keydown_events(self, event):
        '''Take action on user key presses'''

        if event.key == pygame.K_ESCAPE:
            sys.exit()

    def check_events(self):
        '''React to user input'''

        for event in pygame.event.get():
            if pygame.event == pygame.QUIT:
                sys.exit()
            elif pygame.event == pygame.KEYDOWN:
                self._check_keydown_events(event)

    def update_screen(self):

        self.screen.blit(self.bg, (0,0))
        pygame.display.flip()

    def run_game(self):
        '''Run main game loop'''
        clock = pygame.time.Clock()

        while True:
            self.update_screen()
            self.check_events()
            clock.tick(2)

def main():
    chess = ChessGame()
    chess.run_game()

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 73

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

pygame.event is a module. The name of the variable which refers to the event object is event.
The type of the event is stored in the the .type property of pygame.event.Event object (event.type):

class ChessGame():

    # [...]

    def check_events(self):
        '''React to user input'''

        for event in pygame.event.get():

            #if pygame.event == pygame.QUIT:
            if event.type == pygame.QUIT:
                sys.exit()

            # elif pygame.event == pygame.KEYDOWN:
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)

Upvotes: 1

Related Questions