forked from arvimal/100DaysofCode-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtic-tac-toe.py
More file actions
83 lines (69 loc) · 2.25 KB
/
tic-tac-toe.py
File metadata and controls
83 lines (69 loc) · 2.25 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
#!/usr/bin/env python3
# Generate a tic-tac-toe board using dicts.
theBoard = {
"top-L": " ",
"top-M": " ",
"top-R": " ",
"mid-L": " ",
"mid-M": " ",
"mid-R": " ",
"low-L": " ",
"low-M": " ",
"low-R": " ",
}
"""
theBoard = [
{"top-L": " ", "top-M": " ", "top-R": " "},
{"mid-L": " ", "mid-M": " ", "mid-R": " ", },
{"low-L": " ", "low-M": " ", "low-R": " "}
]
"""
def printBoard(board):
"""Print the latest state"""
print("\n - TIC TAC TOE - ")
print("\n")
print("\t{}".format("-" * 9))
print("\t{} | {} | {}".format(board["top-L"], board["top-M"], board["top-R"]))
print("\t{}".format("-" * 9))
print("\t{} | {} | {}".format(board["mid-L"], board["mid-M"], board["mid-R"]))
print("\t{}".format("-" * 9))
print("\t{} | {} | {}".format(board["low-L"], board["low-M"], board["low-R"]))
print("\t{}".format("-" * 9))
print("\n")
def check_win(theBoard):
"""
Check for a win
"""
vals = ["X", "O"]
# import pdb
# pdb.set_trace()
for i in vals:
if (theBoard["top-L"] and theBoard["top-M"] and theBoard["top-R"]) is i:
print("Player {} is the new Winner".format(i))
elif (theBoard["mid-L"] and theBoard["mid-M"] and theBoard["mid-R"]) is i:
print("Player {} is the new Winner".format(i))
elif (theBoard["low-L"] and theBoard["low-M"] and theBoard["low-R"]) is i:
print("Player {} is the new Winner".format(i))
else:
pass
def play_loop():
player = "X"
for i in range(9):
printBoard(theBoard)
move_location = input("Player ** {} **, enter location: ".format(player))
if move_location not in theBoard.keys():
print(" \nLocation {} not valid. Try again!".format(move_location))
play_loop()
# Set the move location to the user's input.
theBoard[move_location] = player
# Check if we've met a win condition
check_win(theBoard)
if player == "X":
player = "O"
else:
player = "X"
printBoard(theBoard)
if __name__ == "__main__":
# There are two players in tic-tac-toe, "X" and "O".
# Both the player and their move is denoted by "X" and "O".
play_loop()