forked from machinatoonist/prompt-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-tic-tac-toe.py
More file actions
147 lines (76 loc) · 2.45 KB
/
example-tic-tac-toe.py
File metadata and controls
147 lines (76 loc) · 2.45 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# Prompt: write a simple python script to enable two players to play a game of tic-tac-toe
# temperature: 0.5
# Code generated by ChatGPT often does not work as expected.
# This is because the model is trained on a large corpus of code,
# but the code generated is not always correct. This is a limitation of the model,
# and not a bug in the code.
# Need to add createBoard function
#!/usr/bin/env python
import sys
def main():
#create and initialize board
board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
#initialize player turn
turn = 'X'
#main game loop
while True:
#print board
printBoard(board)
#get player input
row, col = getPlayerInput(turn)
#update board
updateBoard(board, row, col, turn)
#check for winner
if checkForWinner(board, turn):
print (f'Player {turn}, wins!')
sys.exit(0)
#check for draw
if checkForDraw(board):
print ('It\'s a draw!')
sys.exit(0)
#switch turns
if turn == 'X':
turn = 'O'
else:
turn = 'X'
def printBoard(board):
print
for i in range(3):
for j in range(3):
sys.stdout.write(board[i][j])
if j != 2:
sys.stdout.write('|')
print
if i != 2:
print ('------')
print
def getPlayerInput(turn):
while True:
print (f'Player {turn} \'s turn.')
row = input('Enter row: ')
col = input('Enter col: ')
if row >= 0 and row <= 2 and col >= 0 and col <= 2 and board[row][col] == ' ':
return row, col
else:
print ('Invalid input. Please try again.')
def updateBoard(board, row, col, turn):
board[row][col] = turn
def checkForWinner(board, turn):
for i in range(3):
if board[i][0] == turn and board[i][1] == turn and board[i][2] == turn:
return True
if board[0][i] == turn and board[1][i] == turn and board[2][i] == turn:
return True
if board[0][0] == turn and board[1][1] == turn and board[2][2] == turn:
return True
if board[0][2] == turn and board[1][1] == turn and board[2][0] == turn:
return True
return False
def checkForDraw(board):
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
return False
return True
if __name__ == '__main__':
main()