forked from sharunrajeev/YourFirstContribution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtictactoe.py
More file actions
98 lines (97 loc) · 3.08 KB
/
tictactoe.py
File metadata and controls
98 lines (97 loc) · 3.08 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
board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return board[pos] == " "
def printBoard(board):
print(" " + board[1] + "| " + board[2] + "| " + board[3])
print("---------")
print(" " + board[4] + "| " + board[5] + "| " + board[6])
print("---------")
print(" " + board[7] + "| " + board[8] + "| " + board[9])
def isWinner(bo, le):
return ((bo[7] == le and bo[8] == le and bo[9] == le) or
(bo[4] == le and bo[5] == le and bo[6] == le) or
(bo[1] == le and bo[2] == le and bo[3] == le) or
(bo[1] == le and bo[4] == le and bo[7] == le) or
(bo[2] == le and bo[5] == le and bo[8] == le) or
(bo[3] == le and bo[6] == le and bo[9] == le) or
(bo[1] == le and bo[5] == le and bo[9] == le) or
(bo[3] == le and bo[5] == le and bo[7] == le))
def playMove():
run = True
while run:
move = input("Please select a position to place an 'X' (1-9): ")
try:
move = int(move)
if move > 0 and move < 10 :
if spaceIsFree(move):
run = False
insertLetter("x", move)
else:
print("Sorry this space is occupied")
else:
print("Please type the number within the range")
except:
print("Please type a number. ")
def compMove():
possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
move = 0
for let in ['o','x']:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
cornersOpen = []
for i in possibleMoves:
if i in [1,3,7,9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
if 5 in possibleMoves:
move = 5
return move
edgesOpen = []
for i in possibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0, ln)
return li[r]
def isBoardFull(board):
if board.count(" ") > 1:
return False
else:
return True
def main():
print("welcome tic tac toe")
printBoard(board)
while not(isBoardFull(board)):
if not(isWinner(board, "o")):
playMove()
printBoard(board)
else:
print("Sorry, O's won this time! ")
break
if not(isWinner(board, "x")):
move = compMove()
if move == 0:
print("Tie game")
else:
insertLetter("o", move)
print("Computer placed an 'o' in position", move, ":")
printBoard(board)
else:
print("X's won this time! Good job")
break
if isBoardFull(board):
print("Tie game")
main()