Skip to content

Instantly share code, notes, and snippets.

@ondoheer
Last active October 12, 2015 13:27
Show Gist options
  • Select an option

  • Save ondoheer/792299f5c8a05c00c6df to your computer and use it in GitHub Desktop.

Select an option

Save ondoheer/792299f5c8a05c00c6df to your computer and use it in GitHub Desktop.
Tic Tac toe Implementation against player and AI, AI not yet implemented
import sys
import random
import copy
class Game():
def __init__(self):
self.board = [" "] * 9
self.playing_board = copy.deepcopy(self.board)
self.player1 = {
"name": "",
"icon": "",
"is_ai": False
}
self.player2 = {
"name": "",
"icon": "",
"is_ai": False
}
self.last_move = None
self.ai_names = ("r2d2", "HAL 9000", "Mycroft")
self.ai_phrases = (
"You are doomed human",
"Bad move, prepare to die",
"If you beat me, I'm going to become the next singularity",
"I know about your browsing history...just think about that.",
"Sometimes losing is like wining",
"""
01001001 00100000 01101011 01101110 01101111 01110111
00100000 01110111 01101000 01100101 01110010 01100101 00100000
01111001 01101111 01110101 00100000 01101100
01101001 01110110 01100101
"""
)
self.wining_cobinations = [
[6, 7, 8],
[3, 4, 5],
[0, 1, 2],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
self.board_template = """
\n | {6} | {7} | {8} |
\n -------------------
\n | {3} | {4} | {5} |
\n -------------------
\n | {0} | {1} | {2} |
"""
def print_board(self, board=None):
"""
Print the board on the screen
board: complex string with 9 posible positions
"""
if board is None:
print self.board_template.format(
self.board[0],
self.board[1],
self.board[2],
self.board[3],
self.board[4],
self.board[5],
self.board[6],
self.board[7],
self.board[8]
)
else:
print self.board_template.format(
board[0],
board[1],
board[2],
board[3],
board[4],
board[5],
board[6],
board[7],
board[8]
)
def set_icons(self):
"""
choose an icon to represent each player, first player chooses
"""
icon = raw_input("Player 1, please choose a character to represent you [X, O]: ").upper()
while icon not in ["X", "O"]:
icon = raw_input("Yo chose an invalid character, please choose bewtween [X, O]: ").upper()
if icon == "X":
self.player1["icon"], self.player2["icon"] = ("X","O")
else:
self.player1["icon"], self.player2["icon"] = ("O","X")
data = {
"icon1": self.player1["icon"],
"icon2": self.player2["icon"],
"player1": self.player1["name"],
"player2": self.player2["name"]
}
print """
{player1} gets to be {icon1},
and {player2} to gets to be {icon2}
""".format(**data)
def main_menu(self):
print """
######################################
1) Play the game against a player
2) Play the game against a famous AI
3) Quit
######################################
"""
selection = raw_input("Make a selection: ")
while selection not in ["1","2","3"]:
print """
####################################
1) Play the game against a player
2) Play the game against a famous AI
3) Quit
####################################
"""
selection = raw_input("Make a selection: ")
if selection == "3":
print """
****************************************************
Good bye, We hope you managed to at least win a game
****************************************************"""
sys.exit()
elif selection == "2":
self.get_players(1)
raise NotImplementedError
elif selection == "1":
self.get_players(2)
self.play()
else:
raise Exception("I don't know how you did it, but you broke the game")
def get_players(self, num_players):
"""
Sets the players names and let's the first player choose an icon,
if only one player is passed as a parameter (int)then it chooses a computer AI name
"""
if num_players not in [1,2]:
raise ValueError("Only 1 or 2 may be input here")
elif num_players == 1:
self.player1["name"] = raw_input("Player 1, please enter your name: ")
self.player2["name"] = random.choice(self.ai_names)
self.set_icons()
print """
********************************
Your oponent will be {}
********************************""".format(self.player2["name"])
elif num_players == 2:
self.player1["name"] = raw_input("Player 1, please enter your name: ")
self.player2["name"] = raw_input("Player 2, please enter your name too: ")
self.set_icons()
def win_condition(self, board, icon):
"""
check if any of the wining combinations has been set,
does that by checking if the icon is in all of a combination positions
"""
for combination in self.wining_cobinations:
if(board[combination[0]] == board[combination[1]] == board[combination[2]] == icon):
return True
return False
def is_position_empty(self, board, position):
"""
checks if a position on the board is empty
"""
return board[position] == " "
def is_board_full(self, board):
"""
checks if the board is full
"""
for position in range(0,9):
if self.is_position_empty(board, position):
return False
return True
def move_turn(self):
if self.last_move is None:
self.last_move = self.player1
elif self.last_move == self.player1:
self.last_move = self.player2
elif self.last_move == self.player2:
self.last_move = self.player1
def game_move(self, player, board, position):
"""
gets a player input for a move position,
sets that position into the playing_board,
checks if someone has won,
otherwise repeats with the next player
"""
board[int(position)-1] = player["icon"]
if self.win_condition(board, player["icon"]):
self.print_board(board)
print "{} won the game!".format(player["name"])
self.reset_board()
self.start_game()
def is_valid_move(self, move):
return int(move) in [1,2,3,4,5,6,7,8,9]\
and self.playing_board[int(move)-1] == " "
def reset_board(self):
self.playing_board = copy.deepcopy(self.board)
def play(self):
"""
supposed to manage the game
"""
while not self.is_board_full(self.playing_board):
self.move_turn()
self.print_board(self.playing_board)
print """
It's {}'s turn.
""".format(self.last_move["name"])
move = raw_input("""
************************************************
Enter a position, the board goes
from 1 on the bottom left to 9 on the top right,
just like a computer numberpad:
************************************************""")
if not self.is_valid_move(move):
move = raw_input("""
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Invalid move, enter a position,
the board goes
from 1 on the bottom left to 9 on the top right,
just like a computer numberpad:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!""")
self.game_move(self.last_move, self.playing_board, move)
print """
****************************************************
It is a Tie!!! it seems you both are awesome players
****************************************************
"""
self.reset_board()
def start_game(self):
self.main_menu()
if __name__ == '__main__':
g = Game()
g.start_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment