-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoeBot.py
355 lines (283 loc) · 9.71 KB
/
tictactoeBot.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
from discord.ext import commands
from discord.client import log
import discord
import random
import asyncio
import logging
"""A bot capable of playing ticTacToe."""
description = """Python bot project by Florian Fasmeyer & Gabriel Grigri."""
bot = commands.Bot(command_prefix='!', description=description)
playPlayer1 = False
isPlaying = False
playVSPC = False
board = 0
player1Name = ''
player2Name = ''
player1Id = ''
player2Id = ''
player1 = ':x:'
player2 = ':o:'
# log.setLevel(logging.DEBUG)
# log.addHandler(logging.StreamHandler())
# logging.basicConfig(level=logging.INFO)
@bot.command(
description='Play TicTacToe against another player.',
pass_context=True)
async def play(ctx, *name2: str):
"""Play TicTacToe against another player."""
global isPlaying
global bot
global player1Name
global player1Id
global player2Id
global playPlayer1
global player2Name
player2Name = ''
messageDisplay = ''
if not isPlaying:
isPlaying = True
playPlayer1 = True
player1Name = ctx.message.author.name
player1Id = ctx.message.author.id
player2Id = ''
messageDisplay += f'\nÀ <@!{player1Id}> de jouer.'
messageDisplay += startGame()
if len(name2) > 0:
player2Name = name2[0]
else:
messageDisplay += '\nUne partie est en cours.'
await bot.say(messageDisplay)
@bot.command(
description='Play TicTacToe against the PC.',
pass_context=True)
async def playSolo(ctx):
"""Play TicTacToe against the PC."""
global isPlaying
global playPlayer1
global player1Id
global player1Name
global playVSPC
messageDisplay = ''
if not isPlaying:
isPlaying = True
playPlayer1 = True
player1Name = ctx.message.author.name
player1Id = ctx.message.author.id
playVSPC = True
messageDisplay += f'\nÀ <@!{player1Id}> de jouer.'
messageDisplay += startGame()
else:
messageDisplay += '\nUne partie est en cours.'
await bot.say(messageDisplay)
@bot.command(
description='Stop the current game.',
pass_context=True)
async def stop(ctx):
"""Stop the current game."""
global isPlaying
if isPlaying:
if (ctx.message.author.name == player1Name or
ctx.message.author.name == player2Name):
isPlaying = False
await bot.say('\nFin de la partie.')
else:
await bot.say('\nAucune partie en cours')
@bot.command(
pass_context=True,
description='Make a move on the TicTacToe board (after starting a game).')
async def move(ctx, *miniToe: int):
"""Make a move on the TicTacToe board (after starting a game)."""
global isPlaying
winner = False
global player1
global player2
global playPlayer1
global player1Name
global player2Name
global player1Id
global player2Id
global playVSPC
boardFull = False
messageDisplay = ''
if not isPlaying:
await bot.say("\nAucune partie en cours.")
return None
if len(miniToe) > 0 and isValid(miniToe[0]):
move = miniToe[0]
else:
await bot.say("\nEntrez un nombre de 1 à 9.")
return None
if not playVSPC:
if playPlayer1 and player1Name == ctx.message.author.name:
if movePlayer(board, player1, move):
if hasWon(board, player1):
messageDisplay += f'\n<@!{player1Id}> a gagné!'
winner = True
elif isBoardFull(board):
boardFull = True
messageDisplay += f'\nIl n\'y a pas de gagnant.'
else:
playPlayer1 = False
if player2Name != '':
if player2Id == '':
messageDisplay += f'\nÀ {player2Name} de jouer.'
else:
messageDisplay += f'\nÀ <@!{player2Id}> de jouer.'
else:
messageDisplay += '\nAu tour du deuxième joueur.'
messageDisplay += draw()
else:
getPlayer2Info(ctx.message.author.name, ctx.message.author.id)
if player2Name == ctx.message.author.name:
if player2Id == '':
player2Id = ctx.message.author.id
if movePlayer(board, player2, move):
if hasWon(board, player2):
messageDisplay += f'\n<@!{player2Id}> a gagné!'
winner = True
else:
if isBoardFull(board):
boardFull = True
messageDisplay += f'\nIl n\'y a pas de gagnant.'
else:
playPlayer1 = True
messageDisplay += f'\nÀ <@!{player1Id}> de jouer.'
messageDisplay += draw()
else:
if movePlayer(board, player1, move):
if hasWon(board, player1):
messageDisplay += f'\n<@!{player1Id}> a gagné!'
winner = True
else:
if isBoardFull(board):
boardFull = True
messageDisplay += f'\nIl n\'y a pas de gagnant.'
else:
# messageDisplay += '\nLe bot joue...'
moveBot = getMoveBot()
if movePlayer(board, player2, moveBot):
if hasWon(board, player2):
messageDisplay += "\nLe bot a gagné!"
winner = True
elif isBoardFull(board):
boardFull = True
messageDisplay += f'\nIl n\'y a pas de gagnant.'
else:
messageDisplay += f'\nÀ <@!{player1Id}> de jouer.'
messageDisplay += draw()
if winner or boardFull:
messageDisplay += '\nPartie terminée.'
isPlaying = False
playVSPC = False
if messageDisplay != '':
await bot.say(messageDisplay)
def getPlayer2Info(name, id):
"""Get info for player 2"""
global player2Name
global player2Id
if player2Name == '':
player2Name = name
player2Id = id
def isValid(move):
"""Return true if input within [1;9]."""
if move in {1, 2, 3, 4, 5, 6, 7, 8, 9}:
return True
return False
def getMoveBot():
"""Move from the bot."""
global player2
'''On test le move du bot sur une copy du board.
Si le moove fait du bot un gagnant, retourne ce move (i).
Sinon, test si le player peut gagner au prochain move,
et retourne ce dernier pour le contrer. Sinon, centre,
puis corners, puis random. IA reprise et modifiée du site
https://inventwithpython.com/chapter10.html.'''
for i in range(1, 10):
boardCopy = getBoardCopy(board)
if isSpaceFree(boardCopy, i):
if movePlayer(boardCopy, player2, i):
if hasWon(boardCopy, player2):
return i
for i in range(1, 10):
boardCopy = getBoardCopy(board)
if isSpaceFree(boardCopy, i):
if movePlayer(boardCopy, player1, i):
if hasWon(boardCopy, player1):
return i
# Centre
if isSpaceFree(board, 5):
return 5
# Corners
for i in range(1, 3, 2):
if isSpaceFree(board, i):
return i
for i in range(7, 9, 2):
if isSpaceFree(board, i):
return i
# Sinon, nombre random
i = random.randint(1, 9)
while not isSpaceFree(boardCopy, i):
i = i + 1
return i
def getBoardCopy(b):
""" Return a copy of the board, for local test"""
boardCopy = []
for i in b:
boardCopy.append(i)
return boardCopy
def movePlayer(b, player, move):
"""Place move on the board."""
if isValid(move) and (isSpaceFree(b, move)):
b[move] = player
return True
else:
return False
def hasWon(board, player):
'''Def the win condition'''
# any(all(x == player for x in board[i::3])
# for i in range(3)):
# any(all(x == player for x in board[i:i+3])
# for i in range(0, 9, 3))
# any(all(x == player for x in board[s])
# for s in (slice(0,9,4), slice(2,7,2)))
for i in range(1, 4):
# vérification des colonnes
if(
board[i] == board[(i+3)] and
board[i] == board[(i+6)] == player):
return True
# vérification des lignes
for i in range(1, 8, 3):
if(
board[i] == board[(i+1)] and
board[i] == board[(i+2)] == player):
return True
# vérification des diagonales
if(
board[1] == board[5] == player and board[5] == board[9] or
board[3] == board[5] == player and board[5] == board[7]):
return True
def initBoard():
"""Initialize the board"""
global board
board = [':white_medium_square:'] * 10
def isBoardFull(b):
"""Return true if the board is full."""
return not ':white_medium_square:' in b
def isSpaceFree(b, position):
"""Return true if the place you want to place your pawn on is free."""
return b[position] == ':white_medium_square:'
def draw():
"""Draw the board"""
result = ''
for i in range(1, 10):
if i % 3 == 0:
result += board[i] + '\n'
else:
result += board[i]
return '\n\n' + result
def startGame():
"""Start the game, randomly choose who will be first."""
initBoard()
return draw()
bot.run("MzE0NjYwOTMxMTIyNDk1NDg4.C_7aWg.gr69xOwZ54dBhSQ3y7cff89GsxQ")