You are on page 1of 19

Chess Game

Chess is a match performed on the reverse ends of a table that contains 64 different color tiles.
Each contestant has sixteen parts: one emperor, two rooks, two bishops, two knights and eight
pawns. The game's objective is to scrutinize the other king. Chess rules are rules regulating the
play of chess (also called chess laws). While games ' precise roots are uncertain, contemporary
laws gave shape in the Middle Ages for the first time. Until the late 19th decade, when they
mainly achieved their present shape, the laws remained mildly changed. The laws were also
somewhat different everywhere. Chess is a two-player chessboard match and each person uses
sixteen parts of six. Each piece sort passes in a separate manner. The aim of the match is to
control the ruler of the opponent (threatening with unavoidable destruction). Games don't end in
checkmates; players often resign if they think they're going to win. In several respects, a match
can also finish in a stake.
Rules:
1. Setting the Chess Board:
The chessboard is designed at the start of the match so that the black (or light) color bar is
placed on the bottom-right. Then each chess piece is organized in the same manner. The
second row is full of pawns (or status). The rooks went to the corners then the knights,
the bishops followed and finally the king who always has his own fit (white in white,
black in black), and the king in the rest of the place.
2. To move Chess pieces:
Each of the six distinct parts goes separately. Pieces cannot pass through other parts and
can never pass into a circle with one of its own parts (even if the rider can fly over others
parts). They may, however, be shifted to replace the part of the opponent. Parts are
usually shifted to position where they are able to catch other parts, protect their own parts
in event they catch or regulate the significant squares of the match by falling on the
ground and exchanging them.
i. To move the King:

The king is one of the weakest and the most significant item. The King can only shift
one square up, down and diagonally in all directions. The king may never be in
control (where he can be caught). When another item attacks the king, it is called '
check. '
ii. To move the Queen:
The queen is the strongest part. As long as she doesn't pass through any piece of her
own, she can proceed in any one direct path-forward, reverse, sideways or diagonally.
And if the Queen catches an adversary's item her step has been over, as with all items.
Note how the White Queen catches the Black Queen and is compelled to relocate by
the Black King.
iii. To move Rook:

The rook may move as far as it wants, but only forward, backward, and to the sides.
The rooks are especially strong when they protect and work together.
iv. To move Bishop:

The bishop can migrate to the desired point, but diagonally only. Each bishop will
always remain in that color, and will start in one color (bright or gray). Bishops
operate together well because each other's weaknesses are covered up.
v. To move Knight:
Knights go very differently, two rows in one position and then one more moves at a
90-degree angle, just like the form of "L." The other parts are very distinct. Knights
are also the only pieces that can move over other pieces.
vi. To move Pawns:
Because pawns move and catch in various respects are uncommon: they run forward
but catch diagonally. Pawns can migrate one piece at a moment only, with the
exception of their first movement in two rows. Only one place in front of them can be
captured by pawns. You can never reverse or catch it. If there's another piece right
before a pawn he can't push near or catch it.
3. Some Special Rules:
Pawns have yet another unique capacity and if a pawn goes across the table, it can be a different
item of chess. Any aspect of a pawn can be endorsed. A common misunderstanding is that pawns
can only be replaced with a seized pawn. This doesn't happen. Usually a pawn becomes a king. It
is possible to promote pawns only. The last principle of pawns is called "in motion" which is "in
writing" in French. When a pawn moves two places on its first step and falls on the opposing
pawn's hand (through the capacity of the other pawn to catch it), that other pawn has the choice
of picking up the first pawn.
4. To find out the first move:
The participant always passes first with the black parts. Therefore, players usually decide
who is white by chance or luck, for example, by turning a coin on the other player or
having a player guess how colorful it is the hidden pawn.
5. Basic Chess Strategies:
i. Protect your King
ii. Don’t give pieces away
iii. Control the Centre of Chessboard
iv. Use all pieces
Development:
Let's discuss certain fundamental ideas to assist us build a straightforward AI game:
The code is written in Python and the Spyder (Anaconda) IDE has been used for compilation.
Following the Article ("Create AI for your own Board Game from the Scratch" (Ref:
https://towardsdatascience.com/create-your-own-board-game-with-powerful-ai-from scratch-
part-1-5dcb028002b8).), the code which we have written is not based on the built -in components
that the Python library provides us. We have used following classes and functions:
1. Class Game:
In the Class GAME, we have following functions:
i. Init:
Here is the function INIT that contains initialization for the objects used in the
game to have a start.
Now move on the next function that is:
ii. Place Pieces

Place Pieces Function has been used for placing the above-mentioned pieces
(King, Queen, Knight, Bishop and Pawn) on the Chess Board so we could have a
visual experience like in our real life to carry on this game.
iii. Main

The main function is entry point of the whole program, it calls functions. Main is responsible for
checking general conditions for valid and invalid movements or turns.
iv. Evaluate:

It evaluates the positions of KINGS in the chess board.


v. Can Seeking and Parse the Input:

