Last active
August 29, 2015 14:14
-
-
Save hernantz/294a387ed25d76ea09a3 to your computer and use it in GitHub Desktop.
Simple tic tac toe game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
GRID = { | |
1: 1, | |
2: 2, | |
3: 3, | |
4: 4, | |
5: 5, | |
6: 6, | |
7: 7, | |
8: 8, | |
9: 9, | |
} | |
WINNER_RESULTS = [ | |
[1, 2, 3], | |
[1, 4, 7], | |
[1, 5, 9], | |
[3, 5, 7], | |
[4, 5, 6], | |
[2, 5, 8], | |
[7, 8, 9], | |
[3, 6, 9], | |
] | |
def check_winner(player): | |
for result in WINNER_RESULTS: | |
if all(GRID[x] == player for x in result): | |
return True | |
def check_game_over(): | |
return all(type(x) is not int for x in GRID.values()) | |
def mark_player_move(player, position): | |
GRID[position] = player | |
def point_repr(val): | |
if val is True: | |
return "✗" | |
if val is False: | |
return "●" | |
return val | |
def get_grid_repr(): | |
return """ | |
------------- | |
| {} | {} | {} | | |
------------- | |
| {} | {} | {} | | |
------------- | |
| {} | {} | {} | | |
------------- | |
""".format(*[point_repr(x) for x in GRID.values()]) | |
if __name__ == '__main__': | |
current_player = True # 2 players: True or False | |
while True: | |
print(get_grid_repr()) | |
move = int(input("Select free a position: ")) | |
mark_player_move(current_player, move) | |
if check_winner(current_player): | |
print("Player {} has won!".format(point_repr(current_player))) | |
break | |
if check_game_over(): | |
print("Draw") | |
break | |
current_player = not current_player |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment