Exemplo n.º 1
0
	def __init__(self, lvl, board, color):
		self.lvl = lvl
		self.board = board
		self.color = color
		self.Rules = ChessRules()
		self.tree = self.createNodeLevel(self.board, self.color, 0, None)
		self.optime = -1
		self.nextmove = chessMove()
Exemplo n.º 2
0
	def __init__(self,options):
		if options.debug:
			self.Board = ChessBoard(2)
			self.debugMode = True
		else:
			self.Board = ChessBoard(0)#0 for normal board setup; see ChessBoard class for other options (for testing purposes)
			self.debugMode = False

		self.Rules = ChessRules()
Exemplo n.º 3
0
    def __init__(self, options):
        if options.debug:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                6
            )  #6 for Checkmate with knights setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()
Exemplo n.º 4
0
    def __init__(self, options):
        if options.debug:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                7
            )  #7 for Bishops Checkmate setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()
Exemplo n.º 5
0
        def __init__(self,graphicStyle=1):
                os.environ['SDL_VIDEO_CENTERED'] = '1' #should center pygame window on the screen
                self.Rules = ChessRules()
                pygame.init()
                pygame.display.init()
                self.screen = pygame.display.set_mode((850,500))
                self.boardStart_x = 50
                self.boardStart_y = 50
                pygame.display.set_caption('Python Chess')

                self.textBox = ScrollingTextBox(self.screen,525,825,50,450)
                self.LoadImages(graphicStyle)
                #pygame.font.init() - should be already called by pygame.init()
                self.fontDefault = pygame.font.Font( None, 20 )
Exemplo n.º 6
0
class ChessAI:
    def __init__(self, name, color):
        #print "In ChessAI __init__"
        self.name = name
        self.color = color
        self.type = 'AI'
        self.Rules = ChessRules()

    def GetName(self):
        return self.name

    def GetColor(self):
        return self.color

    def GetType(self):
        return self.type

    def GetMyPiecesWithLegalMoves(self, board):
        #get list of my pieces
        myPieces = []
        for row in range(8):
            for col in range(8):
                piece = board.squares[row][col]
                if 'w' in piece:
                    if len(
                            list(
                                self.Rules.GetListOfValidMoves(
                                    board, (row, col)))) > 0:
                        myPieces.append((row, col))

        return myPieces
Exemplo n.º 7
0
class ChessAI():
	def __init__(self,name,color):
		self.name = name
		self.color = color
		self.type = 'AI'
		self.Rules = ChessRules()
		
	def GetName(self):
		return self.name
		
	def GetColor(self):
		return self.color
		
	def GetType(self):
		return self.type
		
	def GetMove(self,board,color):
		if color == "black":
			myColor = 'b'
			enemyColor = 'w'
		else:
			myColor = 'w'
			enemyColor = 'b'
		
		myPieces = []
		for row in range(8):
			for col in range(8):
				piece = board[row][col]
				if myColor in piece:
					if len(self.Rules.GetListOfValidMoves(board,color,(row,col))) > 0:
						myPieces.append((row,col))		
		
		fromTuple = myPieces[random.randint(0,len(myPieces)-1)]
		legalMoves = self.Rules.GetListOfValidMoves(board,color,fromTuple)
		toTuple = legalMoves[random.randint(0,len(legalMoves)-1)]
		
		moveTuple = (fromTuple,toTuple)
		return moveTuple
Exemplo n.º 8
0
class PythonChessMain:
    def __init__(self, options):
        if options.debug:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                6
            )  #6 for Checkmate with knights setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()

    def SetUp(self, options):
        #gameSetupParams: Player 1 and 2 Name, Color, Human/AI level
        if self.debugMode:
            player1Name = 'Kasparov'
            player1Type = 'human'
            player1Color = 'white'
            player2Name = 'Light Blue'
            player2Type = 'randomAI'
            player2Color = 'black'
        else:
            GameParams = TkinterGameSetupParams()
            (player1Name, player1Color, player1Type, player2Name, player2Color,
             player2Type) = GameParams.GetGameSetupParams()

        self.player = [0, 0]
        if player1Type == 'human':
            self.player[0] = ChessPlayer(player1Name, player1Color)
        elif player1Type == 'randomAI':
            self.player[0] = ChessAI_random(player1Name, player1Color)
        elif player1Type == 'defenseAI':
            self.player[0] = ChessAI_defense(player1Name, player1Color)
        elif player1Type == 'offenseAI':
            self.player[0] = ChessAI_offense(player1Name, player1Color)

        if player2Type == 'human':
            self.player[1] = ChessPlayer(player2Name, player2Color)
        elif player2Type == 'randomAI':
            self.player[1] = ChessAI_random(player2Name, player2Color)
        elif player2Type == 'defenseAI':
            self.player[1] = ChessAI_defense(player2Name, player2Color)
        elif player2Type == 'offenseAI':
            self.player[1] = ChessAI_offense(player2Name, player2Color)

        if 'AI' in self.player[0].GetType() and 'AI' in self.player[1].GetType(
        ):
            self.AIvsAI = True
        else:
            self.AIvsAI = False

        if options.pauseSeconds > 0:
            self.AIpause = True
            self.AIpauseSeconds = int(options.pauseSeconds)
        else:
            self.AIpause = False

        #create the gui object - didn't do earlier because pygame conflicts with any gui manager (Tkinter, WxPython...)
        if options.text:
            self.guitype = 'text'
            self.Gui = ChessGUI_text()
        else:
            self.guitype = 'pygame'
            if options.old:
                self.Gui = ChessGUI_pygame(0)
            else:
                self.Gui = ChessGUI_pygame(1)

    def MainLoop(self):
        currentPlayerIndex = 0
        turnCount = 0
        while not self.Rules.IsCheckmate(
                self.Board.GetState(), self.player[currentPlayerIndex].color):
            board = self.Board.GetState()
            currentColor = self.player[currentPlayerIndex].GetColor()
            #hardcoded so that player 1 is always white
            if currentColor == 'white':
                turnCount = turnCount + 1
            self.Gui.PrintMessage("")
            baseMsg = "TURN %s - %s (%s)" % (
                str(turnCount), self.player[currentPlayerIndex].GetName(),
                currentColor)
            self.Gui.PrintMessage("-----%s-----" % baseMsg)
            self.Gui.Draw(board)
            if self.Rules.IsInCheck(board, currentColor):
                self.Gui.PrintMessage(
                    "Warning..." + self.player[currentPlayerIndex].GetName() +
                    " (" + self.player[currentPlayerIndex].GetColor() +
                    ") is in check!")

            if self.player[currentPlayerIndex].GetType() == 'AI':
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor)
            else:
                moveTuple = self.Gui.GetPlayerInput(board, currentColor)
            moveReport = self.Board.MovePiece(
                moveTuple
            )  #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            self.Gui.PrintMessage(moveReport)
            currentPlayerIndex = (
                currentPlayerIndex + 1
            ) % 2  #this will cause the currentPlayerIndex to toggle between 1 and 0
            if self.AIvsAI and self.AIpause:
                time.sleep(self.AIpauseSeconds)

        self.Gui.PrintMessage("CHECKMATE!")
        winnerIndex = (currentPlayerIndex + 1) % 2
        self.Gui.PrintMessage(self.player[winnerIndex].GetName() + " (" +
                              self.player[winnerIndex].GetColor() +
                              ") won the game!")
        self.Gui.EndGame(board)
Exemplo n.º 9
0
class ChessBoard():
  _chessBoard = [
    [Pieces.BLACK_CASTLE, Pieces.BLACK_KNIGHT, Pieces.BLACK_BISHOP,
      Pieces.BLACK_QUEEN, Pieces.BLACK_KING, Pieces.BLACK_BISHOP,
      Pieces.BLACK_KNIGHT, Pieces.BLACK_CASTLE],
    [Pieces.BLACK_PAWN, Pieces.BLACK_PAWN, Pieces.BLACK_PAWN,
      Pieces.BLACK_PAWN, Pieces.BLACK_PAWN, Pieces.BLACK_PAWN,
      Pieces.BLACK_PAWN, Pieces.BLACK_PAWN],
    [None, None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None, None],
    [None, None, None, None, None, None, None, None],
    [Pieces.WHITE_PAWN, Pieces.WHITE_PAWN, Pieces.WHITE_PAWN,
      Pieces.WHITE_PAWN, Pieces.WHITE_PAWN, Pieces.WHITE_PAWN,
      Pieces.WHITE_PAWN, Pieces.WHITE_PAWN],
    [Pieces.WHITE_CASTLE, Pieces.WHITE_KNIGHT, Pieces.WHITE_BISHOP,
      Pieces.WHITE_QUEEN, Pieces.WHITE_KING, Pieces.WHITE_BISHOP,
      Pieces.WHITE_KNIGHT, Pieces.WHITE_CASTLE]
  ]
  _rules = ChessRules(_chessBoard)

  _pieceDir = "images/pieces"
  _whiteDir = _pieceDir + "/default-white"
  _blackDir = _pieceDir + "/default-black"
  _images = {
    Pieces.WHITE_PAWN: pygame.image.load(resourcePath(_whiteDir + "/pawn.png")),
    Pieces.WHITE_KNIGHT: pygame.image.load(resourcePath(_whiteDir + "/knight.png")),
    Pieces.WHITE_BISHOP: pygame.image.load(resourcePath(_whiteDir + "/bishop.png")),
    Pieces.WHITE_CASTLE: pygame.image.load(resourcePath(_whiteDir + "/castle.png")),
    Pieces.WHITE_QUEEN: pygame.image.load(resourcePath(_whiteDir + "/queen.png")),
    Pieces.WHITE_KING: pygame.image.load(resourcePath(_whiteDir + "/king.png")),
    Pieces.BLACK_PAWN: pygame.image.load(resourcePath(_blackDir + "/pawn.png")),
    Pieces.BLACK_KNIGHT: pygame.image.load(resourcePath(_blackDir + "/knight.png")),
    Pieces.BLACK_BISHOP: pygame.image.load(resourcePath(_blackDir + "/bishop.png")),
    Pieces.BLACK_CASTLE: pygame.image.load(resourcePath(_blackDir + "/castle.png")),
    Pieces.BLACK_QUEEN: pygame.image.load(resourcePath(_blackDir + "/queen.png")),
    Pieces.BLACK_KING: pygame.image.load(resourcePath(_blackDir + "/king.png"))
  }

  def validMove(self, startPos, endPos):
    return self._rules.validMove(startPos, endPos)

  def movePiece(self, startPos, endPos):
    self._rules.movePiece(startPos, endPos)

  def turn(self):
    return self._rules.turn()

  def isCheck(self):
    return self._rules.isCheck()

  def isCheckmate(self):
    return self._rules.isCheckmate()

  def __str__(self):
    boardStr = ""
    rowIndex = 8
    for row in self._chessBoard:
      boardStr += str(rowIndex)
      for column in row:
        boardStr += " "
        if(column is not None):
          boardStr += str(column)
        else:
          boardStr += "00"
      boardStr += "\n"
      rowIndex -= 1
    boardStr += "  a  b  c  d  e  f  g  h\n"
    return boardStr

  def boardToPygameIndex(self, xpos, ypos):
    return (20 + (ypos * 50), 20 + (xpos * 50))

  def pygameBlit(self, screen):
    rowIndex = 0
    for row in self._chessBoard:
      columnIndex = 0
      for piece in row:
        if(piece is not None):
          (dx, dy) = self.boardToPygameIndex(rowIndex, columnIndex)
          pieceImage = self._images[piece]
          pieceRect = pieceImage.get_rect().move(dx, dy)
          screen.blit(pieceImage, pieceRect)
        columnIndex += 1
      rowIndex += 1
Exemplo n.º 10
0
 def __init__(self, name, color):
     #print "In ChessAI __init__"
     self.name = name
     self.color = color
     self.type = 'AI'
     self.Rules = ChessRules()
Exemplo n.º 11
0
 def __init__(self, name, color):
     self.name = name
     self.color = color
     self.type = 'EnemyOffense'
     self.rules = ChessRules()
Exemplo n.º 12
0
 def __init__(self, name, color):
     self.name = name
     self.color = color
     self.type = 'HeuristicDefense'
     self.Rules = ChessRules()
Exemplo n.º 13
0
class PythonChessMain:
    def __init__(self,options):
        if options.debug:
            self.Board = ChessBoard(1)
            self.debugMode = True
        else:
            self.Board = ChessBoard(0)#0 for normal board setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()
        self.StateList = []
        
    def SetUp(self,options):
        #gameSetupParams: Player 1 and 2 Name, Color, Human/AI level
        if self.debugMode:
            player1Name = 'Kasparov'
            player1Type = 'human'
            player1Color = 'white'
            player2Name = 'Light Blue'
            player2Type = 'AI'
            player2Color = 'black'        
        else:
            GameParams = TkinterGameSetupParams()
            (player1Name, player1Color, player1Type, player2Name, player2Color, player2Type) = GameParams.GetGameSetupParams()

        self.player = [0,0]
        if player1Type == 'human':
            self.player[0] = ChessPlayer(player1Name,player1Color)
        elif player1Type == 'RandomAI':
            self.player[0] = ChessAI_random(player1Name,player1Color)
        elif player1Type == 'SunpushAI':
            self.player[0] = ChessAI_sunpush(player1Name,player1Color)
            
        if player2Type == 'human':
            self.player[1] = ChessPlayer(player2Name,player2Color)
        elif player2Type == 'RandomAI':
            self.player[1] = ChessAI_random(player2Name,player2Color)
        elif player2Type == 'SunpushAI':
            self.player[1] = ChessAI_sunpush(player2Name,player2Color)
            
        if 'AI' in self.player[0].GetType() and 'AI' in self.player[1].GetType():
            self.AIvsAI = True
        else:
            self.AIvsAI = False
            
        if options.pauseSeconds > 0:
            self.AIpause = True
            self.AIpauseSeconds = int(options.pauseSeconds)
        else:
            self.AIpause = False
            
        #create the gui object - didn't do earlier because pygame conflicts with any gui manager (Tkinter, WxPython...)
        if options.text:
            self.guitype = 'text'
            self.Gui = ChessGUI_text()
        else:
            self.guitype = 'pygame'
            if options.old:
                self.Gui = ChessGUI_pygame(0)
            else:
                self.Gui = ChessGUI_pygame(1)
            
    def MainLoop(self):
        currentPlayerIndex = 0
        turnCount = 0
        movelist=[]
        while not self.Rules.IsCheckmate(self.Board) and not self.Rules.IsStalemate(self):
            self.Board.GetSquaresLayout()
            currentColor = self.player[currentPlayerIndex].GetColor()
            self.StateList.append((self.Board.board,currentColor))
            #hardcoded so that player 1 is always white
            if currentColor == 'white':
                turnCount = turnCount + 1
            self.Gui.PrintMessage("")
            baseMsg = "TURN %s - %s (%s)" % (str(turnCount),self.player[currentPlayerIndex].GetName(),currentColor)
            self.Gui.PrintMessage("-----%s-----" % baseMsg)
            self.Gui.Draw(self.Board,currentColor)
            if self.Rules.IsInCheck(self.Board):
                self.Gui.PrintMessage("Warning..."+self.player[currentPlayerIndex].GetName()+" ("+self.player[currentPlayerIndex].GetColor()+") is in check!")
            if self.player[currentPlayerIndex].GetType() == 'AI':
                moveTuple = self.player[currentPlayerIndex].GetMove(self.Board) 
                if moveTuple[1] not in self.Rules.GetListOfValidMoves(self.Board,moveTuple[0]):
                    if (moveTuple[1],moveTuple[2]) not in self.Rules.GetListOfValidMoves(self.Board,moveTuple[0]):
                        print(moveTuple[1])
                        print(self.Rules.DoesMovePutPlayerInCheck(self.Board,'white',moveTuple))
                        raise TypeError('AI did an invalid move')
            else:
                moveTuple = self.Gui.GetPlayerInput(self.Board,currentColor)
            moveReport = self.Board.MovePiece(moveTuple,currentColor,getMessage=True) #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            self.Board.GetSquaresLayout()
            movelist.append(moveReport+'\n')
            self.Gui.PrintMessage(moveReport)
            currentPlayerIndex = (currentPlayerIndex+1)%2 #this will cause the currentPlayerIndex to toggle between 1 and 0
            if self.AIvsAI and self.AIpause:
                time.sleep(self.AIpauseSeconds)
                self.Gui.Draw(self.Board,currentColor)
            with open('logs/chess','w') as f:
                f.writelines(movelist)
            self.Board.Rotate() #rotate it so that chessrules can understand it
            #self.Board.GetSquaresLayout()

        if self.Rules.IsCheckmate(self.Board):
            self.Board.Rotate()
            self.Board.GetSquaresLayout()
            self.Gui.Draw(self.Board,currentColor)
            self.Gui.PrintMessage("CHECKMATE!")
            winnerIndex = (currentPlayerIndex+1)%2
            self.Gui.PrintMessage(self.player[winnerIndex].GetName()+" ("+self.player[winnerIndex].GetColor()+") won the game!")
        else:
            self.Board.Rotate()
            self.Gui.Draw(self.Board,currentColor)
            self.Gui.PrintMessage("STALEMATE!")
            self.Gui.PrintMessage("It's a draw!")
        self.Gui.EndGame(self.Board,currentColor)
Exemplo n.º 14
0
 def __init__(self):
     self.Rules = ChessRules()
Exemplo n.º 15
0
class PythonChessMain:
    def __init__(self, options):
        if options.debug:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                0
            )  #0 for normal board setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()

    def SetUp(self, options):
        #gameSetupParams: Player 1 and 2 Name, Color, Human/AI level
        if self.debugMode:
            player1Name = 'Kasparov'
            player1Type = 'human'
            player1Color = 'white'
            player2Name = 'Light Blue'
            player2Type = 'randomAI'
            player2Color = 'black'
        else:
            GameParams = TkinterGameSetupParams()
            (player1Name, player1Color, player1Type, player2Name, player2Color,
             player2Type) = GameParams.GetGameSetupParams()

        self.player = [0, 0]
        if player1Type == 'human':
            self.player[0] = ChessPlayer(player1Name, player1Color)
        elif player1Type == 'randomAI':
            self.player[0] = ChessAI_random(player1Name, player1Color)
        elif player1Type == 'HeuristicOffense':
            self.player[0] = Off_Heuristic(player1Name, player1Color,
                                           self.Board)
        elif player1Type == 'EnemyOffense':
            self.player[0] = Off_Enemy(player1Name, player1Color, self.Board)

        if player2Type == 'human':
            self.player[1] = ChessPlayer(player2Name, player2Color)
        elif player2Type == 'randomAI':
            self.player[1] = ChessAI_random(player2Name, player2Color)
        elif player2Type == 'HeuristicDefense':
            self.player[1] = Def_Heuristic(player2Name, player2Color,
                                           self.Board)
        elif player2Type == 'EnemyDefense':
            self.player[1] = Def_Enemy(player2Name, player2Color, self.Board)

        if 'AI' in self.player[0].GetType() and 'AI' in self.player[1].GetType(
        ):
            self.AIvsAI = True
        else:
            self.AIvsAI = False

        if options.pauseSeconds > 0:
            self.AIpause = True
            self.AIpauseSeconds = int(options.pauseSeconds)
        else:
            self.AIpause = False

        #create the gui object - didn't do earlier because pygame conflicts with any gui manager (Tkinter, WxPython...)
        if options.text:
            self.guitype = 'text'
            self.Gui = ChessGUI_text()
        else:
            self.guitype = 'pygame'
            if options.old:
                self.Gui = ChessGUI_pygame(0)
            else:
                self.Gui = ChessGUI_pygame(1)

    def MainLoop(self):
        currentPlayerIndex = 0
        turnCount = 0
        # open("log_X.txt", "w").close()
        # open("log_Y.txt", "w").close()
        prevBoards = []  #To compare previous boards
        while not self.Rules.IsCheckmate(
                self.Board.GetState(), self.player[currentPlayerIndex].color):
            board = self.Board.GetState()
            currentColor = self.player[currentPlayerIndex].GetColor()
            #hardcoded so that player 1 is always white
            turnCount = turnCount + 1
            if turnCount == 101:
                self.Gui.PrintMessage("Maximum moves reached.")
                self.Gui.EndGame(board)
            if currentColor == 'black':  #Only the defense player wants a draw
                #print prevBoards.count(board)
                if prevBoards.count(board) == 2:
                    self.Gui.PrintMessage(
                        "Black player calls threefold repetition draw.")
                    self.Gui.EndGame(board)
                prevBoards.append(copy.deepcopy(board))
            self.Gui.PrintMessage("")
            baseMsg = "TURN %s - %s (%s)" % (
                str(turnCount), self.player[currentPlayerIndex].GetName(),
                currentColor)
            self.Gui.PrintMessage("-----%s-----" % baseMsg)
            self.Gui.Draw(board)
            if currentColor == "white":
                currentPlayer = "X"
            if currentColor == "black":
                currentPlayer = "Y"
            if self.Rules.IsInCheck(board, currentColor):
                self.Gui.PrintMessage(
                    "Warning..." + self.player[currentPlayerIndex].GetName() +
                    " (" + self.player[currentPlayerIndex].GetColor() +
                    ") is in check!")

            move = ""
            if self.player[currentPlayerIndex].GetType() == 'HeuristicDefense':
                #	then get new move to put into MoveTuple and make move
                currentPlayer = "Y"

                if turnCount > 1:
                    textFileX = open("log_X.txt", "r")
                    for line in textFileX:
                        move = line
                    textFileY = open("log_Y.txt", "a")
                    textFileY.write(move)
                    textFileY.close()
                    textFileX.close()
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor)
                self.WriteMove(board, moveTuple, currentPlayer, turnCount)

            #	write to text file player_ytext below before changing currentPlayerIndex below
            elif self.player[currentPlayerIndex].GetType(
            ) == 'HeuristicOffense':
                currentPlayer = "X"

                if turnCount > 1:
                    textFileY = open("log_Y.txt", "r")
                    for line in textFileY:
                        move = line
                    textFileX = open("log_X.txt", "a")
                    textFileX.write(move)
                    textFileX.close()
                    textFileY.close()
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor)
                self.WriteMove(board, moveTuple, currentPlayer, turnCount)

            # #	then get new move to put into Movetuple and make move
            # #	write to text file player_xtext below before changing currentPlayerIndex below
            elif self.player[currentPlayerIndex].GetType() == 'EnemyDefense':
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor, turnCount)
            # 	#CALL READ FUNCTION HERE FOR ENEMY PLAYER == DEFENSE KRUTIK
            # 	#moveTuple = defense read function
            elif self.player[currentPlayerIndex].GetType() == 'EnemyOffense':
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor, turnCount)
            # 	#CALL READ FUNCTION HERE FOR ENEMY PLAYER == OFFENSE KRUTIK
            # 	#moveTuple = offense read function
            else:
                moveTuple = self.Gui.GetPlayerInput(board, currentColor)
            moveReport = self.Board.MovePiece(
                moveTuple
            )  #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            self.Gui.PrintMessage(moveReport)
            #	use current player index to determine what file to write to
            #	index = 0 is player x / "white" / offense
            #	index = 1 is player y / "black" / defense
            currentPlayerIndex = (
                currentPlayerIndex + 1
            ) % 2  #this will cause the currentPlayerIndex to toggle between 1 and 0
            self.AIvsAI = True
            if self.AIvsAI and self.AIpause:
                time.sleep(self.AIpauseSeconds)
        self.Gui.PrintMessage("CHECKMATE!")
        winnerIndex = (currentPlayerIndex + 1) % 2
        self.Gui.PrintMessage(self.player[winnerIndex].GetName() + " (" +
                              self.player[winnerIndex].GetColor() +
                              ") won the game!")
        self.Gui.EndGame(board)

    def WriteMove(self, board, tuple, currentPlayer, turnCount):
        #a-g columns
        #1-8 rows
        pieceRow = tuple[0][0]
        pieceCol = tuple[0][1]
        pieceToMove = board[pieceRow][pieceCol]
        print tuple

        if tuple[1][1] == 0:
            columnLetter = 'a'
        elif tuple[1][1] == 1:
            columnLetter = 'b'
        elif tuple[1][1] == 2:
            columnLetter = 'c'
        elif tuple[1][1] == 3:
            columnLetter = 'd'
        elif tuple[1][1] == 4:
            columnLetter = 'e'
        elif tuple[1][1] == 5:
            columnLetter = 'f'
        elif tuple[1][1] == 6:
            columnLetter = 'g'
        elif tuple[1][1] == 7:
            columnLetter = 'h'

        if tuple[1][0] == 0:
            rowNumber = 8
        elif tuple[1][0] == 1:
            rowNumber = 7
        elif tuple[1][0] == 2:
            rowNumber = 6
        elif tuple[1][0] == 3:
            rowNumber = 5
        elif tuple[1][0] == 4:
            rowNumber = 4
        elif tuple[1][0] == 5:
            rowNumber = 3
        elif tuple[1][0] == 6:
            rowNumber = 2
        elif tuple[1][0] == 7:
            rowNumber = 1

        fileName = "log_" + currentPlayer + ".txt"
        file = open(fileName, "a")
        file.write(
            str(turnCount) + " " + currentPlayer + ":" + pieceToMove[1] + ":" +
            columnLetter + str(rowNumber) + "\n")
        file.close()
