-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoe.py
97 lines (80 loc) · 2.8 KB
/
tictactoe.py
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
#!/bin/python3
# initial source:
# https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874
# The above steps through how to write this and what each section is doing
# really well and I am very grateful to James Shah and Byte Code for sharing it.
import sys
theBoard = {'7':' ' , '8':' ' , '9':' ' ,
'4':' ' , '5':' ' , '6':' ' ,
'1':' ' , '2':' ' , '3':' ' }
board_keys = []
def printBoard(board):
j=7
i=0
while i < 3:
print(board[str(j-(i*3))] + '|' + board[str(j-(i*3)+1)] + '|' + board[str(j-(i*3)+2)])
if i<2:
print('-+-+-')
i+=1
def checkWin(startPoint):
i=0
while i < 3:
if theBoard[str(startPoint-(i*3))] == theBoard[str(startPoint-(i*3)+1)] == theBoard[str(startPoint-(i*3)+2)] != ' ':
return True
if theBoard[str(startPoint+i)] == theBoard[str((startPoint+i)-3)] == theBoard[str((startPoint+i)-6)] != ' ':
return True
i += 1
if theBoard[str(startPoint)] == theBoard[str(startPoint-2)] == theBoard[str(startPoint-4)] != ' ':
return True
if theBoard[str(startPoint+2)] == theBoard[str(startPoint-2)] == theBoard[str(startPoint-6)] != ' ':
return True
def game():
turn = 'X'
count = 0
for i in range(10):
printBoard(theBoard)
print("It's your turn," + turn + ". Move to which place?")
move = input()
if move.isdigit():
if int(move)>9 or int(move)<1:
print("That position doesn't exits.\nMove to which place?")
continue
elif theBoard[move] == ' ':
theBoard[move] = turn
count += 1
else:
print("That place is already filled.\nMove to which place?")
continue
else:
print("We only accept numbers.\nPlease enter a number between 1 and 9.")
continue
# Now we check if player X or player O has won, for every move after 5 moves
if count >= 5:
if checkWin(7):
printBoard(theBoard)
print("\nGame Over.\n")
print(" *** " + turn + " won. *** ")
break
# If neither X nor O win:
if count == 9:
print("\nGame Over.\n")
print("It's a tie!!\n")
restart()
# we change the player
if turn == 'X':
turn = 'O'
else:
turn = 'X'
for key in theBoard:
board_keys.append(key)
restart()
def restart():
restart = input("Do you want to play again? (y/n)")
if restart == "y" or restart == "Y":
for key in board_keys:
theBoard[key] = " "
game()
else:
sys.exit("Game no longer continued.")
if __name__ == "__main__":
game()