Jan-03-2023, 10:19 PM
(This post was last modified: Jan-03-2023, 10:21 PM by deanhystad.)
Your
And the code is ugly. if you keep the pygame event loop small it is fairly easy to understand the game logic. I've seen pygame code were everything is in the main loop and it is impossible to follow what's happening. You cannot control that the code required to draw a simple message in pygame is ugly, but you can control where you put that code. I would remove the cube.draw() method and make a refresh() function. The refresh() function would do all the screen drawing, including displaying a message. If you wanted to add a scoreboard or a title, or anything, it will be much easier if you have all the code for drawing that stuff located in one place.
Now the main loop can be tight again.
if cube.done()
is in the wrong place. The game ends and the screen doesn't show a message until you click the mouse. Then you have to click again to start a new game.And the code is ugly. if you keep the pygame event loop small it is fairly easy to understand the game logic. I've seen pygame code were everything is in the main loop and it is impossible to follow what's happening. You cannot control that the code required to draw a simple message in pygame is ugly, but you can control where you put that code. I would remove the cube.draw() method and make a refresh() function. The refresh() function would do all the screen drawing, including displaying a message. If you wanted to add a scoreboard or a title, or anything, it will be much easier if you have all the code for drawing that stuff located in one place.
def refresh(surface, cube, msg=None): """Draw all the tic-tac-toe boards.""" surface.fill("white") for square in cube.squares: square.draw(surface) if msg: text = pygame.font.Font(None, 100).render(text, True, 'white') rect = text.get_rect() pos = ((surface.get_width() - rect.width) / 2, (surface.get_height() - rect.height) / 2) surface.blit(text, pos) pygame.display.flip()Still ugly, but isolated.
Now the main loop can be tight again.
refresh(surface, cube) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: if cube.done(): # Game over. Start a new game cube.reset() if cube.mark == ROBOT: cube.play(robot.play(), ROBOT) refresh(surface, cube) else: if cube.click(pygame.Vector2(event.pos)): # Player selected square. Robot's turn, if not cube.done(): refresh(surface, cube) cube.play(robot.play(), ROBOT) # Is the game over? refresh(surface, cube, "Game Over" if cube.done() else None) pygame.event.clear()