Skip to content

Instantly share code, notes, and snippets.

@BensonMuriithi
Created August 8, 2016 10:13
Show Gist options
  • Save BensonMuriithi/4244bf851ad504ae6e6f95ad4ac048ac to your computer and use it in GitHub Desktop.
Save BensonMuriithi/4244bf851ad504ae6e6f95ad4ac048ac to your computer and use it in GitHub Desktop.
My solution (tictactoeengine.py) for 'Tic Tac Toe Game' exercise on practicepython.org -> http://www.practicepython.org/exercise/2016/08/03/28-tic-tac-toe-game.html
"""Functions for printing a TicTacToe gameboard to the console
The gameboard should be represented as a 2 dimensional list of 3 rows and 3 columns
"""
element_process = lambda i: ("X" if i == 1 else ("O" if i == 2 else " "))
def printboard(board):
print "\n game = [%s]\n" % ",\n\t ".join(["[%s]" % ", ".join(map(element_process, board[i])) for i in xrange(3)])
"""Determine the winner of any of a game of tic tac toe
The results of the play woll be provided to the program as a
2 dimensional array of 3 lists which will contain numbers
indicating the mark on that spot on the board.
1 will represent play by player 1
2 represent play by player 2
0 inicates a blank cell
"""
def determine_winner(board):
"""Returns 0 if there's no winner, 1 or 2 if there's a winnner
As 1 and 2 represent plays by player 1 and player 2 respectively,
1 or 2 is returned if either player wins.
"""
#check forward diagonal
if board[0][0] == board[1][1] == board[2][2]:
return board[0][0]
#check backward diagonal
elif board[0][2] == board[1][1] == board[2][0]:
return board[0][2]
#check verticals
for i in xrange(3):
if board[0][i] == board[1][i] == board[2][i]:
return board[0][i]
#check horizontals last as they are least likely to win
for i in xrange(3):
if board[i][0] and (board[i][0] == board[i][1] == board[i][2]):
return board[i][0]
return 0
if __name__ == "__main__":
testboard = [[1,2,2], [2,2,0], [2,1,1]]
winner = determine_winner(testboard)
if winner:
print "Player %d won." % winner
else:
print "Draw!"
"""Game engine for Tic Tac Toe game.
These functions only initialise and organise the game as well as keep the scores
of players
"""
from tictactoeplay import play_game
def play():
"""Handle the initialising of games and keeping score"""
Player1wins = Player2wins = games = 0
do_play = raw_input("Do you wish to play a game of Tic Tac Toe? (y/n) : ").lower()
if "y" in do_play:
while 1:
games += 1
winner = play_game()
if winner:
if winner == 1:Player1wins += 1
elif winner == 2: Player2wins += 1
print "\nPlayer %d wins.\n" % winner
else: print "\nDraw!\n"
print "\tGames Played\tPlayer 1 wins\tPlayer 2 wins\n\t %d\t %d \t%d" % (games, Player1wins, Player2wins)
again = raw_input("\nWould you like to play again? (y/n) : ").lower()
if "y" in again:
continue
else: break
if __name__ == "__main__":
play()
"""A basic tictactoe game to be played from the console
Input of the game will be entered as coordinates of the form (x,y)
where x is the row and y the column and they are both numbers
with a minimum number of 1 and a maximum of 3
"""
import tictactoecheck as gamechecker
import gameboardtoscreen as gameprinter
def introduceplayers():
"""Prints a text file that contains introductory information about the game.
Information in the file includes instructions on how to play the game."""
with open("gameintro.txt", 'r') as f:
print f.read()
def get_playermove(player):
"""Processes return it as a tuple of coordinates.
If the input is invalid in any way that will affect the game
The player is notified and the function repeats recursively"""
rr = raw_input("\nPlayer %d >> " % player)
move = rr.split(",")
try:
#if coordinates were actually entered
if len(move) != 2:
move = rr.split()
if len(move) != 2:
raise ValueError
x, y = int(move[0]), int(move[1])
#the coordinates be within range
if all((0 < x < 4, 0 < y < 4)):
return (x, y)
else:
print "\nThe first column or row is 1 and the final is 3"
print "Please re-enter correctly."
return get_playermove(player)
except ValueError:
#if coordinates not entered or not integers
print "Please enter only the row and column as numbers separated by a comma eg(1, 1)"
return get_playermove(player)
def play_game():
"""Handle playing of Tic Tac Toe game"""
introduceplayers()
#just for fun
board = [[0 for j in xrange(3)] for i in xrange(3)]
free_slots = 9
a, b = 1, 2
winner = 0
while free_slots and not winner:
playermove = get_playermove(a)
while board[playermove[0]-1][playermove[1]-1]:
#prevent playing a move that's already played
print "\nThat move has already been played. Please play another."
playermove = get_playermove(a)
board[playermove[0]-1][playermove[1]-1] = a
free_slots -= 1
a, b = b, a
#print the game to the screen
gameprinter.printboard(board)
if (9 - free_slots) >= 5:
#minimum number of moves that can be made for any player to win is 5
#so start checking for a winner after 5 moves
winner = gamechecker.determine_winner(board)
return winner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment