노는게 제일 좋습니다.

틱택토 인공지능 버그 수정 본문

Python/기타 공부

틱택토 인공지능 버그 수정

노는게 제일 좋습니다. 2016. 2. 3. 19:31

틱택도 다음으로 베이글 게임(세자리 숫자 맞추기)을 만들다가 힘들어서 틱택토를 다시 꺼내서 컴퓨터와 놀았는데..

하다보니 이상한 점이 발견되었다. 분명 컴퓨터가 이길 수 있는데도, 이길 수 있는 자리에 돌을 놓지 않고.

반대로 내가 돌을 놓으면 이길 수 있는 자리를 컴퓨터가 막지 않았다.

내가 경우의 수를 덜 계산한 것이 문제였다.


인공지능이 자신이 돌을 놓을 위치를 고를 때, 아래 순서의 과정을 거친다.

1이 참이라면 2는 생략한다.


1. 내가 놓아서 이길 수 있는 자리가 있나? - - - [참] - - -> 그 자리를 놓을 자리 리스트에 등록

l

l

[ 거 짓 ]

l

l

2. 상대방이 놓으면 이기는 자리가 있나? - - - [참] - - -> 그 자리를 놓을 자리 리스트에 등록


여기서 1, 2 는 각자 이런 내용을 담고 있다. (대상으로 하는 리스트만 다르고, 내용은 완전히 같다.)

A. 가로를 검사한다.



아래 B,C도 A와 순서도 구조 동일함.

B. 세로를 검사한다.

C. 대각선을 검사한다.


바로 여기에서 문제가 발생한다.

나는 기존의 코드에서 가운데에 돌이 있는가? -> 그 주위에 돌이 또 하나 있는가?

식으로 적어두었다. 그렇기 때문에, 가운데에 돌이 없고 양 끝에 돌이 있을 때 문제가 발생한다.

그 예는 다음과 같다.




