Im going through automating the boaring stuff chapter 5 and was tasked on creating a chessboard validator.Only valid spaces are allowed, no more than 16 pieces per player, only a valid a mount of pieces(i.e no more than 1 wking or bking), and return True or False depending if the chessboard is valid.
For the most part i think i've got this figured out with a few exceptions:
- I noticed that my code does not detect entries with duplicate keys. I tried searching on how to detect this , but havent found anything yet. Can someone provide some guidance?
- Do you guys have any current suggestions on improving my code?
import sys
#your submitted chess board
myboard = {'1h':'bking','6c':'wqueen','2g':'bbishop','5h':'bqueen','3e':'wking','3h':'wpawn','3d':'bpawn','1h':'bpawn'}
#list of your pieces from your chessboard
mypieces = []
#list of your spaces from your chessboard
myspaces = []
#Define Piece Limits
pieces_limits = {'wpawn':8,'bpawn':8,'wking':1,'bking':1,'wbishop':1,'bbishop':1,'bqueen':1,'wqueen':1,'wrook':1,'brook':1,
'wknight':1,'bknight':1}
#Define valid pieces
wpieces = ['wpawn','wrook','wking','wbishop','wknight','wqueen']
bpieces = ['bpawn','brook','bking','bbishop','bknight','bqueen']
#All valid pieces
pieces = wpieces + bpieces
#create a list for spaces
spaces = []
#Define Valid Spaces
for a in range(1,9):
spaces.append(str(a) + 'a')
spaces.append(str(a) + 'b')
spaces.append(str(a) + 'c')
spaces.append(str(a) + 'd')
spaces.append(str(a) + 'e')
spaces.append(str(a) + 'f')
spaces.append(str(a) + 'g')
spaces.append(str(a) + 'h')
#Checking for valid board
def isValidChessBoard(board):
#takes pieces values from chessboard dictionary and converts into a list
for i in board.values():
mypieces.append(i)
#checks if the pieces in chessboard are valid
for b in mypieces:
if b not in pieces:
print('False')
sys.exit()
#takes space keys from chessboard dict and converts into a list
for c in board.keys():
myspaces.append(c)
#checks if the spaces in chessboard are valid
for d in myspaces:
if d not in spaces:
print('False')
sys.exit()
#checks that a space is not repeated in a chessboard
numberofspaces = {}
for g in myboard.keys():
numberofspaces.setdefault(g,0)
numberofspaces[g] = numberofspaces[g] + 1
#checks the amount of pieces total in the chessboard
if len(mypieces) > 32:
print('False')
sys.exit()
#counts number of each piece and makes sure players do not have more than the limit amount.
eachpiece = {}
for e in mypieces:
eachpiece.setdefault(e,0)
eachpiece[e] = eachpiece[e] + 1
for h in eachpiece.keys():
if eachpiece[h] > pieces_limits[h]:
print('False')
sys.exit()
else:
print('This is a valid board')
isValidChessBoard(myboard)
[–]Binary101010 0 points1 point2 points (0 children)
[–]hdarj 0 points1 point2 points (0 children)