Repository navigation
Expand file tree
/
Copy pathtic-tac-toe.py
More file actions
executable file
·102 lines (73 loc) · 2.17 KB
/
Copy pathtic-tac-toe.py
File metadata and controls
executable file
·102 lines (73 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Work with lists to create a tic tac toe.
The program has limited checks on dealing with errors.
You could add code to check for a winner or tie game.
Or you could add som intelligence to the computer move.
"""
def printGame(board):
"""
Print out the current game board.
"""
print("------- ")
print("|{}|{}|{}| (1,2,3)".format(board[0], board[1], board[2]))
print("|{}|{}|{}| (4,5,6)".format(board[3], board[4], board[5]))
print("|{}|{}|{}| (7,8,9)".format(board[6], board[7], board[8]))
print("------- ")
def isInt(s):
"""
Check that a string can be converted to a integer.
"""
try:
int(s)
return True
except ValueError:
return False
def place(board, what, where):
"""
Place a marker on the board.
"""
board[where] = what
def placeComputer(board):
"""
Place a marker on the board.
"""
for position, value in enumerate(board):
if value == " ":
return position
return False
def checkIfWinnerOrTie(board):
"""
Check if there is a winner or if there is a tie game.
"""
# pylint: disable=unused-argument
print("(Checking for winner or tie is not yet implemented)")
def main():
"""
Play a game of Tic Tac Toe.
"""
# Create a list of nine spaces
board = [" "] * 9
print("Play against the computer.")
print("You start, you are X. Computer is O.")
print("Three in a row wins.")
while 1:
printGame(board)
position = input("Enter position (1-9) to place you X (or q for quit): ")
if position == "q":
break
elif isInt(position):
# User move
place(board, "X", int(position) - 1)
# Computer move
computerPos = placeComputer(board)
if computerPos is not False:
place(board, "O", computerPos)
print("Computer moved to {}.".format(computerPos))
if checkIfWinnerOrTie(board) is True:
break
if __name__ == "__main__":
print(__doc__)
input("Press enter to continue.")
main()