Exemplo n.º 16
0
class game:
	def __init__(self, *args, **kwargs):
		self.checkmate = False
		self.command = ''
		self.current_player = 0
		self.figures = {'wP':chr(14), 'wR':chr(15), 'wT':chr(16), 'wB':chr(17), 'wQ':chr(18), 'wK':chr(19), 'bP':chr(20), 'bR':chr(21), 'bT':chr(22), 'bB':chr(23), 'bQ':chr(24), 'bK':chr(25)}
		self.board = None
		self.rules = None
		self.players = [0,0]
		self.AIvsAI = False
		self.AIpause = False
		self.AIpauseSeconds = 1
		if has_chess_modules:
			self.rules = ChessRules()
			self.board = ChessBoard(0)
			player1Name = 'Kasparov'
			player1Type = 'human'
			player1Color = 'white'
			player2Name = 'Light Blue'
			player2Type = 'randomAI'
			player2Color = 'black'		
			if player1Type == 'human':
				self.players[0] = ChessPlayer(player1Name,player1Color)
			elif player1Type == 'randomAI':
				self.players[0] = ChessAI.ChessAI_random(player1Name,player1Color)
			elif player1Type == 'defenseAI':
				self.players[0] = ChessAI.ChessAI_defense(player1Name,player1Color)
			elif player1Type == 'offenseAI':
				self.players[0] = ChessAI.ChessAI_offense(player1Name,player1Color)
			if player2Type == 'human':
				self.players[1] = ChessPlayer(player2Name,player2Color)
			elif player2Type == 'randomAI':
				self.players[1] = ChessAI.ChessAI_random(player2Name,player2Color)
			elif player2Type == 'defenseAI':
				self.players[1] = ChessAI.ChessAI_defense(player2Name,player2Color)
			elif player2Type == 'offenseAI':
				self.players[1] = ChessAI.ChessAI_offense(player2Name,player2Color)
			if 'AI' in self.players[0].GetType() and 'AI' in self.players[1].GetType():
				self.AIvsAI = True
		self.font_size_text = 20
		self.font_file_text = os.environ['SYSTEMROOT']+'/Fonts/arial.ttf'
		self.font_size_chess = 40
		self.font_file_chess = 'chess.ttf'
		#~ self.font_file_chess = 'cheq_tt.ttf'
		self.black = SColor(255, 0, 0, 0)
		self.white = SColor(255, 255, 255, 255)
		self.back_color = SColor(255,150,150,150)
		self.board_color = SColor(255, 255, 255, 0)
		self.help_dialog = None
		self.video_driver = None
		self.scene_manager = None
		self.gui_environment = None
		self.font_text = None
		self.font_chess = None
		self.skin = None
		p = SIrrlichtCreationParameters()
		p.DriverType = driverType
		p.WindowSize = dimension2du(640, 480)
		p.AntiAlias = True
		p.WithAlphaChannel = True
		self.device = createDeviceEx(p)
		if self.device:
			self.device.setWindowCaption('Python Chess written by Steve Osborne, Irrlicht GUI by Maxim Kolosov')
			self.device.setResizable(True)
			self.video_driver = self.device.getVideoDriver()
			self.scene_manager = self.device.getSceneManager()
			self.gui_environment = self.device.getGUIEnvironment()
			# icon
			if is_frozen():
				self.video_driver.SetIcon(101)
			else:
				self.video_driver.SetIcon()
			# skin
			self.skin = self.gui_environment.getSkin()
			self.skin.setColor(EGDC_HIGH_LIGHT_TEXT, SColor(255, 0, 0, 0))
			self.skin.setColor(EGDC_GRAY_TEXT, SColor(255, 0, 255, 0))
			# chess font
			self.font_chess = CGUITTFont(self.gui_environment, self.font_file_chess, self.font_size_chess)
			if self.font_chess:
				self.skin.setFont(self.font_chess)
			else:
				self.font_chess = self.gui_environment.getBuiltInFont()
				print('++++ ERROR chess font not created !!!')
			# text font
			self.font_text = CGUITTFont(self.gui_environment, self.font_file_text, self.font_size_text)
			if self.font_text:
				self.skin.setFont(self.font_text, EGDF_BUTTON)
				self.skin.setFont(self.font_text, EGDF_WINDOW)
				self.skin.setFont(self.font_text, EGDF_MENU)
				self.skin.setFont(self.font_text, EGDF_TOOLTIP)
			# create board
			#~ self.dlg_tbl = self.gui_environment.addWindow(recti(0,0,800,600), True, _('board'))
			self.back_table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl, drawBackground = True)
			#~ self.back_table.setDrawFlags(EGTDF_ROWS | EGTDF_COLUMNS)
			self.table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl)
			self.table.setResizableColumns(False)
			self.table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			#~ self.black_table = self.gui_environment.addTable(recti(0,0,800,600), self.dlg_tbl)
			#~ self.black_table.setResizableColumns(False)
			#~ self.black_table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			self.fill_table()
			# create dialog list commands
			self.dlg_cmd = self.gui_environment.addWindow(recti(0,0,150,400))#, True, _('Steps history'))
			self.commands = self.gui_environment.addListBox(recti(0,20,150,300), self.dlg_cmd)
			self.commands.setAutoScrollEnabled(True)
			self.dlg_cmd.setRelativePosition(position2di(500,0))
		else:
			print('ERROR createDevice')

	def fill_table(self):
		blue = SColor(255, 0, 0, 255)
		green = SColor(255, 0, 255, 0)
		index = 0
		columns = '*abcdefgh*'
		for column in columns:
			self.table.addColumn('', index)
			self.table.setColumnWidth(index, 50)
			self.back_table.addColumn(column, index)
			self.back_table.setColumnWidth(index, 50)
			index = index + 1
		index = 0
		rows = '87654321'
		for row in rows:
			self.table.addRow(index)
			self.back_table.addRow(index)
			self.back_table.setCellText(index, 0, row, green)
			self.back_table.setCellText(index, 9, row, green)
			#~ for column in range(self.table.getColumnCount()):
				#~ self.table.setCellColor(index, column, self.white)
			index = index + 1
		self.back_table.addRow(index)#this is bottom row for captions
		first = True
		w, b = chr(1), chr(3)
		for row in range(self.back_table.getRowCount()):
			for column in range(1,self.back_table.getColumnCount()-1):
				if first:
					self.back_table.setCellText(row, column, '')
				else:
					self.back_table.setCellText(row, column, b)
				self.back_table.setCellColor(row, column, blue)
				first = not first
			first = not first
		index = 0
		for column in columns:
			self.back_table.setCellText(8, index, column, green)
			index = index + 1
		if not has_chess_modules:
			for i in range(1,9):
				self.table.setCellText(1, i, self.figures['bP'])
				self.table.setCellText(6, i, self.figures['wP'], self.white)
			self.table.setCellText(0, 1, self.figures['bR'])
			self.table.setCellText(0, 2, self.figures['bT'])
			self.table.setCellText(0, 3, self.figures['bB'])
			self.table.setCellText(0, 4, self.figures['bQ'])
			self.table.setCellText(0, 5, self.figures['bK'])
			self.table.setCellText(0, 6, self.figures['bB'])
			self.table.setCellText(0, 7, self.figures['bT'])
			self.table.setCellText(0, 8, self.figures['bR'])
			self.table.setCellText(7, 1, self.figures['wR'], self.white)
			self.table.setCellText(7, 2, self.figures['wT'], self.white)
			self.table.setCellText(7, 3, self.figures['wB'], self.white)
			self.table.setCellText(7, 4, self.figures['wQ'], self.white)
			self.table.setCellText(7, 5, self.figures['wK'], self.white)
			self.table.setCellText(7, 6, self.figures['wB'], self.white)
			self.table.setCellText(7, 7, self.figures['wT'], self.white)
			self.table.setCellText(7, 8, self.figures['wR'], self.white)
		else:
			self.redraw_board()

	def redraw_board(self):
		board_state = self.board.GetState()
		for row in range(self.table.getRowCount()):
			for column in range(1,self.table.getColumnCount()-1):
				figure = str(board_state[row][column-1])
				#~ print('=== figure', figure)
				if figure[0] in ('b', 'w'):
					if figure[0] == 'w':
						self.table.setCellText(row, column, self.figures[figure], self.white)
					else:
						self.table.setCellText(row, column, self.figures[figure])
				else:
					self.table.setCellText(row, column, '')
		#~ self.gui_environment.setFocus(self.dlg_cmd)
		#~ print "      a      b      c      d      e      f      g      h"
		#~ print "  ----------------------------------------"
		#~ for r in range(8):
			#~ print "r"+str(r)+"|",
			#~ for c in range(8):
				#~ if board_state[r][c] != 'e':
					#~ print  str(board_state[r][c]), "|",
				#~ else:
					#~ print "   |",
				#~ if c == 7:
					#~ print #to get a new line
			#~ print "  ----------------------------------------"

	def translate_step(self, step):
		s = step.replace('8', '0').replace('7', '1').replace('6', '2').replace('5', '3').replace('3', '5').replace('2', '6').replace('1', '7').lower().replace('a', '0').replace('b', '1').replace('c', '2').replace('d', '3').replace('e', '4').replace('f', '5').replace('g', '6').replace('h', '7')
		return (int(s[1]), int(s[0])), (int(s[3]), int(s[2]))

	def make_step(self):
		if len(self.command) < 4 and self.players[self.current_player].GetType() != 'AI':
			print('=== WRONG command %s' % self.command)
			return
		board_state = self.board.GetState()
		if self.rules.IsCheckmate(board_state, self.players[self.current_player].color):
			self.checkmate = True
			print('=== MATE')
			return
		if self.rules.IsInCheck(board_state, self.players[self.current_player].color):
			print('=== Warning... %s is in check!' % self.players[self.current_player].color)
		step = ((1,0), (2,0))
		if self.players[self.current_player].GetType() == 'AI':
			step = self.players[self.current_player].GetMove(self.board.GetState(), self.players[self.current_player].color) 
		else:
			step = self.translate_step(self.command)
		#~ if self.rules.IsClearPath(self.board.GetState(), *step):
		print('=== %s' % self.board.MovePiece(step))
		self.current_player = int(not self.current_player)
		if self.AIvsAI and self.AIpause:
			self.device.sleep(self.AIpauseSeconds)
		self.redraw_board()
		#~ else:
			#~ print('STEP %s is wrong' % self.command)
		if self.players[self.current_player].GetType() == 'AI':
			self.make_step()

	def run(self):
		i_event_receiver = UserIEventReceiver()
		i_event_receiver.game = self
		self.device.setEventReceiver(i_event_receiver)
		while self.device.run():
			if self.device.isWindowActive():
				if i_event_receiver.IsKeyDown(KEY_ESCAPE) and not self.help_dialog:
					break
				if self.video_driver.beginScene(True, True, self.back_color):
					#~ self.screen_size = self.video_driver.getScreenSize()
					#~ if not self.checkmate:
						#~ self.redraw_board()
					#~ self.font.draw(self.command, recti(0, 0, 100, self.font_size_text), self.board_color)
					self.gui_environment.drawAll()
					self.video_driver.endScene()
				self.device.sleep(10)
			else:
				self.device._yield()
		self.device.closeDevice()
		self.device.drop()