It looks for the pieces that seek to move and the other function is responsible for parsing the
input in such a way that is understandable for the source code in order to take action on that
command.
vi. Print Chess Board:

It Prints the Chess board as:


As seen in the IPython Console, the chess board has been created using print board function.
2. Class Piece:
We have following functions in the class named ‘Piece’:

i. The Init function is used for initialization purpose, IsValid function checks for the
valid moves that can be made at a specific position with a specific piece. A function
definition has been added to the class Piece named ‘availableMoves’ but it has not
been used there as the declaration f this function has been added to the concrete
classes of class piece.
ii. Move:
The move function is one of the fundamental functions of the game’s code.
It is responsible for checking the indices means the intended positions of the pieces if the
intended position exists in out bounds or not. It appends the indices in the current position of the
piece and make a valid move.
iii. Check Bound and Conflicts:

These two functions are responsible for checking validity of the bounds and conflicts for the
movement of pieces and have been called by other functions for utility.
3. Class Knight:
All of the above shown classes are representation of chess pieces as a valid, unique object in the
game having some constraints according which it can move.
Similarly, other pieces have classes like:

At the end of the code we have defined and declared the chess pieces objects and assigned them
a symbol by which are known as a whole. It helps implementing a visually pleasant game and
interface.
Further refinements of the game can be done following the next articles of the same thread. It
may include:
 Search Tree using MiniMax:
We'll generate a search tree then that allows the algorithm to select the finest movement.
The Minimax engine is used to do this. This algorithm examines the recursive tree in a
specified range of all feasible movements and evaluates the place at the end of the tree's
leaves. We return to the parent node, depending on whether it's a white or a black
movement, the smallest or biggest value of the children. (In other words, we attempt to
minimize or enhance each amount of results.)

Figure 1: A visualization of the minimax algorithm in an artificial position. The best move for
white is b2-c3, because we can guarantee that we can get to a position where the evaluation is
-50
The efficacy of the minimax algorithm is strongly dependent on the query scope. In the next
phase, we will enhance this.
 Alpha Beta Pruning:
Alpha-beta pruning is a minimax optimization process that enables some nodes in the search
tree to be ignored. This enables us to deepen the minimum search tree and use the same
funds. The alpha-beta pruning is focused on a scenario where a search tree portion can be
stopped if a change is found that contributes to a worse scenario than an old step. Alpha-
beta tapping has no effect on the results of the minimum machine— it only increases speed.

Conclusion:
Even the power of a simple algorithm of chess play is that it makes no foolish errors. That said,
strategic knowledge is still lacking. We could program a chess-playing algorithm with the
techniques I presented here, which can perform fundamental chess.
References:
 "Create AI for your own Board Game from the Scratch" (Ref:
https://towardsdatascience.com/create-your-own-board-game-with-powerful-ai-from
scratch-part-1-5dcb028002b8).
 Salen, K., Tekinbaş, K.S. and Zimmerman, E., 2004. Rules of play: Game design
fundamentals. MIT press.
 Basevi, L., 1985. Instructional chess game. U.S. Patent 4,515,371.
 Phillips, D., 2010. Python 3 Object Oriented Programming. Packt Publishing Ltd.
 Kanchibail, R., Suryaprakash, S. and Jagadish, S., 2016. Chess board recognition. Not
published in journal.

Source Code:

# -*- coding: utf-8 -*-


