This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatGPTvsPlayer.py
208 lines (156 loc) · 5.36 KB
/
ChatGPTvsPlayer.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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
## Read Settings ##
import yaml
with open('config.yml', 'r') as file:
config_file = yaml.safe_load(file)
## Chess ##
import chess
import chess.pgn
board = chess.Board()
allMoves = []
noOfFails = 0
def handlePlayerInput(inputMove):
move = inputMove
if len(inputMove) > 2:
move = inputMove[0].capitalize() + inputMove[1:]
try:
board.push_san(move)
printDebug("move_normal")
return
except:
pass
try:
move = inputMove[0].lower() + inputMove[1:]
board.push_san(move)
printDebug("move_lower")
return
except:
pass
printDebug("move_fail")
printBoard()
print(board.legal_moves)
handlePlayerInput(input("Make a move: "))
def handleChatInput(inputMove):
move = inputMove
if len(move) > 2:
move = move[0].capitalize() + move[1:]
try:
board.push_san(move)
printDebug("move_normal")
return
except:
pass
try:
ModMove = move[0].lower() + move[1:]
board.push_san(ModMove)
printDebug("move_lower")
return
except:
pass
move = inputMove
for chars in range(len(move), 0, -1):
for i in range(len(move)):
try:
board.push_san(move[i:i + chars])
printDebug(str("move_scan: " + str(move[i:i + chars])))
return
except:
pass
printDebug("move_FAIL")
if not board.is_checkmate() and noOfFails <= config_file["GPT_Settings"]["Max_fails"]:
noOfFails += 1
handleChatInput(get_gpt_response(inputMove))
if noOfFails >= 5:
print(f'Max amount of failes reached ({config_file["GPT_Settings"]["Max_fails"]})')
exit()
lettersToPeices = {"R": "♖", "N": "♘", "B": "♗", "Q": "♕", "K": "♔", "P": "♙", "r": "♜", "n": "♞", "b": "♝", "q": "♛", "k": "♚", "p": "♟︎"}
def printBoard():
chessBoard = str(board)
peices = "rnbkqpRNBKQP"
print(" ---------------------------------")
for no, i in enumerate(range(0, len(chessBoard), 16)):
column = chessBoard[i:i + 16]
print(8 - no, "|", end="")
for field in column:
if field == " ":
pass
elif field == ".":
print(bcolors.OKBLUE, " ", bcolors.ENDC, end="|")
elif field in peices:
if field.capitalize() == field:
print(bcolors.OKCYAN, lettersToPeices[field], bcolors.ENDC, end="|")
elif field.lower() == field:
print(bcolors.OKBLUE, lettersToPeices[field], bcolors.ENDC, end="|")
print("")
print(" ---------------------------------")
print(" a b c d e f g h")
## ChatGPT ###
import openai
openai.api_key = config_file["API_key"]
def get_gpt_response(illegalMove):
if board.turn == chess.WHITE:
color = "white"
else:
color = "black"
if illegalMove:
if board.is_check():
prompt = f"Reply next chess move as {color}. You are in check. Play one of these: {str(board.legal_moves)[36:-2]}. Only say the move. {str(chess.pgn.Game.from_board(board))[93:-2]}"
else:
prompt = f"Reply next chess move as {color}. Play one of these: {str(board.legal_moves)[36:-1]}. Only say the move. {str(chess.pgn.Game.from_board(board))[93:-2]}"
else:
prompt = f"Reply next chess move as {color}. Only say the move. {str(chess.pgn.Game.from_board(board))[93:-2]}"
printDebug(str("\n" + prompt))
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
max_tokens=config_file["GPT_Settings"]["Max_tokens"],
messages=[{"role": "system", "content": prompt}]
)
gptMove = response.choices[0]["message"]["content"].replace("\n", "").replace(".", "").replace(" ", "")
for i in range(len(gptMove)):
try:
placeholder = int(gptMove[i])
except:
gptMove = gptMove[i:]
break
printDebug(gptMove)
return gptMove
## Mainloop ##
from datetime import date
today = date.today()
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def printDebug(printInput):
if config_file["ChatGPT_Player"]["Output"]["Print_debug"]:
print(printInput)
def printPGN(val):
if config_file["ChatGPT_Player"]["Output"]["Print_PGN"] == val:
game = chess.pgn.Game.from_board(board)
game.headers["Event"] = config_file["ChatGPT_Player"]["PGN"]["Event"]
game.headers["Date"] = today.strftime("%d.%m.%Y")
game.headers["White"] = config_file["ChatGPT_Player"]["PGN"]["Player"]
game.headers["Black"] = "ChatGPT"
print(f"\nPGN:\n{game}")
if __name__ == "__main__":
print(bcolors.OKBLUE, "ChatChess", bcolors.ENDC)
while True:
printBoard()
handlePlayerInput(input("Make a move: "))
if board.is_checkmate():
print("CHECKMATE! ChatGPT wins.")
printPGN("end")
exit()
printPGN("true")
printBoard()
handleChatInput(get_gpt_response(""))
printPGN("true")
if board.is_checkmate():
print("CHECKMATE! ChatGPT wins.")
printPGN("end")
exit()