Exemplo n.º 17
0
class PythonChessMain:
    def __init__(self, options):
        if options.debug:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                0
            )  #0 for normal board setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()

    def SetUp(self, options):
        #gameSetupParams: Player 1 and 2 Name, Color, Human/AI level
        if self.debugMode:
            player1Name = 'Atahualpa'
            player1Type = 'humano'
            player1Color = 'blanco'
            player2Name = 'Huascar'
            player2Type = 'randomAI'
            player2Color = 'negro'
        else:
            GameParams = TkinterGameSetupParams()
            (player1Name, player1Color, player1Type, player2Name, player2Color,
             player2Type) = GameParams.GetGameSetupParams()

        self.player = [0, 0]
        self.redis = player1Type
        if player1Type == 'humano':
            self.player[0] = ChessPlayer(player1Name, player1Color)
        elif player1Type == 'server':
            self.player[0] = ChessPlayer(player1Name, player1Color)
        elif player1Type == 'client':
            self.player[0] = ChessPlayer(player2Name, player2Color)
        elif player1Type == 'offenseAI':
            self.player[0] = ChessAI_offense(player1Name, player1Color)

        if player2Type == 'humano':
            self.player[1] = ChessPlayer(player2Name, player2Color)
        elif player2Type == 'server':
            self.player[1] = ChessPlayer(player1Name, player1Color)
        elif player2Type == 'client':
            self.player[1] = ChessPlayer(player2Name, player2Color)
        elif player2Type == 'offenseAI':
            self.player[1] = ChessAI_offense(player2Name, player2Color)

        if options.pauseSeconds > 0:
            self.AIpause = True
            self.AIpauseSeconds = int(options.pauseSeconds)
        else:
            self.AIpause = False

        #create the gui object - didn't do earlier because pygame conflicts with any gui manager (Tkinter, WxPython...)
        if options.text:
            self.guitype = 'text'
            self.Gui = ChessGUI_text()
        else:
            self.guitype = 'pygame'
            if options.old:
                self.Gui = ChessGUI_pygame(0)
            else:
                self.Gui = ChessGUI_pygame(1)

    """def reDato(self,s,sc):
		print "globales"
		global hilo
		global datito
		print "esperando mensaje"
		mensaje = sc.recv(1024)
		print "recibido"
		datito=mensaje
		print "hilito"
		hilo = 1
        print "brack"""

    def MainLoop(self):
        hilo = 0
        datito = "123"
        s = 0
        sc = 0
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #s.settimeout(20)
        verify = 2
        if self.redis == 'server':
            verify = 0
            serv = ventanaServer()
            (direccion) = serv.GetipServer()
            if direccion == '0':
                pygame.quit()
                sys.exit(0)
            else:
                s.bind((direccion, 9999))
                s.listen(1)
                s.settimeout(20)
                #s.setblocking (0)
                print "Esperando conexion..."
                sc, adr = s.accept()
                #sc.settimeout(20)
                #sc.setblocking (0)
        elif self.redis == 'client':
            verify = 1
            clie = ventanaClient()
            (direccion1) = clie.GetipClient()
            if direccion1 == '0':
                pygame.quit()
                sys.exit(0)
            else:
                s.connect((direccion1, 9999))
        currentPlayerIndex = 0
        turnCount = 0
        sinComer = 0
        reySoloBlanco = 0
        reySoloNegro = 0
        reySolo = 0
        ayniN = 0
        ayniB = 0
        while not self.Rules.IsCheckmate(self.Board.GetState(),
                                         self.player[currentPlayerIndex].color,
                                         ayniB, ayniN):
            board = self.Board.GetState()
            currentColor = self.player[currentPlayerIndex].GetColor()
            #hardcoded so that player 1 is always white
            if currentColor == 'blanco':
                turnCount = turnCount + 1
            self.Gui.PrintMessage("")
            baseMsg = "TURNO %s - %s (%s)" % (
                str(turnCount), self.player[currentPlayerIndex].GetName(),
                currentColor)
            self.Gui.PrintMessage("-----%s-----" % baseMsg)
            self.Gui.Draw(board)
            if self.Rules.IsInCheck(board, currentColor):
                self.Gui.PrintMessage(
                    "Peligro..." + self.player[currentPlayerIndex].GetName() +
                    " (" + self.player[currentPlayerIndex].GetColor() +
                    ") esta en jaque")
                jak = jake()
                (ka) = jak.aviso()
            if currentColor == 'negro' and verify == 0:  #self.player[currentPlayerIndex].GetType() == 'server' and turnCount%2!=0: blanco espera movimiento
                """#s.settimeout(20)
				#s.setblocking (0)
				#hilo=False
				print "ejecutando el treaht"
				thread.start_new_thread(self.reDato,(s,sc))
				hilo=0
				print hilo,"bucle infinito"
				while (hilo==0):
						pass
				#hilo=True
				print "salio de bucle",hilo
				recibido=datito"""
                recibido = sc.recv(1024)
                if recibido == "empate":
                    empa = confirmarDerrota()
                    (empat) = empa.confirmacionEmpate()
                    if empat == 1:
                        sc.send("aceptar")
                        em = empate()
                        (emp) = em.mostrarEmpate()
                        self.Gui.EndGame(board)
                    elif empat == 2:
                        sc.send("no")
                        recibido = sc.recv(1024)
                elif recibido == "salir":
                    vi = victoria()
                    (vic) = vi.mostrarVictoria()
                    self.Gui.EndGame(board)
                else:
                    numero = int(recibido)
                    Aa = numero / 1000
                    AA = numero % 1000
                    Ee = AA / 100
                    EE = AA % 100
                    Ii = EE / 10
                    II = EE % 10
                    moveTuple = (Aa, Ee), (Ii, II)

            elif currentColor == 'blanco' and verify == 0:  #self.player[currentPlayerIndex].GetType() == 'client' and turnCount%2==0: blanco hace su movimiento
                moveTuple = self.Gui.GetPlayerInput(board, currentColor,
                                                    verify, s, sc, ayniB,
                                                    ayniN)
                (a, e), (i, o) = moveTuple
                A = str(a)
                E = str(e)
                I = str(i)
                O = str(o)
                mensaje = A + E + I + O
                sc.send(mensaje)
            elif currentColor == 'blanco' and verify == 1:  #negro espera movimiento
                recibido = s.recv(1024)
                if recibido == "empate":
                    empa = confirmarDerrota()
                    (empat) = empa.confirmacionEmpate()
                    if empat == 1:
                        s.send("aceptar")
                        em = empate()
                        (emp) = em.mostrarEmpate()
                        self.Gui.EndGame(board)
                    elif empat == 2:
                        s.send("no")
                        recibido = s.recv(1024)
                elif recibido == "salir":
                    vi = victoria()
                    (vic) = vi.mostrarVictoria()
                    self.Gui.EndGame(board)
                else:
                    numero = int(recibido)
                    Aa = numero / 1000
                    AA = numero % 1000
                    Ee = AA / 100
                    EE = AA % 100
                    Ii = EE / 10
                    II = EE % 10
                    moveTuple = (Aa, Ee), (Ii, II)
            elif currentColor == 'negro' and verify == 1:  #blanco hace su movimiento
                moveTuple = self.Gui.GetPlayerInput(board, currentColor,
                                                    verify, s, sc, ayniB,
                                                    ayniN)
                (a, e), (i, o) = moveTuple
                A = str(a)
                E = str(e)
                I = str(i)
                O = str(o)
                mensaje = A + E + I + O
                s.send(mensaje)
            else:
                moveTuple = self.Gui.GetPlayerInput(board, currentColor,
                                                    verify, s, sc, ayniB,
                                                    ayniN)
            moveReport, contadorsito, solito, ayni = self.Board.MovePiece(
                moveTuple
            )  #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            self.Gui.PrintMessage(moveReport)
            currentPlayerIndex = (
                currentPlayerIndex + 1
            ) % 2  #this will cause the currentPlayerIndex to toggle between 1 and 0
            if ayni == 1:
                ayniB = ayniB + 1
                print ayniB, "y", ayniN
            elif ayni == 2:
                ayniN = ayniN + 1
                print ayniB, "y", ayniN
            if contadorsito == 1:
                sinComer = sinComer + 1
            else:
                sinComer = 0
            if solito == 1:
                reySoloNegro = reySoloNegro + 1
            elif solito == 0:
                reySoloBlanco = reySoloBlanco + 1
            if reySoloBlanco == 14 or reySoloNegro == 14:
                reySolo = reySolo + 1
            if sinComer == 28 or reySolo == 15:
                em = empate()
                (emp) = em.mostrarEmpate()
                self.Gui.EndGame(board)

        s.close()
        self.Gui.PrintMessage(
            "--------------------------------------------------     JAKE MATE")
        winnerIndex = (currentPlayerIndex + 1) % 2
        self.Gui.PrintMessage(self.player[winnerIndex].GetName() + " (" +
                              self.player[winnerIndex].GetColor() +
                              ") gano el juego")
        if (self.player[winnerIndex].GetColor() == 'blanco' and verify
                == 0) or (self.player[winnerIndex].GetColor() == 'negro'
                          and verify == 1):
            vi = victoria()
            (vic) = vi.mostrarVictoria()
        elif (self.player[winnerIndex].GetColor() == 'negro' and verify
              == 0) or (self.player[winnerIndex].GetColor() == 'blanco'
                        and verify == 1):
            dec = derrota()
            (derr) = dec.mostrarDerrota()
        else:
            vi = victoria()
            (vic) = vi.mostrarVictoria()
        self.Gui.EndGame(board)
Exemplo n.º 18
0
class ChessGUI_text:
    def __init__(self):
        self.Rules = ChessRules()

    # def GetGameSetupParams(self):
    #MOVED FUNCTIONALITY TO CHESSGAMEPARAMS.PY
    # player1Name = raw_input("Player 1 name: ")
    # player1Color = 'red'
    # while not player1Color == 'black' and not player1Color == 'white':
    # player1Color = raw_input("  Player 1 color ('white' or 'black'): ")
    # if player1Color == 'white':
    # player2Color = 'black'
    # else:
    # player2Color = 'white'
    # player1Type = 'monkey'
    # while not player1Type == 'human' and not player1Type == 'AI':
    # player1Type = raw_input("  Is player 1 'human' or 'AI'? ")

    # player2Name = raw_input("Player 2 name: ");
    # player2Type = 'monkey'
    # while not player2Type == 'human' and not player2Type == 'AI':
    # player2Type = raw_input("  Is player 2 'human' or 'AI'? ")

    # print "Setting up game..."
    # print "Player 1:", player1Name, player1Color, player1Type
    # print "Player 2:", player2Name, player2Color, player2Type

    # return (player1Name,player1Color,player1Type,player2Name,player2Color,player2Type)

    def Draw(self, board):
        print "     0   1   2   3   4   5   6   7 "
        print "   ----------------------------------------"
        count = -1
        for r in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
            count = count + 1
            print "", r, "|",
            for c in range(8):
                if board[count][c] != 'e':
                    print str(board[count][c]), "|",
                else:
                    print "   |",
                if c == 7:
                    print  #to get a new line
            print "   ----------------------------------------"

    def EndGame(self, board):
        self.Draw(board)

    def GetPlayerInput(self, board, color):
        fromTuple = self.GetPlayerInput_SquareFrom(board, color)
        toTuple = self.GetPlayerInput_SquareTo(board, color, fromTuple)
        return (fromTuple, toTuple)

    def GetPlayerInput_SquareFrom(self, board, color):
        ch = "?"
        cmd_r = 0
        cmd_c = 0
        cmd_c = 0
        rowinput = 0
        colinput = 0
        while (ch not in board[rowinput][colinput]
               or self.Rules.GetListOfValidMoves(board, color,
                                                 (rowinput, colinput)) == []):
            print "Player", color
            # cmd_r = int(raw_input("  From row: "))
            # cmd_c = int(raw_input("  From col: "))
            rawinput = raw_input("> Your Move:\n ")
            if len(rawinput) != 2:
                print("invalid move")
            else:  #97 - 104 a-h 48-56 0-7
                inputstring = rawinput.lower()
                if ord(inputstring[0]) >= 97 and ord(
                        inputstring[0]) <= 104 and ord(
                            inputstring[1]) >= 48 and ord(
                                inputstring[1]) <= 56:
                    # print("row and col valid")
                    rowinput = ord(inputstring[0]) - 97
                    colinput = ord(inputstring[1]) - 48
                    if color == "black":
                        ch = "b"
                    else:
                        ch = "w"
                    if (board[rowinput][colinput] == 'e'):
                        print "  Nothing there!"
                    elif (ch not in board[rowinput][colinput]):
                        print "  That's not your piece!"
                    elif self.Rules.GetListOfValidMoves(
                            board, color, (rowinput, colinput)) == []:
                        print "  No valid moves for that piece!"
                else:
                    print " -               - "
                    print " - Invalid Input - "
                    print " -               - "
        # print (rowinput,colinput)
        return (rowinput, colinput)
        #     if color == "black":
        #         ch = "b"
        #     else:
        #         ch = "w"
        #     if (board[cmd_r][cmd_c] == 'e'):
        #         print "  Nothing there!"
        #     elif (ch not in board[cmd_r][cmd_c]):
        #         print "  That's not your piece!"
        #     elif self.Rules.GetListOfValidMoves(board,color,(cmd_r,cmd_c)) == []:
        #         print "  No valid moves for that piece!"
        #
        # return (cmd_r,cmd_c)

    def GetPlayerInput_SquareTo(self, board, color, fromTuple):
        toTuple = ('x', 'x')
        collist = ['0', '1', '2', '3', '4', '5', '6', '7']
        rowlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
        validMoveList = self.Rules.GetListOfValidMoves(board, color, fromTuple)
        realvalidMoveList = []
        for el in validMoveList:
            temp = str(rowlist[el[0]]).upper() + str(collist[el[1]])
            realvalidMoveList.append(temp)
        # print "List of valid moves for piece at",rowlist[fromTuple[0]]collist[fromTuple[1]],": ", validMoveList
        print "List of valid moves for piece at", str(
            rowlist[fromTuple[0]]).upper() + str(
                collist[fromTuple[1]]), ": ", realvalidMoveList

        while (not toTuple in validMoveList):
            rawinput = raw_input("> Target Square:\n ")
            if len(rawinput) != 2:
                print("invalid move")
            else:  #97 - 104 a-h 48-56 0-7
                inputstring = rawinput.lower()

                if ord(inputstring[0]) >= 97 and ord(
                        inputstring[0]) <= 104 and ord(
                            inputstring[1]) >= 48 and ord(
                                inputstring[1]) <= 56:
                    # print("row and col valid")
                    rowinput = ord(inputstring[0]) - 97
                    colinput = ord(inputstring[1]) - 48
                    toTuple = (rowinput, colinput)
                    if not inputstring in validMoveList:
                        print "  Invalid move!"
                    elif not toTuple in validMoveList:
                        print "  Invalid move!"
                    elif self.Rules.GetListOfValidMoves(
                            board, color, (rowinput, colinput)) == []:
                        print "  No valid moves for that piece!"
                else:
                    print " -               - "
                    print " - Invalid Input - "
                    print " -               - "

        return toTuple

    def PrintMessage(self, message):
        print message