그래서, 다음과 같이 수정한다.

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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import random
import sys
import time
############################################################################
def introDisplay():
    print('틱택토(Tic Tac Toe)에 오신 것을 환영합니다!')
    
    while True:
        
        print('가이드를 보시려면 "1"을, 보지 않고 스킵하시려면 "2"를 입력해주세요')
        print('>> 입력 : ', end='')
        needGuide = input()
        if needGuide!='1' and needGuide!='2':
            print('[오류] 잘못 입력하셨습니다')
            continue
        elif needGuide =='1':
            break
        elif needGuide =='2':
            print('가이드를 건너뜁니다.')
            print()
            return
        
    print()
    print('                     [    게    임    가    이    드    ]')
    print('아무키나 누르시면 설명을 한 줄씩 출력합니다.')
    input()
    
    print('오목과 유사한 규칙을 가지고 있습니다. 다른점은 3X3판을 사용한다는 점 입니다.')
    input()
    
    print('그렇기 때문에 돌 5개가 아니라, 3개로 한 줄을 만들면 승리합니다.')
    input()
    
    print('이 게임에서는 컴퓨터와 대결을 펼치게 됩니다.')
    input()
    print('당신은 문자 O와 X중 하나를 골라 오목에서의 "돌"과 같이 사용합니다.')
    input()
    print('돌을 놓는 방법을 알려드리겠습니다. 키보드 우측 키패드 1~9를 사용합니다.')
    input()
    virtualGameScreen = ['''''''''' ,'' ,'' ,'''']
    print('게임판은 키패드의 모양과 유사하게 그려집니다. 다음 그림을 보십시오.')
    print('현재는 돌이 하나도 놓여있지 않은 상태입니다.')
    drawingGameScreen(virtualGameScreen)
    input()
    virtualGameScreen = ['7''8''9''4''5' , '6' ,'1' ,'2''3']
    drawingGameScreen(virtualGameScreen)
    print('각 칸에 숫자를 입력했습니다. 입력된 각 칸에는 돌이 하나씩 들어갑니다.')
    input()
    
    print('쓰여진 숫자는 위치를 지정할 때 사용합니다.')
    input()
    
    print('예를 들어, 5가 쓰인 자리에 돌을 놓아보겠습니다.')
    input()
    
    print('당신의 돌은 O로 지정하겠습니다. 컴퓨터의 돌은 X입니다.')
    input()
    
    virtualGameScreen = ['''''''''' ,'' ,'' ,'''']
    drawingGameScreen(virtualGameScreen)
    print('이 상태에서 키보드 오른쪽 키패드의 숫자중 5를 입력해보십시오.')
   
    while True:
        print('5를 입력하세요! : ',end='')
        temp = input()
        if temp=='5':
            break
        else:
            print('질못된 입력입니다.')
            continue
    virtualGameScreen = ['''''''''O' ,'X' ,'' ,'''']
    drawingGameScreen(virtualGameScreen)
    print('5를 입력함으로써 5번자리에 당신의 돌 "O"가 놓여졌습니다.')
    print('"X"는 컴퓨터가 당신의 순서가 끝나고, 컴퓨터 차례에 돌을 놓은 것입니다.')
    input()
    print('한 번 더 해보겠습니다. 이번에는 8을 입력해보세요.')
    
    while True:
        print('8 입력하세요! : ',end='')
        temp = input()
        if temp=='8':
            break
        else:
            print('질못된 입력입니다.')
            continue
    virtualGameScreen = ['''X''''''O' ,'X' ,'' ,'O''']
    drawingGameScreen(virtualGameScreen)
    print('8를 입력함으로써 8번자리에 당신의 돌 "O"가 놓여졌습니다.')
    print('만약 이 상태에서 2번자리에 또 당신이 O를 놓았다면 당신이 승리합니다.')
    input()
    print('하지만 컴퓨터가 이를 눈치채고 2번 자리에 자신의 돌 X를 놓아 버렸습니다.')
    input()
    print('이런식으로 경기할 수 있습니다. 그럼 즐거운 게임 되시길 바랍니다.')
    print('아무 키나 누르면 게임을 시작합니다.')
    input()
    return 0
############################################################################  
    
def choosePlayerMark():
    print('사용하실 문자를 고르세요.(영문자 X 또는 O 입력)')
    print('X : 선공')
    print('O : 후공')
    while True:
        print('입력 : ', end='')
        chosenMark = input().upper()
        if chosenMark != 'O' and chosenMark !='X' :
            print('[오류] 잘못 입력하셨습니다. 영문자 O 또는 X를 입력해주세요.')
            print('------------------------------------------------------------------------')
            continue
        elif chosenMark == 'O':
            print('O를 고르셨습니다. 컴퓨터가 먼저 공격합니다.')
            return 'O','X'
        elif chosenMark == 'X':
            print('X를 고르셨습니다. 당신이 컴퓨터보다 먼저 공격합니다.')
            return 'X','O'
        
############################################################################
def drawingGameScreen(screen):
    print()
    print()
    print('--------------------------------------------------------------------------------')
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('\t'+screen[6]+'\t'+'|'+'\t'+screen[7]+'\t'+'|'+'\t'+screen[8])
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('--------------------------------------------------------------------------------')
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('\t'+screen[3]+'\t'+'|'+'\t'+screen[4]+'\t'+'|'+'\t'+screen[5])
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('--------------------------------------------------------------------------------')
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('\t'+screen[0]+'\t'+'|'+'\t'+screen[1]+'\t'+'|'+'\t'+screen[2])
    print('\t'+'\t'+'|'+'\t'+'\t'+'|'+'\t')
    print('--------------------------------------------------------------------------------')
    print()
    print()
 
############################################################################
    
def putPlayerStone(screen,mark):
    print('당신의 차례입니다! 돌을 놓을 위치를 선택해주세요.')
    while True:
        print('>> 위치 지정 : ',end='')
        position = input()
        if position not in ['1''2''3''4''5' ,'6' ,'7' ,'8''9'] :
            print('[오류]잘못된 값이 입력되었습니다. 1부터 9까지 입력가능합니다.')
            continue
        if screen[int(position)-1!= '':
            print('이미 돌이 놓여있습니다. 다른 곳에 놓아주세요.')
            continue
        else :
            break
    
    screen[int(position)-1= mark
    print('당신은 '+position+'번 위치에 돌을 놓았습니다!')
    return position,screen
############################################################################
def putComputerStone(screen,playerMark,computerMark):
    print('컴퓨터의 차례입니다!')
    
    computer_willPut_here=[] #컴퓨터가 놓을 위치
    
    #플레이어가 돌을 놓은 위치를 확인
    didPut_player = [False, False, False, False, False, False, False, False, False]
    for i in range(0,9):
        if playerMark == screen[i]:
            didPut_player[i] = True
    ###################################################
    #                                                                                                  #
    #                              컴퓨터의  승리 가능여부 확인                            #
    #                                                                                                  #
    ###################################################
    #컴퓨터가 놓아서 승리할 수 있는 위치가 있는지 확인
    didPut_computer = [False, False, False, False, False, False, False, False, False]
    for i in range(0,9):
        if computerMark == screen[i]:
            didPut_computer[i] = True
    
   #컴퓨터의 돌이 가로로 2개 이상 놓였는지 확인
    garoIndex = 8
    while garoIndex >= 2:
        #한 쪽에 쏠려 놓인 경우
        if  didPut_computer[garoIndex-1]==True:#가운데
            if didPut_computer[garoIndex-1-1== True: #왼쪽
                computer_willPut_here.append(garoIndex-1+1)
            elif didPut_player[garoIndex-1+1== True: #오른쪽
                computer_willPut_here.append(garoIndex-1-1)
        ##양쪽에 놓인 경우
        elif didPut_computer[garoIndex-1-1== True and didPut_computer[garoIndex-1+1== True:
            computer_willPut_here.append(garoIndex-1)
        garoIndex -= 3
    
    #컴퓨터의 돌이 세로로 2개 이상 놓였는지 확인
    seroIndex = 4
    while seroIndex <= 6:
        # 한쪽에 쏠려 놓인경우.
        if didPut_computer[seroIndex-1== True: #가운데 돌이 놓인경우
            if didPut_computer[seroIndex-1+3== True: #위쪽에 돌이 놓인 경우
                computer_willPut_here.append(seroIndex-1-3)
            elif didPut_computer[seroIndex-1-3== True: #아래쪽에 돌이 놓인 경우
                computer_willPut_here.append(seroIndex-1+3)
        #양쪽에 놓인 경우
        elif didPut_computer[seroIndex-1+3== True and didPut_computer[seroIndex-1-3== True:
            computer_willPut_here.append(seroIndex-1)
        seroIndex += 1
        
    #컴퓨터의 돌이 대각선으로 2개 이상 놓였는지 확인
    if didPut_computer[5-1== True: #5번에 돌이 놓인경우
        if didPut_computer[7-1== True:
            computer_willPut_here.append(3-1)
        elif didPut_computer[3-1== True:
            computer_willPut_here.append(7-1)
        elif didPut_computer[9-1== True:
            computer_willPut_here.append(1-1)
        elif didPut_computer[1-1== True:
            computer_willPut_here.append(9-1)
    if didPut_computer[7-1== True and didPut_computer[3-1== True:
        computer_willPut_here.append(5-1)
    if didPut_computer[9-1== True and didPut_computer[1-1== True:
        computer_willPut_here.append(5-1)
    #컴퓨터가 돌을 놓을 자리 선택
    for i in range(0,len(computer_willPut_here)):
        if screen[computer_willPut_here[i]] == '' :
            screen[computer_willPut_here[i]] = computerMark
            print('컴퓨터가 '+str(computer_willPut_here[i]+1)+'번 위치에 돌을 놓았습니다!')
            return screen
        
    ###################################################
    #                                                                                                  #
    #                                     플레이어의 승리 막기                                #
    #                                                                                                  #
    ###################################################
    #플레이어의 돌이 가로로 2개 이상 놓였는지 확인
    garoIndex = 8
    while garoIndex >= 2:
        if didPut_player[garoIndex-1== True: #가운데 돌이 놓인경우
            if didPut_player[garoIndex-1-1== True: #왼쪽에 돌이 놓인 경우
                computer_willPut_here.append(garoIndex-1+1)
            elif didPut_player[garoIndex-1+1== True: #오른쪽에 돌이 놓인 경우
                computer_willPut_here.append(garoIndex-1-1)
        ##양쪽에 놓인 경우
        elif didPut_player[garoIndex-1-1== True and didPut_player[garoIndex-1+1== True:
            computer_willPut_here.append(garoIndex-1)
        garoIndex -= 3
    
    #플레이어의 돌이 세로로 2개 이상 놓였는지 확인
    seroIndex = 4
    while seroIndex <= 6:
        if didPut_player[seroIndex-1== True: #가운데 돌이 놓인경우
            if didPut_player[seroIndex-1+3== True: #위쪽에 돌이 놓인 경우
                computer_willPut_here.append(seroIndex-1-3)
            elif didPut_player[seroIndex-1-3== True: #아래쪽에 돌이 놓인 경우
                computer_willPut_here.append(seroIndex-1+3)
        #양쪽에 놓인 경우
        elif didPut_player[seroIndex-1+3== True and didPut_player[seroIndex-1-3== True:
            computer_willPut_here.append(seroIndex-1)
        seroIndex += 1
        
    #플레이어의 돌이 대각선으로 2개 이상 놓였는지 확인
    if didPut_player[5-1== True: #5번에 돌이 놓인경우
        if didPut_player[7-1== True:
            computer_willPut_here.append(3-1)
        elif didPut_player[3-1== True:
            computer_willPut_here.append(7-1)
        elif didPut_player[9-1== True:
            computer_willPut_here.append(1-1)
        elif didPut_player[1-1== True:
            computer_willPut_here.append(9-1)
    if didPut_player[7-1== True and didPut_player[3-1== True:
        computer_willPut_here.append(5-1)
    if didPut_player[9-1== True and didPut_player[1-1== True:
        computer_willPut_here.append(5-1)
 
   
    #돌을 놓을 자리 선택
    for i in range(0,len(computer_willPut_here)):
        if screen[computer_willPut_here[i]] == '' :
            screen[computer_willPut_here[i]] = computerMark
            print('컴퓨터가 '+str(computer_willPut_here[i]+1)+'번 위치에 돌을 놓았습니다!')
            return screen
    
    #놓을 자리를 못찾은 경우 랜덤하게 지정
    #if len(computer_willPut_here)==0:
    for i in range(0,9):
         if screen[i]=='':
            computer_willPut_here.append(i)
    available = []
    for i in range(0,len(computer_willPut_here)):
        if screen[computer_willPut_here[i]] == '' :
            available.append(computer_willPut_here[i])
    available = random.choice(available)
    screen[int(available)] = computerMark
    print('컴퓨터가 '+str(available+1)+'번 위치에 돌을 놓았습니다!')
    return screen
 
############################################################################
 
def checkWinner(screen,playerMark,computerMark):
    ###################################################
    #                                                                                                  #
    #                                     플레리어 승리 확인                                   #
    #                                                                                                  #
    ###################################################
    #플레이어가 돌을 놓은 위치를 확인
    playerPut = [False, False, False, False, False, False, False, False, False]
    for i in range(0,9):
        if playerMark == screen[i]:
            playerPut[i] = True
    #세로 확인
    seroIndex = 7
    while seroIndex<=9:
        if playerPut[seroIndex-1]==True and playerPut[seroIndex-1-3]==True and playerPut[seroIndex-1-6]==True :
            playerWin(screen)
            return True
        
        seroIndex+=1
    #가로 확인
    garoIndex = 7
    while garoIndex>=1:
        if playerPut[garoIndex-1]==True and playerPut[garoIndex-1+1]==True and playerPut[garoIndex-1+2]==True :
            playerWin(screen)
            return True
        
        garoIndex-=3
    #탄라로 확인
         #if 탄라로인가?:
            #print('글쿤')
    #대각선 확인
    if playerPut[7-1]==True and playerPut[5-1]==True and playerPut[3-1]==True :
        playerWin(screen)
        return True
    
    elif playerPut[9-1]==True and playerPut[5-1]==True and playerPut[1-1]==True :
        playerWin(screen)
        return True
    ###################################################
    #                                                                                                  #
    #                                     컴퓨터의  승리 확인                                  #
    #                                                                                                  #
    ###################################################
    #컴퓨터가 돌을 놓은 위치를 확인
    computerPut = [False, False, False, False, False, False, False, False, False]
    for i in range(0,9):
        if computerMark == screen[i]:
            computerPut[i] = True
    #세로 확인
    seroIndex = 7
    while seroIndex<=9:
        if computerPut[seroIndex-1]==True and computerPut[seroIndex-1-3]==True and computerPut[seroIndex-1-6]==True :
            comWin(screen)
            return True
        
        seroIndex+=1
    #가로 확인
    garoIndex = 7
    while garoIndex>=1:
        if computerPut[garoIndex-1]==True and computerPut[garoIndex-1+1]==True and computerPut[garoIndex-1+2]==True :
            comWin(screen)
            return True
        
        garoIndex-=3
    #대각선 확인
    if computerPut[7-1]==True and computerPut[5-1]==True and computerPut[3-1]==True :
        comWin(screen)
        return True
    
    elif computerPut[9-1]==True and computerPut[5-1]==True and computerPut[1-1]==True :
        comWin(screen)
        return True
    ###################################################
    #                                                                                                  #
    #                                         무승부 확인                                         #
    #                                                                                                  #
    ###################################################
    for i in range(0,9):
        if screen[i]=='':
            break
        elif i==8:
            drawingGameScreen(screen)
            print()
            print()
            print('************************************************')
            print()
            print('                                 앗! 무승부입니다!!                        ')
            print()
            print('************************************************')
            print()
            print()
            return True
def playerWin(gameScreen):
        drawingGameScreen(gameScreen)
        print()
        print()
        print('************************************************')
        print()
        print('                             플레이어가 승리했습니다!!                          ')
        print()
        print('************************************************')
        print()
        print()
def comWin(gameScreen):
        drawingGameScreen(gameScreen)
        print()
        print()
        print('************************************************')
        print()
        print('                                컴퓨터가 승리했습니다!!                              ')
        print()
        print('************************************************')
        print()
        print()
        
##############################################################################
def replayGuide():
    print('다시 플레이 하시겠습니까? (1.네   /  2.아니요)')
    print(' >> 입력 : ',end='')
    temp = input()
    while True:
          if temp == '1':
            print()
            print()
            print()
            print('새로운 게임을 시작합니다!')
            print()
            print()
            print()
            break
          elif temp == '2':
            print()
            print()
            print()
            print('즐거웠습니다! 잘가요!')
            print()
            print()
            print()
            sys.exit(0)
          else :
            print('잘못 입력하셨습니다. 1 또는 2를 입력해주세요')
            continue
 
    return True
 
####################################################################
####################################################################
####################################################################
####################################################################
 
while True:
    gameScreen = ['''''''''' ,'' ,'' ,''''# 순서대로 789456123
    introDisplay()
    playerMark, computerMark = choosePlayerMark()
    drawingGameScreen(gameScreen)
    
    if playerMark=='X':
        while True:
            putPlayerStone(gameScreen, playerMark)
            temp = checkWinner(gameScreen,playerMark,computerMark)
            if temp==True:
                if replayGuide()==True:
                    break
            drawingGameScreen(gameScreen)
            time.sleep(1)
            
            putComputerStone(gameScreen,playerMark,computerMark)
            temp = checkWinner(gameScreen,playerMark,computerMark)
            if temp==True:
                if replayGuide()==True:
                    break
            drawingGameScreen(gameScreen)
            time.sleep(1)
            
            
    elif playerMark=='O':
        while True:
            putComputerStone(gameScreen,playerMark,computerMark)
            temp = checkWinner(gameScreen,playerMark,computerMark)
            if temp==True:
                if replayGuide()==True:
                    break
            drawingGameScreen(gameScreen)
            time.sleep(1)
            
            putPlayerStone(gameScreen, playerMark)
            temp = checkWinner(gameScreen,playerMark,computerMark)
            if temp==True:
                if replayGuide()==True:
                    break
            drawingGameScreen(gameScreen)
            time.sleep(1)
            
         
 
 
cs




Comments