Sei sulla pagina 1di 4

Instantly share code, notes, and snippets.

rsheldiii / chess.py
Created 7 years ago

Embed <script src="https://gis Download ZIP

chess program for python

chess.py

1 """CONVENTIONS:
2 positions are done row-column from the bottom left and are both numbers. This corresponds to the alpha-number system in traditio
3 """
4 import itertools
5 WHITE = "white"
6 BLACK = "black"
7
8
9
10
11
12
13
14 class Game:
15 #ive decided since the number of pieces is capped but the type of pieces is not (pawn transformations), I've already coded m
16 def __init__(self):
17 self.playersturn = BLACK
18 self.message = "this is where prompts will go"
19 self.gameboard = {}
20 self.placePieces()
21 print("chess program. enter moves in algebraic notation separated by space")
22 self.main()
23
24
25 def placePieces(self):
26
27 for i in range(0,8):
28 self.gameboard[(i,1)] = Pawn(WHITE,uniDict[WHITE][Pawn],1)
29 self.gameboard[(i,6)] = Pawn(BLACK,uniDict[BLACK][Pawn],-1)
30
31 placers = [Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook]
32
33 for i in range(0,8):
34 self.gameboard[(i,0)] = placers[i](WHITE,uniDict[WHITE][placers[i]])
35 self.gameboard[((7-i),7)] = placers[i](BLACK,uniDict[BLACK][placers[i]])
36 placers.reverse()
37
38
39 def main(self):
40
41 while True:
42 self.printBoard()
43 print(self.message)
44 self.message = ""
45 startpos,endpos = self.parseInput()
46 try:
47 target = self.gameboard[startpos]
48 except:
49 self.message = "could not find piece; index probably out of range"
50 target = None
51
52 if target:
53 print("found "+str(target))
54 if target.Color != self.playersturn:
55 self.message = "you aren't allowed to move that piece this turn"
56 continue
57 if target.isValid(startpos,endpos,target.Color,self.gameboard):
58 self.message = "that is a valid move"
59 self.gameboard[endpos] = self.gameboard[startpos]
60 del self.gameboard[startpos]
61 self.isCheck()
62 if self.playersturn == BLACK:
63 self.playersturn = WHITE
64 else : self.playersturn = BLACK
65 else :
66 self.message = "invalid move" + str(target.availableMoves(startpos[0],startpos[1],self.gameboard))
67 print(target.availableMoves(startpos[0],startpos[1],self.gameboard))
68 else : self.message = "there is no piece in that space"
69
70 def isCheck(self):
71 #ascertain where the kings are, check all pieces of opposing color against those kings, then if either get hit, check if
72 king = King
73 kingDict = {}
74 pieceDict = {BLACK : [], WHITE : []}
75 for position,piece in self.gameboard.items():
76 if type(piece) == King:
77 kingDict[piece.Color] = position
78 print(piece)
79 pieceDict[piece.Color].append((piece,position))
80 #white
81 if self.canSeeKing(kingDict[WHITE],pieceDict[BLACK]):
82 self.message = "White player is in check"
83 if self.canSeeKing(kingDict[BLACK],pieceDict[WHITE]):
84 self.message = "Black player is in check"
85
86
87 def canSeeKing(self,kingpos,piecelist):
88 #checks if any pieces in piece list (which is an array of (piece,position) tuples) can see the king in kingpos
89 for piece,position in piecelist:
90 if piece.isValid(position,kingpos,piece.Color,self.gameboard):
91 return True
92
93 def parseInput(self):
94 try:
95 a,b = input().split()
96 a = ((ord(a[0])-97), int(a[1])-1)
97 b = (ord(b[0])-97, int(b[1])-1)
98 print(a,b)
99 return (a,b)
100 except:
101 print("error decoding input. please try again")
102 return((-1,-1),(-1,-1))
103
104 """def validateInput(self, *kargs):
105 for arg in kargs:
106 if type(arg[0]) is not type(1) or type(arg[1]) is not type(1):
107 return False
108 return True"""
109
110 def printBoard(self):
111 print(" 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |")
112 for i in range(0,8):
113 print("-"*32)
114 print(chr(i+97),end="|")
115 for j in range(0,8):
116 item = self.gameboard.get((i,j)," ")
117 print(str(item)+' |', end = " ")
118 print()
119 print("-"*32)
120
121
122
123 """game class. contains the following members and methods:
124 two arrays of pieces for each player
125 8x8 piece array with references to these pieces
126 a parse function, which turns the input from the user into a list of two tuples denoting start and end points
127 a checkmateExists function which checks if either players are in checkmate
128 a checkExists function which checks if either players are in check (woah, I just got that nonsequitur)
129 a main loop, which takes input, runs it through the parser, asks the piece if the move is valid, and moves the piece if it i
130 """
131
132 class Piece:
133
134 def __init__(self,color,name):
135 self.name = name
136 self.position = None
137 self.Color = color
138 def isValid(self,startpos,endpos,Color,gameboard):
139 if endpos in self.availableMoves(startpos[0],startpos[1],gameboard, Color = Color):
140 return True
141 return False
142 def __repr__(self):
143 return self.name
144
145 def __str__(self):
146 return self.name
147
148 def availableMoves(self,x,y,gameboard):
149 print("ERROR: no movement for base class")
150
151 def AdNauseum(self,x,y,gameboard, Color, intervals):
152 """repeats the given interval until another piece is run into.
153 if that piece is not of the same color, that square is added and
154 then the list is returned"""
155 answers = []
156 for xint,yint in intervals:
157 xtemp,ytemp = x+xint,y+yint
158 while self.isInBounds(xtemp,ytemp):
159 #print(str((xtemp,ytemp))+"is in bounds")
160
161 target = gameboard.get((xtemp,ytemp),None)
162 if target is None: answers.append((xtemp,ytemp))
163 elif target.Color != Color:
164 answers.append((xtemp,ytemp))
165 break
166 else:
167 break
168
169 xtemp,ytemp = xtemp + xint,ytemp + yint
170 return answers
171
172 def isInBounds(self,x,y):
173 "checks if a position is on the board"
174 if x >= 0 and x < 8 and y >= 0 and y < 8:
175 return True
176 return False
177
178 def noConflict(self,gameboard,initialColor,x,y):
179 "checks if a single position poses no conflict to the rules of chess"
180 if self.isInBounds(x,y) and (((x,y) not in gameboard) or gameboard[(x,y)].Color != initialColor) : return True
181 return False
182
183
184 chessCardinals = [(1,0),(0,1),(-1,0),(0,-1)]
185 chessDiagonals = [(1,1),(-1,1),(1,-1),(-1,-1)]
186
187 def knightList(x,y,int1,int2):
188 """sepcifically for the rook, permutes the values needed around a position for noConflict tests"""
189 return [(x+int1,y+int2),(x-int1,y+int2),(x+int1,y-int2),(x-int1,y-int2),(x+int2,y+int1),(x-int2,y+int1),(x+int2,y-int1),(x-i
190 def kingList(x,y):
191 return [(x+1,y),(x+1,y+1),(x+1,y-1),(x,y+1),(x,y-1),(x-1,y),(x-1,y+1),(x-1,y-1)]
192
193
194
195 class Knight(Piece):
196 def availableMoves(self,x,y,gameboard, Color = None):
197 if Color is None : Color = self.Color
198 return [(xx,yy) for xx,yy in knightList(x,y,2,1) if self.noConflict(gameboard, Color, xx, yy)]
199
200 class Rook(Piece):
201 def availableMoves(self,x,y,gameboard ,Color = None):
202 if Color is None : Color = self.Color
203 return self.AdNauseum(x, y, gameboard, Color, chessCardinals)
204
205 class Bishop(Piece):
206 def availableMoves(self,x,y,gameboard, Color = None):
207 if Color is None : Color = self.Color
208 return self.AdNauseum(x, y, gameboard, Color, chessDiagonals)
209
210 class Queen(Piece):
211 def availableMoves(self,x,y,gameboard, Color = None):
212 if Color is None : Color = self.Color
213 return self.AdNauseum(x, y, gameboard, Color, chessCardinals+chessDiagonals)
214
215 class King(Piece):
216 def availableMoves(self,x,y,gameboard, Color = None):
217 if Color is None : Color = self.Color
218 return [(xx,yy) for xx,yy in kingList(x,y) if self.noConflict(gameboard, Color, xx, yy)]
219
220 class Pawn(Piece):
221 def __init__(self,color,name,direction):
222 self.name = name
223 self.Color = color
224 #of course, the smallest piece is the hardest to code. direction should be either 1 or -1, should be -1 if the pawn is t
225 self.direction = direction
226 def availableMoves(self,x,y,gameboard, Color = None):
227 if Color is None : Color = self.Color
228 answers = []
229 if (x+1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x+1, y+self.direction) : answers.append((x+
230 if (x-1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x-1, y+self.direction) : answers.append((x-
231 if (x,y+self.direction) not in gameboard and Color == self.Color : answers.append((x,y+self.direction))# the condition a
232 return answers
233
234 uniDict = {WHITE : {Pawn : "♙", Rook : "♖", Knight : "♘", Bishop : "♗", King : "♔", Queen : "♕" }, BLACK : {Pawn : "♟", Rook :
235
236
237
238
239
240 Game()

d3mon1231 commented on 24 Nov 2017

pawn can moves two forward from their starting place. I dont think yours can

MichaelGitHubHype commented on 8 Dec 2017

Potrebbero piacerti anche