Exemplo n.º 19
0
	def __init__(self, *args, **kwargs):
		self.checkmate = False
		self.command = ''
		self.current_player = 0
		self.figures = {'wP':chr(14), 'wR':chr(15), 'wT':chr(16), 'wB':chr(17), 'wQ':chr(18), 'wK':chr(19), 'bP':chr(20), 'bR':chr(21), 'bT':chr(22), 'bB':chr(23), 'bQ':chr(24), 'bK':chr(25)}
		self.board = None
		self.rules = None
		self.players = [0,0]
		self.AIvsAI = False
		self.AIpause = False
		self.AIpauseSeconds = 1
		if has_chess_modules:
			self.rules = ChessRules()
			self.board = ChessBoard(0)
			player1Name = 'Kasparov'
			player1Type = 'human'
			player1Color = 'white'
			player2Name = 'Light Blue'
			player2Type = 'randomAI'
			player2Color = 'black'		
			if player1Type == 'human':
				self.players[0] = ChessPlayer(player1Name,player1Color)
			elif player1Type == 'randomAI':
				self.players[0] = ChessAI.ChessAI_random(player1Name,player1Color)
			elif player1Type == 'defenseAI':
				self.players[0] = ChessAI.ChessAI_defense(player1Name,player1Color)
			elif player1Type == 'offenseAI':
				self.players[0] = ChessAI.ChessAI_offense(player1Name,player1Color)
			if player2Type == 'human':
				self.players[1] = ChessPlayer(player2Name,player2Color)
			elif player2Type == 'randomAI':
				self.players[1] = ChessAI.ChessAI_random(player2Name,player2Color)
			elif player2Type == 'defenseAI':
				self.players[1] = ChessAI.ChessAI_defense(player2Name,player2Color)
			elif player2Type == 'offenseAI':
				self.players[1] = ChessAI.ChessAI_offense(player2Name,player2Color)
			if 'AI' in self.players[0].GetType() and 'AI' in self.players[1].GetType():
				self.AIvsAI = True
		self.font_size_text = 20
		self.font_file_text = os.environ['SYSTEMROOT']+'/Fonts/arial.ttf'
		self.font_size_chess = 40
		self.font_file_chess = 'chess.ttf'
		#~ self.font_file_chess = 'cheq_tt.ttf'
		self.black = SColor(255, 0, 0, 0)
		self.white = SColor(255, 255, 255, 255)
		self.back_color = SColor(255,150,150,150)
		self.board_color = SColor(255, 255, 255, 0)
		self.help_dialog = None
		self.video_driver = None
		self.scene_manager = None
		self.gui_environment = None
		self.font_text = None
		self.font_chess = None
		self.skin = None
		p = SIrrlichtCreationParameters()
		p.DriverType = driverType
		p.WindowSize = dimension2du(640, 480)
		p.AntiAlias = True
		p.WithAlphaChannel = True
		self.device = createDeviceEx(p)
		if self.device:
			self.device.setWindowCaption('Python Chess written by Steve Osborne, Irrlicht GUI by Maxim Kolosov')
			self.device.setResizable(True)
			self.video_driver = self.device.getVideoDriver()
			self.scene_manager = self.device.getSceneManager()
			self.gui_environment = self.device.getGUIEnvironment()
			# icon
			if is_frozen():
				self.video_driver.SetIcon(101)
			else:
				self.video_driver.SetIcon()
			# skin
			self.skin = self.gui_environment.getSkin()
			self.skin.setColor(EGDC_HIGH_LIGHT_TEXT, SColor(255, 0, 0, 0))
			self.skin.setColor(EGDC_GRAY_TEXT, SColor(255, 0, 255, 0))
			# chess font
			self.font_chess = CGUITTFont(self.gui_environment, self.font_file_chess, self.font_size_chess)
			if self.font_chess:
				self.skin.setFont(self.font_chess)
			else:
				self.font_chess = self.gui_environment.getBuiltInFont()
				print('++++ ERROR chess font not created !!!')
			# text font
			self.font_text = CGUITTFont(self.gui_environment, self.font_file_text, self.font_size_text)
			if self.font_text:
				self.skin.setFont(self.font_text, EGDF_BUTTON)
				self.skin.setFont(self.font_text, EGDF_WINDOW)
				self.skin.setFont(self.font_text, EGDF_MENU)
				self.skin.setFont(self.font_text, EGDF_TOOLTIP)
			# create board
			#~ self.dlg_tbl = self.gui_environment.addWindow(recti(0,0,800,600), True, _('board'))
			self.back_table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl, drawBackground = True)
			#~ self.back_table.setDrawFlags(EGTDF_ROWS | EGTDF_COLUMNS)
			self.table = self.gui_environment.addTable(recti(0,0,800,600))#, self.dlg_tbl)
			self.table.setResizableColumns(False)
			self.table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			#~ self.black_table = self.gui_environment.addTable(recti(0,0,800,600), self.dlg_tbl)
			#~ self.black_table.setResizableColumns(False)
			#~ self.black_table.setDrawFlags(EGUI_TABLE_DRAW_FLAGS)
			self.fill_table()
			# create dialog list commands
			self.dlg_cmd = self.gui_environment.addWindow(recti(0,0,150,400))#, True, _('Steps history'))
			self.commands = self.gui_environment.addListBox(recti(0,20,150,300), self.dlg_cmd)
			self.commands.setAutoScrollEnabled(True)
			self.dlg_cmd.setRelativePosition(position2di(500,0))
		else:
			print('ERROR createDevice')
Exemplo n.º 20
0
class CMtree:
	def __init__(self, lvl, board, color):
		self.lvl = lvl
		self.board = board
		self.color = color
		self.Rules = ChessRules()
		self.tree = self.createNodeLevel(self.board, self.color, 0, None)
		self.optime = -1
		self.nextmove = chessMove()
		
	def makeMove(self, f, t, board):
		toBoard = deepcopy(board)
		toBoard[t[0]][t[1]] = board[f[0]][f[1]]
		toBoard[f[0]][f[1]] = 'e'
		return toBoard
		
	def unmakeMove(self, f, t, board):
		toBoard = deepcopy(board)
		toBoard[f[0]][f[1]] = board[t[0]][t[1]]
		toBoard[t[0]][t[1]] = 'e'
		return toBoard
		
	def createNodeLevel(self, board, color, lvl, dad):
		for f in self.Rules.getMyPiecesWithLegalMoves(board, color):
			for t in self.Rules.GetListOfValidMoves(board, color,(f[0],f[1])):
				yield chessMove(dad, f, t, board, lvl)
				
					
	def positionEvaluation(self, dad):
		if dad.children[-1].color in self.color:
			dad.children[-1].setScore (dad.score + dad.children[-1].score)
		else:
			dad.children[-1].setScore (dad.score - dad.children[-1].score)
				
	def alphabeta2(self, move, alpha, beta):
		if move.lvl == self.lvl
			return move.score
			
		for f in self.Rules.getMyPiecesWithLegalMoves(move.board, color):
			for t in self.Rules.GetListOfValidMoves(move.board, color,(f[0],f[1])):
				chessMove(dad, f, t, board, lvl)
		
		
		
	def alphabeta(self, n, alpha, beta):
		if (n.children):
			if (n.color == self.color):
				for i in n.children:
					alpha = max(self.alphabeta(i,alpha,beta),alpha)
					if(alpha>=beta):
						return beta
				return alpha
			else:
				for i in n.children:
					beta = min(self.alphabeta(i,alpha,beta),beta)
					if(alpha>=beta):
						return alpha
				return beta
		else:
			return n.score
	
	
	
	def route(self):
		def recursive(n):
			if n.dad:
				if (n.dad.dad):
					return recursive(n.dad)
				else:
					return n.dad
				
		for i in self.leafs:
			if(i.score==self.optime):
				self.nextmove = recursive(i)
				
	def run_alphabeta(self):
		for i in self.tree:
			temp = self.alphabeta(i, -9000, 9951)
			#temp = self.alphabeta(i)
			if temp > self.optime:
				self.optime = temp
				self.nextmove = i
Exemplo n.º 21
0
	def __init__(self,name,color):
		self.name = name
		self.color = color
		self.type = 'AI'
		self.Rules = ChessRules()
Exemplo n.º 22
0
class PythonChessAIStats:
    def __init__(self):
        self.Rules = ChessRules()

    def SetUp(self, whiteType, blackType):
        self.player = [0, 0]
        if whiteType == "defense":
            self.player[0] = ChessAI_defense("Defense AI - white", "white")
        elif whiteType == "offense":
            self.player[0] = ChessAI_offense("Offense AI - white", "white")
        else:
            self.player[0] = ChessAI_random("Random AI - white", "white")

        if blackType == "defense":
            self.player[1] = ChessAI_defense("Defense AI - black", "black")
        elif blackType == "offense":
            self.player[1] = ChessAI_offense("Offense AI - black", "black")
        else:
            self.player[1] = ChessAI_random("Random AI - black", "black")

    def Run(self, numRuns, useExternalSeed, seedFileName):
        self.seeds = []
        if useExternalSeed:
            #read seeds from seedFileName
            seedFile = open(seedFileName)
            for line in seedFile:
                if line != "":
                    self.seeds.append(int(line))

        self.results = []
        for r in range(numRuns):
            print ""
            #load seed
            if r < len(self.seeds):
                random.seed(
                    self.seeds[r])  #use file specified seed if available
                print "Using seed %d" % self.seeds[r]
            else:
                random.seed(
                )  #otherwise, use the system clock (default action for random.seed())

            print "Playing Match #%d" % (r + 1),
            self.results.append(self.PlaySingleMatch())

    def PlaySingleMatch(self):
        self.Board = ChessBoard(0)  #reset board
        currentPlayerIndex = 0
        turnCount = 0

        while not self.Rules.IsCheckmate(
                self.Board.GetState(), self.player[currentPlayerIndex].color):
            board = self.Board.GetState()
            currentColor = self.player[currentPlayerIndex].GetColor()
            #hardcoded so that player 1 is always white
            if currentColor == 'white':
                turnCount = turnCount + 1
                if turnCount % 10 == 0:
                    print " %d" % turnCount,
                if turnCount > 200:
                    return (
                        turnCount, -1
                    )  #Call it a draw... otherwise some games can go on forever.
            moveTuple = self.player[currentPlayerIndex].GetMove(
                self.Board.GetState(), currentColor)
            moveReport = self.Board.MovePiece(
                moveTuple
            )  #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            #print moveReport
            currentPlayerIndex = (
                currentPlayerIndex + 1
            ) % 2  #this will cause the currentPlayerIndex to toggle between 1 and 0

        winnerIndex = (currentPlayerIndex + 1) % 2

        return (turnCount, winnerIndex)

    def PrintResults(self, writeToFile, outFileName, useExternalSeed,
                     seedFileName):
        numRuns = len(self.results)
        whiteWins = 0
        whiteLosses = 0
        whiteTurnsToWin = 0
        whiteTurnsToLoss = 0
        blackWins = 0
        blackLosses = 0
        blackTurnsToWin = 0
        blackTurnsToLoss = 0
        draws = 0

        #winnerIndex: 0 for white, 1 for black, -1 for draw
        for m in self.results:
            turns = m[0]
            winner = m[1]
            if winner == 0:
                whiteWins = whiteWins + 1
                blackLosses = blackLosses + 1
                whiteTurnsToWin = whiteTurnsToWin + turns
                blackTurnsToLoss = blackTurnsToLoss + turns
            elif winner == 1:
                blackWins = blackWins + 1
                whiteLosses = whiteLosses + 1
                blackTurnsToWin = blackTurnsToWin + turns
                whiteTurnsToLoss = whiteTurnsToLoss + turns
            else:
                draws = draws + 1

        whiteWinPct = 100 * whiteWins / numRuns
        whiteAveTurnsToWin = whiteTurnsToWin / numRuns
        blackWinPct = 100 * blackWins / numRuns
        blackAveTurnsToWin = blackTurnsToWin / numRuns
        drawPct = 100 * draws / numRuns
        time = str(datetime.datetime.now())
        print ""
        print "Final results: "
        print "  " + time
        print "  %d runs" % numRuns
        if useExternalSeed:
            print "  %d random seeds used from %s" % (len(
                self.seeds), seedFileName)
        print "  %s win pct = %0.2f" % (self.player[0].GetName(), whiteWinPct)
        print "  %s average number of turns to win = %0.2f" % (
            self.player[0].GetName(), whiteAveTurnsToWin)
        print "  %s win pct = %0.2f" % (self.player[1].GetName(), blackWinPct)
        print "  %s average number of turns to win = %0.2f" % (
            self.player[1].GetName(), blackAveTurnsToWin)
        print "  Draw pct = %0.2f" % drawPct

        if writeToFile:
            f = open(outFileName, 'a')
            f.write("\n")
            f.write(time + "\n")
            f.write(str("%d runs" % numRuns) + "\n")
            if useExternalSeed:
                f.write(
                    str("%d random seeds used from %s" %
                        (len(self.seeds), seedFileName)) + "\n")
            f.write(
                str("%s win pct = %0.2f" %
                    (self.player[0].GetName(), whiteWinPct)) + "\n")
            f.write(
                str("%s average number of turns to win = %0.2f" %
                    (self.player[0].GetName(), whiteAveTurnsToWin)) + "\n")
            f.write(
                str("%s win pct = %0.2f" %
                    (self.player[1].GetName(), blackWinPct)) + "\n")
            f.write(
                str("%s average number of turns to win = %0.2f" %
                    (self.player[1].GetName(), blackAveTurnsToWin)) + "\n")
            f.write(str("Draw pct = %0.2f" % drawPct) + "\n")
Exemplo n.º 23
0
class ChessGUI_text:
    def __init__(self):
        self.Rules = ChessRules()

    # def GetGameSetupParams(self):
    #MOVED FUNCTIONALITY TO CHESSGAMEPARAMS.PY
    # player1Name = raw_input("Player 1 name: ")
    # player1Color = 'red'
    # while not player1Color == 'black' and not player1Color == 'white':
    # player1Color = raw_input("  Player 1 color ('white' or 'black'): ")
    # if player1Color == 'white':
    # player2Color = 'black'
    # else:
    # player2Color = 'white'
    # player1Type = 'monkey'
    # while not player1Type == 'human' and not player1Type == 'AI':
    # player1Type = raw_input("  Is player 1 'human' or 'AI'? ")

    # player2Name = raw_input("Player 2 name: ");
    # player2Type = 'monkey'
    # while not player2Type == 'human' and not player2Type == 'AI':
    # player2Type = raw_input("  Is player 2 'human' or 'AI'? ")

    # print "Setting up game..."
    # print "Player 1:", player1Name, player1Color, player1Type
    # print "Player 2:", player2Name, player2Color, player2Type

    # return (player1Name,player1Color,player1Type,player2Name,player2Color,player2Type)

    def Draw(self, board):
        print("    c0   c1   c2   c3   c4   c5   c6   c7 ")
        print("  ----------------------------------------")
        for r in range(8):
            print("r" + str(r) + "|", )
            for c in range(8):
                if board[r][c] != 'e':
                    print(
                        str(board[r][c]),
                        "|",
                    )
                else:
                    print("   |", )
                if c == 7:
                    print()  #to get a new line
            print("  ----------------------------------------")

    def EndGame(self, board):
        self.Draw(board)

    def GetPlayerInput(self, board, color):
        fromTuple = self.GetPlayerInput_SquareFrom(board, color)
        toTuple = self.GetPlayerInput_SquareTo(board, color, fromTuple)
        return (fromTuple, toTuple)

    def GetPlayerInput_SquareFrom(self, board, color):
        ch = "?"
        cmd_r = 0
        cmd_c = 0
        while (ch not in board[cmd_r][cmd_c]
               or self.Rules.GetListOfValidMoves(board, color,
                                                 (cmd_r, cmd_c)) == []):
            print("Player", color)
            cmd_r = int(raw_input("  From row: "))
            cmd_c = int(raw_input("  From col: "))
            if color == "black":
                ch = "b"
            else:
                ch = "w"
            if (board[cmd_r][cmd_c] == 'e'):
                print("  Nothing there!")
            elif (ch not in board[cmd_r][cmd_c]):
                print("  That's not your piece!")
            elif self.Rules.GetListOfValidMoves(board, color,
                                                (cmd_r, cmd_c)) == []:
                print("  No valid moves for that piece!")

        return (cmd_r, cmd_c)

    def GetPlayerInput_SquareTo(self, board, color, fromTuple):
        toTuple = ('x', 'x')
        validMoveList = self.Rules.GetListOfValidMoves(board, color, fromTuple)
        print("List of valid moves for piece at", fromTuple, ": ",
              validMoveList)

        while (not toTuple in validMoveList):
            cmd_r = int(raw_input("  To row: "))
            cmd_c = int(raw_input("  To col: "))
            toTuple = (cmd_r, cmd_c)
            if not toTuple in validMoveList:
                print("  Invalid move!")

        return toTuple

    def PrintMessage(self, message):
        print(message)
Exemplo n.º 24
0
class ChessGUI_pygame:
    def __init__(self, graphicStyle=1):
        os.environ[
            'SDL_VIDEO_CENTERED'] = '1'  #should center pygame window on the screen
        self.Rules = ChessRules()
        pygame.init()
        pygame.display.init()
        self.screen = pygame.display.set_mode((850, 500))
        self.boardStart_x = 50
        self.boardStart_y = 50
        pygame.display.set_caption('Python Chess')

        self.textBox = ScrollingTextBox(self.screen, 525, 825, 50, 450)
        self.LoadImages(graphicStyle)
        #pygame.font.init() - should be already called by pygame.init()
        self.fontDefault = pygame.font.Font(None, 20)

    def LoadImages(self, graphicStyle):
        if graphicStyle == 0:
            self.square_size = 50  #all images must be images 50 x 50 pixels
            self.white_square = pygame.image.load(
                os.path.join("images", "white_square.png")).convert()
            self.brown_square = pygame.image.load(
                os.path.join("images", "brown_square.png")).convert()
            self.cyan_square = pygame.image.load(
                os.path.join("images", "cyan_square.png")).convert()
            #"convert()" is supposed to help pygame display the images faster.  It seems to mess up transparency - makes it all black!
            #And, for this chess program, the images don't need to change that fast.
            self.black_pawn = pygame.image.load(
                os.path.join("images", "blackPawn.png"))
            self.black_rook = pygame.image.load(
                os.path.join("images", "blackRook.png"))
            self.black_knight = pygame.image.load(
                os.path.join("images", "blackKnight.png"))
            self.black_bishop = pygame.image.load(
                os.path.join("images", "blackBishop.png"))
            self.black_king = pygame.image.load(
                os.path.join("images", "blackKing.png"))
            self.black_queen = pygame.image.load(
                os.path.join("images", "blackQueen.png"))
            self.white_pawn = pygame.image.load(
                os.path.join("images", "whitePawn.png"))
            self.white_rook = pygame.image.load(
                os.path.join("images", "whiteRook.png"))
            self.white_knight = pygame.image.load(
                os.path.join("images", "whiteKnight.png"))
            self.white_bishop = pygame.image.load(
                os.path.join("images", "whiteBishop.png"))
            self.white_king = pygame.image.load(
                os.path.join("images", "whiteKing.png"))
            self.white_queen = pygame.image.load(
                os.path.join("images", "whiteQueen.png"))
        elif graphicStyle == 1:
            self.square_size = 50
            self.white_square = pygame.image.load(
                os.path.join("images", "white_square.png")).convert()
            self.brown_square = pygame.image.load(
                os.path.join("images", "brown_square.png")).convert()
            self.cyan_square = pygame.image.load(
                os.path.join("images", "cyan_square.png")).convert()

            self.black_pawn = pygame.image.load(
                os.path.join("images", "Chess_tile_pd.png")).convert()
            self.black_pawn = pygame.transform.scale(
                self.black_pawn, (self.square_size, self.square_size))
            self.black_rook = pygame.image.load(
                os.path.join("images", "Chess_tile_rd.png")).convert()
            self.black_rook = pygame.transform.scale(
                self.black_rook, (self.square_size, self.square_size))
            self.black_knight = pygame.image.load(
                os.path.join("images", "Chess_tile_nd.png")).convert()
            self.black_knight = pygame.transform.scale(
                self.black_knight, (self.square_size, self.square_size))
            self.black_bishop = pygame.image.load(
                os.path.join("images", "Chess_tile_bd.png")).convert()
            self.black_bishop = pygame.transform.scale(
                self.black_bishop, (self.square_size, self.square_size))
            self.black_king = pygame.image.load(
                os.path.join("images", "Chess_tile_kd.png")).convert()
            self.black_king = pygame.transform.scale(
                self.black_king, (self.square_size, self.square_size))
            self.black_queen = pygame.image.load(
                os.path.join("images", "Chess_tile_qd.png")).convert()
            self.black_queen = pygame.transform.scale(
                self.black_queen, (self.square_size, self.square_size))

            self.white_pawn = pygame.image.load(
                os.path.join("images", "Chess_tile_pl.png")).convert()
            self.white_pawn = pygame.transform.scale(
                self.white_pawn, (self.square_size, self.square_size))
            self.white_rook = pygame.image.load(
                os.path.join("images", "Chess_tile_rl.png")).convert()
            self.white_rook = pygame.transform.scale(
                self.white_rook, (self.square_size, self.square_size))
            self.white_knight = pygame.image.load(
                os.path.join("images", "Chess_tile_nl.png")).convert()
            self.white_knight = pygame.transform.scale(
                self.white_knight, (self.square_size, self.square_size))
            self.white_bishop = pygame.image.load(
                os.path.join("images", "Chess_tile_bl.png")).convert()
            self.white_bishop = pygame.transform.scale(
                self.white_bishop, (self.square_size, self.square_size))
            self.white_king = pygame.image.load(
                os.path.join("images", "Chess_tile_kl.png")).convert()
            self.white_king = pygame.transform.scale(
                self.white_king, (self.square_size, self.square_size))
            self.white_queen = pygame.image.load(
                os.path.join("images", "Chess_tile_ql.png")).convert()
            self.white_queen = pygame.transform.scale(
                self.white_queen, (self.square_size, self.square_size))

    def PrintMessage(self, message):
        #prints a string to the area to the right of the board
        self.textBox.Add(message)
        self.textBox.Draw()

    def ConvertToScreenCoords(self, chessSquareTuple):
        #converts a (row,col) chessSquare into the pixel location of the upper-left corner of the square
        (row, col) = chessSquareTuple
        screenX = self.boardStart_x + col * self.square_size
        screenY = self.boardStart_y + row * self.square_size
        return (screenX, screenY)

    def ConvertToChessCoords(self, screenPositionTuple):
        #converts a screen pixel location (X,Y) into a chessSquare tuple (row,col)
        #x is horizontal, y is vertical
        #(x=0,y=0) is upper-left corner of the screen
        (X, Y) = screenPositionTuple
        row = (Y - self.boardStart_y) / self.square_size
        col = (X - self.boardStart_x) / self.square_size
        return (row, col)

    def Draw(self, board, highlightSquares=[]):
        self.screen.fill((0, 0, 0))
        self.textBox.Draw()
        boardSize = len(
            board
        )  #board should be square.  boardSize should be always 8 for chess, but I dislike "magic numbers" :)

        #draw blank board
        current_square = 0
        for r in range(boardSize):
            for c in range(boardSize):
                (screenX, screenY) = self.ConvertToScreenCoords((r, c))
                if current_square:
                    self.screen.blit(self.brown_square, (screenX, screenY))
                    current_square = (current_square + 1) % 2
                else:
                    self.screen.blit(self.white_square, (screenX, screenY))
                    current_square = (current_square + 1) % 2

            current_square = (current_square + 1) % 2

        #draw row/column labels around the edge of the board
        chessboard_obj = ChessBoard(
            0)  #need a dummy object to access some of ChessBoard's methods....
        color = (255, 255, 255)  #white
        antialias = 1

        #top and bottom - display cols
        for c in range(boardSize):
            for r in [-1, boardSize]:
                (screenX, screenY) = self.ConvertToScreenCoords((r, c))
                screenX = screenX + self.square_size / 2
                screenY = screenY + self.square_size / 2
                notation = chessboard_obj.ConvertToAlgebraicNotation_col(c)
                renderedLine = self.fontDefault.render(notation, antialias,
                                                       color)
                self.screen.blit(renderedLine, (screenX, screenY))

        #left and right - display rows
        for r in range(boardSize):
            for c in [-1, boardSize]:
                (screenX, screenY) = self.ConvertToScreenCoords((r, c))
                screenX = screenX + self.square_size / 2
                screenY = screenY + self.square_size / 2
                notation = chessboard_obj.ConvertToAlgebraicNotation_row(r)
                renderedLine = self.fontDefault.render(notation, antialias,
                                                       color)
                self.screen.blit(renderedLine, (screenX, screenY))

        #highlight squares if specified
        for square in highlightSquares:
            (screenX, screenY) = self.ConvertToScreenCoords(square)
            self.screen.blit(self.cyan_square, (screenX, screenY))

        #draw pieces
        for r in range(boardSize):
            for c in range(boardSize):
                (screenX, screenY) = self.ConvertToScreenCoords((r, c))
                if board[r][c] == 'bP':
                    self.screen.blit(self.black_pawn, (screenX, screenY))
                if board[r][c] == 'bR':
                    self.screen.blit(self.black_rook, (screenX, screenY))
                if board[r][c] == 'bT':
                    self.screen.blit(self.black_knight, (screenX, screenY))
                if board[r][c] == 'bB':
                    self.screen.blit(self.black_bishop, (screenX, screenY))
                if board[r][c] == 'bQ':
                    self.screen.blit(self.black_queen, (screenX, screenY))
                if board[r][c] == 'bK':
                    self.screen.blit(self.black_king, (screenX, screenY))
                if board[r][c] == 'wP':
                    self.screen.blit(self.white_pawn, (screenX, screenY))
                if board[r][c] == 'wR':
                    self.screen.blit(self.white_rook, (screenX, screenY))
                if board[r][c] == 'wT':
                    self.screen.blit(self.white_knight, (screenX, screenY))
                if board[r][c] == 'wB':
                    self.screen.blit(self.white_bishop, (screenX, screenY))
                if board[r][c] == 'wQ':
                    self.screen.blit(self.white_queen, (screenX, screenY))
                if board[r][c] == 'wK':
                    self.screen.blit(self.white_king, (screenX, screenY))

        pygame.display.flip()

    def EndGame(self, board):
        self.PrintMessage("Press any key to exit.")
        self.Draw(board)  #draw board to show end game status
        pygame.event.set_blocked(MOUSEMOTION)
        while 1:
            e = pygame.event.wait()
            if e.type is KEYDOWN:
                pygame.quit()
                sys.exit(0)
            if e.type is QUIT:
                pygame.quit()
                sys.exit(0)

    def GetPlayerInput(self, board, currentColor):
        #returns ((from_row,from_col),(to_row,to_col))
        fromSquareChosen = 0
        toSquareChosen = 0
        while not fromSquareChosen or not toSquareChosen:
            squareClicked = []
            pygame.event.set_blocked(MOUSEMOTION)
            e = pygame.event.wait()
            if e.type is KEYDOWN:
                if e.key is K_ESCAPE:
                    fromSquareChosen = 0
                    fromTuple = []
            if e.type is MOUSEBUTTONDOWN:
                (mouseX, mouseY) = pygame.mouse.get_pos()
                squareClicked = self.ConvertToChessCoords((mouseX, mouseY))
                if squareClicked[0] < 0 or squareClicked[
                        0] > 7 or squareClicked[1] < 0 or squareClicked[1] > 7:
                    squareClicked = []  #not a valid chess square
            if e.type is QUIT:  #the "x" kill button
                pygame.quit()
                sys.exit(0)

            if not fromSquareChosen and not toSquareChosen:
                self.Draw(board)
                if squareClicked != []:
                    (r, c) = squareClicked
                    if currentColor == 'black' and 'b' in board[r][c]:
                        if len(
                                self.Rules.GetListOfValidMoves(
                                    board, currentColor, squareClicked)) > 0:
                            fromSquareChosen = 1
                            fromTuple = squareClicked
                    elif currentColor == 'white' and 'w' in board[r][c]:
                        if len(
                                self.Rules.GetListOfValidMoves(
                                    board, currentColor, squareClicked)) > 0:
                            fromSquareChosen = 1
                            fromTuple = squareClicked

            elif fromSquareChosen and not toSquareChosen:
                possibleDestinations = self.Rules.GetListOfValidMoves(
                    board, currentColor, fromTuple)
                self.Draw(board, possibleDestinations)
                if squareClicked != []:
                    (r, c) = squareClicked
                    if squareClicked in possibleDestinations:
                        toSquareChosen = 1
                        toTuple = squareClicked
                    elif currentColor == 'black' and 'b' in board[r][c]:
                        if squareClicked == fromTuple:
                            fromSquareChosen = 0
                        elif len(
                                self.Rules.GetListOfValidMoves(
                                    board, currentColor, squareClicked)) > 0:
                            fromSquareChosen = 1
                            fromTuple = squareClicked
                        else:
                            fromSquareChosen = 0  #piece is of own color, but no possible moves
                    elif currentColor == 'white' and 'w' in board[r][c]:
                        if squareClicked == fromTuple:
                            fromSquareChosen = 0
                        elif len(
                                self.Rules.GetListOfValidMoves(
                                    board, currentColor, squareClicked)) > 0:
                            fromSquareChosen = 1
                            fromTuple = squareClicked
                        else:
                            fromSquareChosen = 0
                    else:  #blank square or opposite color piece not in possible destinations clicked
                        fromSquareChosen = 0

        return (fromTuple, toTuple)

    def GetClickedSquare(self, mouseX, mouseY):
        #test function
        print "User clicked screen position x =", mouseX, "y =", mouseY
        (row, col) = self.ConvertToChessCoords((mouseX, mouseY))
        if col < 8 and col >= 0 and row < 8 and row >= 0:
            print "  Chess board units row =", row, "col =", col

    def TestRoutine(self):
        #test function
        pygame.event.set_blocked(MOUSEMOTION)
        while 1:
            e = pygame.event.wait()
            if e.type is QUIT:
                return
            if e.type is KEYDOWN:
                if e.key is K_ESCAPE:
                    pygame.quit()
                    return
            if e.type is MOUSEBUTTONDOWN:
                (mouseX, mouseY) = pygame.mouse.get_pos()
                #x is horizontal, y is vertical
                #(x=0,y=0) is upper-left corner of the screen
                self.GetClickedSquare(mouseX, mouseY)
class PythonChessMain:
    def __init__(self, options):
        if 'd' in options:
            self.Board = ChessBoard(2)
            self.debugMode = True
        else:
            self.Board = ChessBoard(
                0
            )  #0 for normal board setup; see ChessBoard class for other options (for testing purposes)
            self.debugMode = False

        self.Rules = ChessRules()

    def SetUp(self, options):
        #gameSetupParams: Player 1 and 2 Name, Color, Human/AI level
        if self.debugMode:
            player1Name = 'Steve'
            player1Type = 'human'
            player1Color = 'white'
            player2Name = 'Bob'
            player2Type = 'AI'
            player2Color = 'black'
        else:
            GameParams = TkinterGameSetupParams()
            (player1Name, player1Color, player1Type, player2Name, player2Color,
             player2Type) = GameParams.GetGameSetupParams()

        self.player = [0, 0]
        if player1Type == 'human':
            self.player[0] = ChessPlayer(player1Name, player1Color)
        else:
            self.player[0] = ChessAI(player1Name, player1Color)

        if player2Type == 'human':
            self.player[1] = ChessPlayer(player2Name, player2Color)
        else:
            self.player[1] = ChessAI(player2Name, player2Color)

        #create the gui object - didn't do earlier because pygame conflicts with any gui manager (Tkinter, WxPython...)
        if 't' in options:
            self.guitype = 'text'
            self.Gui = ChessGUI_text()
        else:
            self.guitype = 'pygame'
            if 'o' in options:
                self.Gui = ChessGUI_pygame(0)
            else:
                self.Gui = ChessGUI_pygame(1)

    def MainLoop(self):
        currentPlayerIndex = 0
        turnCount = 0
        while not self.Rules.IsCheckmate(
                self.Board.GetState(), self.player[currentPlayerIndex].color):
            board = self.Board.GetState()
            currentColor = self.player[currentPlayerIndex].GetColor()
            #hardcoded so that player 1 is always white
            if currentColor == 'white':
                turnCount = turnCount + 1
            self.Gui.Draw(board)
            self.Gui.PrintMessage("")
            self.Gui.PrintMessage("-----------TURN " + str(turnCount) + " - " +
                                  self.player[currentPlayerIndex].GetName() +
                                  " (" + currentColor + ")-----------")
            if self.Rules.IsInCheck(board, currentColor):
                self.Gui.PrintMessage(
                    "Warning..." + self.player[currentPlayerIndex].GetName() +
                    " (" + self.player[currentPlayerIndex].GetColor() +
                    ") is in check!")

            if self.player[currentPlayerIndex].GetType() == 'AI':
                moveTuple = self.player[currentPlayerIndex].GetMove(
                    self.Board.GetState(), currentColor)
            else:
                moveTuple = self.Gui.GetPlayerInput(board, currentColor)
            moveReport = self.Board.MovePiece(
                moveTuple
            )  #moveReport = string like "White Bishop moves from A1 to C3" (+) "and captures ___!"
            self.Gui.PrintMessage(moveReport)
            currentPlayerIndex = (
                currentPlayerIndex + 1
            ) % 2  #this will cause the currentPlayerIndex to toggle between 1 and 0

        self.Gui.PrintMessage("CHECKMATE!")
        winnerIndex = (currentPlayerIndex + 1) % 2
        self.Gui.PrintMessage(self.player[winnerIndex].GetName() + " (" +
                              self.player[winnerIndex].GetColor() +
                              ") won the game!")
        self.Gui.Draw(board)  #draw board a final time to show the end game
        c = raw_input(
            "Game finished...press any key to quit.")  #pause at the end
        if self.guitype == 'pygame':
            pygame.quit()