"""

Created on Sat Aug 24 01:33:36 2019

@author:

WHITE = "white"

BLACK = "black"

class Game:

def __init__(self):

self.playersturn = BLACK

self.message = "the game begins here"

self.gameboard = {}

self.placePieces()

self.main()

def placePieces(self):

for i in range(0,8):

self.gameboard[(i,1)] = Pawn(WHITE,uniDict[WHITE][Pawn],1)

self.gameboard[(i,6)] = Pawn(BLACK,uniDict[BLACK][Pawn],-1)

placers = [Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook]

for i in range(0,8):

self.gameboard[(i,0)] = placers[i](WHITE,uniDict[WHITE][placers[i]])

self.gameboard[((7-i),7)] = placers[i](BLACK,uniDict[BLACK][placers[i]])

placers.reverse()
def main(self):

while True:

self.printBoard()

print(self.message)

self.message = ""

startpos,endpos = self.parseInput()

try:

target = self.gameboard[startpos]

except:

self.message = "The piece you are looking for is unreachable or you wanted to go out
of the bound or index"

target = None

if target:

print("found "+str(target))

if target.Color != self.playersturn:

self.message = "Sorry! it's not permitted to move piece or take your turn right now"

continue

if target.isValid(startpos,endpos,target.Color,self.gameboard):

self.message = "Congratulations! for this Valid move and turn"

self.gameboard[endpos] = self.gameboard[startpos]
del self.gameboard[startpos]

self.Evaluate()

if self.playersturn == BLACK:

self.playersturn = WHITE

else : self.playersturn = BLACK

else :

self.message = "invalid move" +


str(target.availableMoves(startpos[0],startpos[1],self.gameboard))

print(target.availableMoves(startpos[0],startpos[1],self.gameboard))

else : self.message = "No piece here"

def Evaluate(self):

kingDict = {}

pieceDict = {BLACK : [], WHITE : []}

for place,piece in self.gameboard.items():

if type(piece) == King:

kingDict[piece.Color] = place

print(piece)

pieceDict[piece.Color].append((piece,place))

#white

if self.canSeeKing(kingDict[WHITE],pieceDict[BLACK]):

self.message = "White player"

if self.canSeeKing(kingDict[BLACK],pieceDict[WHITE]):
self.message = "Black player"

def canSeeKing(self,kingpos,piecelist):

for piece,place in piecelist:

if piece.isValid(place,kingpos,piece.Color,self.gameboard):

return True

def parseInput(self):

try:

a,b = input().split()

a = ((ord(a[0])-97), int(a[1])-1)

b = (ord(b[0])-97, int(b[1])-1)

print(a,b)

return (a,b)

except:

print("error decoding input. please try again")

return((-1,-1),(-1,-1))

def printBoard(self):

print(" 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |")

for i in range(0,8):
print("-"*32)

print(chr(i+97),end="|")

for j in range(0,8):

item = self.gameboard.get((i,j)," ")

print(str(item)+' |', end = " ")

print()

print("-"*32)

class Piece:

def __init__(self,color,name):

self.name = name

self.place = None

self.Color = color

def isValid(self,startpos,endpos,Color,gameboard):

if endpos in self.availableMoves(startpos[0],startpos[1],gameboard, Color = Color):

return True

return False

def __repr__(self):

return self.name

def __str__(self):
return self.name

def availableMoves(self,x,y,gameboard):

print("ERROR: no movement for base class")

def Move(self,x,y,gameboard, Color, intervals):

"""repeats the given interval until another piece is run into.

if that piece is not of the same color, that square is added and

then the list is returned"""

answers = []

for xint,yint in intervals:

xtemp,ytemp = x+xint,y+yint

while self.CheckBounds(xtemp,ytemp):

target = gameboard.get((xtemp,ytemp),None)

if target is None: answers.append((xtemp,ytemp))

elif target.Color != Color:

answers.append((xtemp,ytemp))

break

else:

break

xtemp,ytemp = xtemp + xint,ytemp + yint


return answers

def CheckBounds(self,x,y):

"checks if a place is on the board"

if x >= 0 and x < 8 and y >= 0 and y < 8:

return True

return False

def noConflict(self,gameboard,initialColor,x,y):

"checks if a single place poses no conflict to the rules of chess"

if self.CheckBounds(x,y) and (((x,y) not in gameboard) or gameboard[(x,y)].Color !=


initialColor) : return True

return False

chessCardinals = [(1,0),(0,1),(-1,0),(0,-1)]

chessDiagonals = [(1,1),(-1,1),(1,-1),(-1,-1)]

def knightList(x,y,int1,int2):

"""sepcifically for the rook, permutes the values needed around a place for noConflict tests"""

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-int2,y-int1)]

def kingList(x,y):
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)]

class Knight(Piece):

def availableMoves(self,x,y,gameboard, Color = None):

if Color is None : Color = self.Color

return [(xx,yy) for xx,yy in knightList(x,y,2,1) if self.noConflict(gameboard, Color, xx, yy)]

class Rook(Piece):

def availableMoves(self,x,y,gameboard ,Color = None):

if Color is None : Color = self.Color

return self.Move(x, y, gameboard, Color, chessCardinals)

class Bishop(Piece):

def availableMoves(self,x,y,gameboard, Color = None):

if Color is None : Color = self.Color

return self.Move(x, y, gameboard, Color, chessDiagonals)

class Queen(Piece):

def availableMoves(self,x,y,gameboard, Color = None):

if Color is None : Color = self.Color

return self.Move(x, y, gameboard, Color, chessCardinals+chessDiagonals)

class King(Piece):

def availableMoves(self,x,y,gameboard, Color = None):

if Color is None : Color = self.Color

return [(xx,yy) for xx,yy in kingList(x,y) if self.noConflict(gameboard, Color, xx, yy)]

class Pawn(Piece):
def __init__(self,color,name,direction):

self.name = name

self.Color = color

self.direction = direction

def availableMoves(self,x,y,gameboard, Color = None):

if Color is None : Color = self.Color

answers = []

if (x+1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x+1,


y+self.direction) : answers.append((x+1,y+self.direction))

if (x-1,y+self.direction) in gameboard and self.noConflict(gameboard, Color, x-1,


y+self.direction) : answers.append((x-1,y+self.direction))

if (x,y+self.direction) not in gameboard and Color == self.Color :


answers.append((x,y+self.direction))

return answers

uniDict = {WHITE : {Pawn : "♙", Rook : "♖", Knight : "♘", Bishop : "♗", King : "♔",
Queen : "♕" }, BLACK : {Pawn : "♟", Rook : "♜", Knight : "♞", Bishop : "♝", King : "♚",
Queen : "♛" }}

Game()

You might also like