-
Notifications
You must be signed in to change notification settings - Fork 1
/
main03.py
105 lines (88 loc) · 2.63 KB
/
main03.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
'''
Chess Program vs computer
https://github.com/Dirk94/ChessAI
'''
import board, pieces, ai, boardControl
# Returns a move object based on the users input. Does not check if the move is valid.
def get_user_move():
print("Example Move: A2 A4")
move_str = input("Your Move: ")
move_str = move_str.replace(" ", "")
try:
xfrom = letter_to_xpos(move_str[0:1])
yfrom = 8 - int(move_str[1:2]) # The board is drawn "upside down", so flip the y coordinate.
xto = letter_to_xpos(move_str[2:3])
yto = 8 - int(move_str[3:4]) # The board is drawn "upside down", so flip the y coordinate.
return ai.Move(xfrom, yfrom, xto, yto, False)
except ValueError:
print("Invalid format. Example: A2 A4")
return get_user_move()
# Returns a valid move based on the users input.
def get_valid_user_move(board):
while True:
move = get_user_move()
valid = False
possible_moves = board.get_possible_moves(pieces.Piece.WHITE)
# No possible moves
if (not possible_moves):
return 0
for possible_move in possible_moves:
if (move.equals(possible_move)):
move.castling_move = possible_move.castling_move
valid = True
break
if (valid):
break
else:
print("Invalid move.")
return move
# Converts a letter (A-H) to the x position on the chess board.
def letter_to_xpos(letter):
letter = letter.upper()
if letter == 'A':
return 0
if letter == 'B':
return 1
if letter == 'C':
return 2
if letter == 'D':
return 3
if letter == 'E':
return 4
if letter == 'F':
return 5
if letter == 'G':
return 6
if letter == 'H':
return 7
raise ValueError("Invalid letter.")
#
# Entry point.
#
board = board.Board.new()
print(board.to_string())
turn = 0
while True:
move = get_valid_user_move(board)
if (move == 0):
if (board.is_check(pieces.Piece.WHITE)):
print("Checkmate. Black Wins.")
break
else:
print("Stalemate.")
break
board.perform_move_board(move,turn)
print("User move: " + move.to_string())
print(board.to_string())
ai_move = ai.AI.get_ai_move(board, [])
if (ai_move == 0):
if (board.is_check(pieces.Piece.BLACK)):
print("Checkmate. White wins.")
break
else:
print("Stalemate.")
break
board.perform_move_board(ai_move,turn)
print("AI move: " + ai_move.to_string())
print(board.to_string())
turn += 1