Skip to content

Commit

Permalink
Process game over correctly, even if it is a draw. Move click handlin…
Browse files Browse the repository at this point in the history
…g to the board class.
  • Loading branch information
kgodey committed Aug 9, 2015
1 parent 17916b9 commit f19c540
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
24 changes: 20 additions & 4 deletions lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ def get_box_at_pixel(self, x, y):
return box
return None

def process_click(self, x, y):
box = self.get_box_at_pixel(x, y)
if box is not None and not self.game_over:
self.play_turn(box)
self.check_game_over()

def play_turn(self, box):
if box.state != 0:
return
Expand Down Expand Up @@ -108,15 +114,25 @@ def check_for_winner(self):
winner = 1
if all(x == 2 for x in states):
winner = 2
return winner

def check_game_over(self):
winner = self.check_for_winner()
if winner:
self.game_over = True
self.display_winner(winner)
elif all(box.state in [1, 2] for box in self.boxes):
self.game_over = True
if self.game_over:
self.display_game_over(winner)

def display_winner(self, winner):
def display_game_over(self, winner):
surface_size = self.surface.get_height()
winner_text = 'Player %s won!' % winner
font = pygame.font.Font('freesansbold.ttf', surface_size / 8)
text = font.render(winner_text, True, BLACK)
if winner:
text = 'Player %s won!' % winner
else:
text = 'Draw!'
text = font.render(text, True, BLACK, WHITE)
rect = text.get_rect()
rect.center = (surface_size / 2, surface_size / 2)
self.surface.blit(text, rect)
7 changes: 2 additions & 5 deletions tictactoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

pygame.init()
clock = pygame.time.Clock()
board = Board(grid_size=4, box_size=150, border=50, line_width=10)
board = Board(grid_size=3, box_size=100, border=50, line_width=10)

while True:
for event in pygame.event.get():
Expand All @@ -15,10 +15,7 @@
sys.exit()
elif event.type == MOUSEBUTTONUP:
x, y = event.pos
box = board.get_box_at_pixel(x, y)
if box is not None:
board.play_turn(box)
board.check_for_winner()
board.process_click(x, y)

pygame.display.update()
clock.tick(30)

0 comments on commit f19c540

Please sign in to comment.