Created
February 23, 2018 21:13
-
-
Save rppowell-lasfs/500caa2e4b234aa4a3b6f43dd17ca7c8 to your computer and use it in GitHub Desktop.
Python Tic-Tac-Toe Game Example
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
import random | |
""" | |
A quick exercise in making a tic-tac-toe game in python 3 | |
""" | |
class Board: | |
def __init__(self): | |
self.newGame() | |
def newGame(self): | |
self.data = [' ' for i in range(9)] | |
self.currentPlayer = 'X' | |
def setData(self, x, y, d): | |
self.data[3*y+x] = d | |
def getData(self, x, y): | |
return self.data[3*y+x] | |
def drawBoard(self): | |
for y in range(3): | |
r = [] | |
for x in range(3): | |
r.append(self.data[y*3+x]) | |
print("|"+' '.join(r)+"|") | |
def checkState(self): | |
# check columns | |
for i in range(3): | |
if self.getData(i, 0) != ' ' and self.getData(i, 0) == self.getData(i, 1) and self.getData(i, 1) == self.getData(i, 2): | |
return self.getData(i, 0) | |
# check rows | |
for i in range(3): | |
if self.getData(0, i) != ' ' and self.getData(0, i) == self.getData(1, i) and self.getData(1, i) == self.getData(2, i): | |
return self.getData(0, i) | |
# check backslash | |
if self.getData(2, 0) != ' ' and self.getData(2, 0) == self.getData(1, 1) and self.getData(1, 1) == self.getData(0, 2): | |
return self.getData(0, 0) | |
# check backslash | |
if self.getData(0, 0) != ' ' and self.getData(0, 0) == self.getData(1, 1) and self.getData(1, 1) == self.getData(2, 2): | |
return self.getData(0, 0) | |
for i in self.data: | |
if i == ' ': | |
return i | |
return 'T' | |
def xyToPos(self, x, y): | |
return (3*y+x) | |
def posToXY(self, pos): | |
return ((pos%3,pos//3)) | |
def doTurn(self): | |
while True: | |
i = random.randint(0, 8) | |
if self.data[i] == ' ': | |
print(self.posToXY(i)) | |
self.data[i] = self.currentPlayer | |
self.currentPlayer = 'O' if self.currentPlayer == 'X' else 'X' | |
break | |
def run_match(): | |
done = False | |
board = Board() | |
board.drawBoard() | |
i = 0 | |
while True: | |
i += 1 | |
print("Round: " + str(i)) | |
board.doTurn() | |
board.drawBoard() | |
if board.checkState() != ' ': | |
print("Winner is: " + board.checkState()) | |
break | |
if __name__ == '__main__': | |
run_match() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment