Text Graphic Game

체스 AI by Python

YunSeong 2022. 9. 10. 19:30
728x90
반응형

1. Set Board 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# set board
board = [['R''N''B''K''Q''B''N''R'],
         ['P''P''P''P''P''P''P''P']]
for _ in range(4) :
    board.append(['.''.''.''.''.''.''.''.'])
board.append(['p''p''p''p''p''p''p''p'])
board.append(['r''n''b''k''q''b''n''r'])
 
U_pieces = [] 
L_pieces = []
for c in range(C) :
    for r in range(R) :
        if board[c][r].islower() :
            L_pieces.append((c, r))
        if board[c][r].isupper() :
            U_pieces.append((c, r))
cs

게임 판을 세팅한다. 

또한 list에 말들의 좌표값을 저장한다.

 


2. Movable Tile 

 

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
# check possible tile 
dc_n = [22-2-211-1-1]
dr_n = [1-11-12-22-2]
 
dc_k = [11100-1-1-1]
dr_k = [10-11-110-1]
 
dc_b = [11-1-1]
dr_b = [1-11-1]
 
dc_r = [1-100]
dr_r = [001-1]
 
dc_q = dc_k[:]
dr_q = dr_k[:]
 
def possible_tile(c, r) :
    piece_type = board[c][r].lower()
    is_lower = board[c][r].islower()
    if piece_type == 'p' :
        return possible_tile_p(c, r, is_lower)
    elif piece_type == 'b' :
        return possible_tile_b(c, r, is_lower)
    elif piece_type == 'n' :
        return possible_tile_n(c, r, is_lower)
    elif piece_type == 'r' :
        return possible_tile_r(c, r, is_lower)
    elif piece_type == 'q' :
        return possible_tile_q(c, r, is_lower)
    elif piece_type == 'k' :
        return possible_tile_k(c, r, is_lower)
 
def possible_tile_p(c, r, is_lower) :
    direction_c = 0
    if is_lower :
        direction_c = -1
    else :
        direction_c = 1
    result = []
    if 0<=c+direction_c<C : 
        if board[c+direction_c][r] == '.' :
            result.append((c+direction_c, r))
            if 0<=c+direction_c*2<and c == int(3.5+direction_c*-1.5) :
                if board[c+direction_c*2][r] == '.' :
                    result.append((c+direction_c*2, r))
        if 0<=r+1<R :
            if board[c+direction_c][r+1].isalpha() and is_lower != board[c+direction_c][r+1].islower() :
                result.append((c+direction_c, r+1))
        if 0<=r-1<R :
            if board[c+direction_c][r-1].isalpha() and is_lower != board[c+direction_c][r-1].islower() :
                result.append((c+direction_c, r-1))
   
    return result
 
def possible_tile_b(c, r, is_lower) :
    result = []
    for i in range(4) :
        dc = dc_b[i]
        dr = dr_b[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc 
            xr += dr
    return result
 
def possible_tile_r(c, r, is_lower) :
    result = []
    for i in range(4) :
        dc = dc_r[i]
        dr = dr_r[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc
            xr += dr
    return result
 
def possible_tile_k(c, r, is_lower) :
    result = []
    for i in range(8) :
        xc = c + dc_k[i]
        xr = r + dr_k[i]
        if 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
    return result
 
def possible_tile_n(c, r, is_lower) :
    result = []
    for i in range(8) :
        xc = c + dc_n[i]
        xr = r + dr_n[i]
        if 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
    return result
 
def possible_tile_q(c, r, is_lower) :
    result = []
    for i in range(8) :
        dc = dc_q[i]
        dr = dr_q[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc 
            xr += dr
    return result
cs

이동가능한 타일을 반환 시켜주는 함수를 정한다.


3. Move piece

 

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
# move piece
 
def move_piece(nc, nr, xc, xr) :
    global score
    if board[nc][nr].isupper() :
 
 
        U_pieces.remove((nc, nr))
        U_pieces.append((xc, xr))
    else : 
        L_pieces.remove((nc, nr))
        L_pieces.append((xc, xr))
 
    temp = board[xc][xr]
    board[xc][xr] = board[nc][nr]
    board[nc][nr] = '.'
       
 
    if temp.isalpha() :
        if temp.isupper() :
            score -= score_a[temp.lower()]
            U_pieces.remove((xc, xr))
        else :
            score += score_a[temp]
            L_pieces.remove((xc, xr))
    return temp
cs

체스 말을 움직이는 함수를 정의한다. 

말을 움직이면서 말 좌표가 담긴 list도 최신화 하고 

AI를 위한 score에도 결과를 반영해준다.


4. AI part

 

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
# AI part
 
def make_decision(n, AIturn, return_type) :  
    global score
    global U_pieces
    global L_pieces
    if n == 0 :
        return score
    else :
        if AIturn :
            max_score = -1000000
            best_decision = []
            for c, r in U_pieces[:] :
                possible_tile_list = possible_tile(c, r)
 
                for xc, xr in possible_tile_list :
                    t_score = score
                    t_U_pieces = U_pieces[:]
                    t_L_pieces = L_pieces[:]
                    temp = move_piece(c, r, xc, xr)
                    n_score = make_decision(n-1False2)
                    if max_score < n_score :
                        max_score = n_score
                        best_decision = [c, r, xc, xr]
                    board[c][r] = board[xc][xr]
                    board[xc][xr] = temp
                    U_pieces = t_U_pieces[:]
                    L_pieces = t_L_pieces[:]
                    score = t_score
            if return_type == 1 :
                return best_decision
            elif return_type == 2 :
                return max_score
        else :
            min_score = 1000000
            best_decision = []
            for c, r in L_pieces[:] :
                possible_tile_list = possible_tile(c, r)
 
                for xc, xr in possible_tile_list :
                    t_score = score
                    t_U_pieces = U_pieces[:]
                    t_L_pieces = L_pieces[:]
                    temp = move_piece(c, r, xc, xr)
                    n_score = make_decision(n-1True2)
                    if min_score > n_score :
                        min_score = n_score
                        best_decision = [c, r, xc, xr]
                    board[c][r] = board[xc][xr]    
                    board[xc][xr] = temp
                    U_pieces = t_U_pieces[:]
                    L_pieces = t_L_pieces[:]
                    score = t_score
            return min_score
cs

minimax algorithm을 사용해서 재귀적으로 함수를 짜준다.

또한 alpha-beta pruning을 사용해서 상대적으로 속도를 빠르게 한다.


5. Main part and Show board part

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# show board 
def print_board() :
    print()
    print('   0 1 2 3 4 5 6 7')
    for c in range(C) :
        sys.stdout.write(' '+str(c))
        for r in range(R) :
            sys.stdout.write(' '+board[c][r])
        print()
 
# main
print_board()
while (True) :
    while (True) :
        nc, nr, xc, xr = map(int, sys.stdin.readline().split())
        if (xc, xr) in possible_tile(nc, nr) :
            move_piece(nc, nr, xc, xr)
            print_board()
            break
    
    nc, nr, xc, xr = make_decision(5True0)
    move_piece(nc, nr, xc, xr)
    print_board()
cs


6. 결과

 

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
import sys
 
= 8
= 8
 
# define score
score_a = {'p' : 1'n' : 3'b' : 3'r' : 5'q' : 9'k' : 10000'.' : 0}
score = 0
 
# set board
board = [['R''N''B''K''Q''B''N''R'],
         ['P''P''P''P''P''P''P''P']]
for _ in range(4) :
    board.append(['.''.''.''.''.''.''.''.'])
board.append(['p''p''p''p''p''p''p''p'])
board.append(['r''n''b''k''q''b''n''r'])
 
 
# check possible tile 
dc_n = [22-2-211-1-1]
dr_n = [1-11-12-22-2]
 
dc_k = [11100-1-1-1]
dr_k = [10-11-110-1]
 
dc_b = [11-1-1]
dr_b = [1-11-1]
 
dc_r = [1-100]
dr_r = [001-1]
 
dc_q = dc_k[:]
dr_q = dr_k[:]
 
def possible_tile(c, r) :
    piece_type = board[c][r].lower()
    is_lower = board[c][r].islower()
    if piece_type == 'p' :
        return possible_tile_p(c, r, is_lower)
    elif piece_type == 'b' :
        return possible_tile_b(c, r, is_lower)
    elif piece_type == 'n' :
        return possible_tile_n(c, r, is_lower)
    elif piece_type == 'r' :
        return possible_tile_r(c, r, is_lower)
    elif piece_type == 'q' :
        return possible_tile_q(c, r, is_lower)
    elif piece_type == 'k' :
        return possible_tile_k(c, r, is_lower)
 
def possible_tile_p(c, r, is_lower) :
    direction_c = 0
    if is_lower :
        direction_c = -1
    else :
        direction_c = 1
    result = []
    if 0<=c+direction_c<C : 
        if board[c+direction_c][r] == '.' :
            result.append((c+direction_c, r))
            if 0<=c+direction_c*2<and c == int(3.5+direction_c*-1.5) :
                if board[c+direction_c*2][r] == '.' :
                    result.append((c+direction_c*2, r))
        if 0<=r+1<R :
            if board[c+direction_c][r+1].isalpha() and is_lower != board[c+direction_c][r+1].islower() :
                result.append((c+direction_c, r+1))
        if 0<=r-1<R :
            if board[c+direction_c][r-1].isalpha() and is_lower != board[c+direction_c][r-1].islower() :
                result.append((c+direction_c, r-1))
   
    return result
 
def possible_tile_b(c, r, is_lower) :
    result = []
    for i in range(4) :
        dc = dc_b[i]
        dr = dr_b[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc 
            xr += dr
    return result
 
def possible_tile_r(c, r, is_lower) :
    result = []
    for i in range(4) :
        dc = dc_r[i]
        dr = dr_r[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc
            xr += dr
    return result
 
def possible_tile_k(c, r, is_lower) :
    result = []
    for i in range(8) :
        xc = c + dc_k[i]
        xr = r + dr_k[i]
        if 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
    return result
 
def possible_tile_n(c, r, is_lower) :
    result = []
    for i in range(8) :
        xc = c + dc_n[i]
        xr = r + dr_n[i]
        if 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
    return result
 
def possible_tile_q(c, r, is_lower) :
    result = []
    for i in range(8) :
        dc = dc_q[i]
        dr = dr_q[i]
        xc = c + dc
        xr = r + dr
        while 0<=xc<and 0<=xr<and (board[xc][xr] == '.' or (board[xc][xr].isalpha and is_lower != board[xc][xr].islower())) :
            result.append((xc, xr))
            if board[xc][xr].isalpha :
                break
            xc += dc 
            xr += dr
    return result
 
U_pieces = []
L_pieces = []
for c in range(C) :
    for r in range(R) :
        if board[c][r].islower() :
            L_pieces.append((c, r))
        if board[c][r].isupper() :
            U_pieces.append((c, r))
 
# move piece
 
def move_piece(nc, nr, xc, xr) :
    global score
    if board[nc][nr].isupper() :
 
 
        U_pieces.remove((nc, nr))
        U_pieces.append((xc, xr))
    else : 
        L_pieces.remove((nc, nr))
        L_pieces.append((xc, xr))
 
    temp = board[xc][xr]
    board[xc][xr] = board[nc][nr]
    board[nc][nr] = '.'
       
 
    if temp.isalpha() :
        if temp.isupper() :
            score -= score_a[temp.lower()]
            U_pieces.remove((xc, xr))
        else :
            score += score_a[temp]
            L_pieces.remove((xc, xr))
    return temp
 
 
# show board 
 
def print_board() :
    print()
    print('   0 1 2 3 4 5 6 7')
    for c in range(C) :
        sys.stdout.write(' '+str(c))
        for r in range(R) :
            sys.stdout.write(' '+board[c][r])
        print()
 
 
# AI part
 
def make_decision(n, AIturn, return_type) :  
    global score
    global U_pieces
    global L_pieces
    if n == 0 :
        return score
    else :
        if AIturn :
            max_score = -1000000
            best_decision = []
            for c, r in U_pieces[:] :
                possible_tile_list = possible_tile(c, r)
 
                for xc, xr in possible_tile_list :
                    t_score = score
                    t_U_pieces = U_pieces[:]
                    t_L_pieces = L_pieces[:]
                    temp = move_piece(c, r, xc, xr)
                    n_score = make_decision(n-1False2)
                    if max_score < n_score :
                        max_score = n_score
                        best_decision = [c, r, xc, xr]
                    board[c][r] = board[xc][xr]
                    board[xc][xr] = temp
                    U_pieces = t_U_pieces[:]
                    L_pieces = t_L_pieces[:]
                    score = t_score
            if return_type == 1 :
                return best_decision
            elif return_type == 2 :
                return max_score
        else :
            min_score = 1000000
            best_decision = []
            for c, r in L_pieces[:] :
                possible_tile_list = possible_tile(c, r)
 
                for xc, xr in possible_tile_list :
                    t_score = score
                    t_U_pieces = U_pieces[:]
                    t_L_pieces = L_pieces[:]
                    temp = move_piece(c, r, xc, xr)
                    n_score = make_decision(n-1True2)
                    if min_score > n_score :
                        min_score = n_score
                        best_decision = [c, r, xc, xr]
                    board[c][r] = board[xc][xr]    
                    board[xc][xr] = temp
                    U_pieces = t_U_pieces[:]
                    L_pieces = t_L_pieces[:]
                    score = t_score
            return min_score
 
 
# main
print_board()
while (True) :
    while (True) :
        nc, nr, xc, xr = map(int, sys.stdin.readline().split())
        if (xc, xr) in possible_tile(nc, nr) :
            move_piece(nc, nr, xc, xr)
            print_board()
            break
    
    nc, nr, xc, xr = make_decision(5True0)
    move_piece(nc, nr, xc, xr)
    print_board()
 
cs

modular programming에 익숙하지가 않아서 그냥 코드를 짰는데 지저분하고 별로다 더 깔끔한 코드를 위해 노력해야할 듯하다.

또한 minimax algorithm에서 깊이를 짝수로 하니 AI가 바보가 되던데 이유를 모르겠다.

728x90
반응형

'Text Graphic Game' 카테고리의 다른 글

테트리스 by C 언어  (0) 2021.11.02
지뢰찾기 by Python  (0) 2021.07.24