Skip to content

Instantly share code, notes, and snippets.

@SwartzCr
Last active April 12, 2016 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SwartzCr/0fab491f5cb171b35c6fc584bfc336d5 to your computer and use it in GitHub Desktop.
Save SwartzCr/0fab491f5cb171b35c6fc584bfc336d5 to your computer and use it in GitHub Desktop.
BOARD = ["|", "|", "\n-----\n", "|", "|", "\n-----\n", "|", "|", "\n"]
SYMBOLS = ["x", "o"]
def print_board(game_state, board):
out = ""
for i in range(9):
out += str(game_state[i])
out += board[i]
print out
def make_new_game():
return range(9)
def take_move(symbol, game_state):
while True:
try:
location = int(raw_input("{0} player, which place would you like to play? ".format(symbol)))
except (ValueError, TypeError) as e:
print "Sorry, please only type integers 0-8"
continue
if location not in range(9) or game_state[location] != location:
print "Sorry, that's not a space you can play in"
continue
return make_move(location, game_state, symbol)
def make_move(location, game_state, symbol):
game_state[location] = symbol
return game_state
def check_won(gs):
for tic, tac, toe in [(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4,6)]:
if gs[tic] == gs[tac] and gs[tac] == gs[toe]:
return True
return False
def congratulate(winner, moves):
if winner == "c":
print "Aww, it was a cat's game"
else:
print "Congratulations player {0}! You won on turn {1}!".format(winner, moves)
print "Here's what the final board state was:"
def play():
game_state = make_new_game()
winner = ""
moves = 0
announce_game()
while not winner:
symbol = SYMBOLS[moves%2]
moves += 1
print_board(game_state, BOARD)
take_move(symbol, game_state)
if check_won(game_state):
winner = symbol
elif moves > 8:
winner = "c"
congratulate(winner, moves)
print_board(game_state, BOARD)
return winner
def prompt_continue():
while True:
answer = raw_input("Would you like to play another game? y/n: ")
if answer.lower() == "y" or answer.lower() == "yes":
return True
elif answer.lower() == "n" or answer.lower() == "no":
return False
print "I'm sorry, I didn't understand that..."
def print_record(wins):
for key in sorted(wins.keys()):
if key == "c":
print "{0} games have ended in a tie".format(wins[key])
else:
print "Player {0} has won {1} games".format(key, wins[key])
def welcome():
print "Welcome to Tic-Tac-Toe 3000 - the newest in computer game technology"
def announce_game():
print "Yes! Let's play a game!"
def bid_adieu():
print "So sorry to see you go, play again sometime!"
def main():
wins = {"x": 0, "o": 0, "c": 0}
keep_playing = True
welcome()
while keep_playing:
winner = play()
wins[winner] += 1
print_record(wins)
keep_playing = prompt_continue()
bid_adieu()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment