TDT4109/Exercise 10/chess/chess.py

97 lines
3.0 KiB
Python
Raw Normal View History

2020-11-12 23:43:39 +01:00
#!/bin/python3
2020-11-10 23:56:21 +01:00
from os import system
from dataclasses import dataclass
2020-11-12 00:17:02 +01:00
from board import Board
2020-11-12 19:17:16 +01:00
from piece import Piece
2020-11-12 00:17:02 +01:00
2020-11-12 23:43:39 +01:00
2020-11-10 23:56:21 +01:00
@dataclass
class Player:
name: str
color: str
2020-11-12 23:43:39 +01:00
2020-11-10 23:56:21 +01:00
class Chess:
def __init__(self, players):
self.players = players
2020-11-12 19:17:16 +01:00
self.board = Board()
2020-11-10 23:56:21 +01:00
2020-11-12 23:43:39 +01:00
def win(self, player):
if player.color == 'white':
print('''
''')
else:
print('''
''')
2020-11-13 18:48:48 +01:00
input('Press any button to exit...')
2020-11-12 23:43:39 +01:00
exit(0)
def tie(self):
print('''
''')
2020-11-13 18:48:48 +01:00
input('Press any button to exit...')
2020-11-12 23:43:39 +01:00
exit(0)
2020-11-13 18:48:48 +01:00
def promoteIfPossible(self, player, position):
promoteY = 0 if player.color == 'white' else 7
if (piece := self.board.getPieceAt(*position)).type == 'p' and position[1] == promoteY:
while True:
answer = input('What would you like your pawn to become? (q,b,r or n) ')
if answer in 'qbrn' and len(answer) == 1:
break
else:
print('\nCouldn\'t parse input. Try again')
piece.type = answer
2020-11-12 19:17:16 +01:00
def makeMove(self, player):
2020-11-13 18:48:48 +01:00
# Get the first piece belonging to the player
currentPlayersPiece = lambda piece: piece.color == player.color
chosenTile = self.board.getPositionsWhere(currentPlayersPiece)[0]
2020-11-12 19:17:16 +01:00
while True:
piece = self.board.selectPiece(player, *chosenTile)
chosenTile = piece
possibleMoves = Piece.possibleMoves(*piece, self.board)
if move := self.board.selectMove(player, *piece, possibleMoves):
break
self.board.movePiece(piece, move)
2020-11-13 18:48:48 +01:00
self.promoteIfPossible(player, move)
2020-11-12 19:17:16 +01:00
2020-11-12 23:43:39 +01:00
def turn(self, playerNum):
2020-11-12 00:17:02 +01:00
system('clear')
2020-11-12 23:43:39 +01:00
self.makeMove(players[playerNum])
# 1 - 1 = 0 and 1 - 0 = 1
if self.board.checkCheckMate(players[1 - playerNum].color):
self.win(players[playerNum])
elif self.board.checkStaleMate(players[1 - playerNum].color):
self.tie()
2020-11-10 23:56:21 +01:00
def loop(self):
while True:
2020-11-12 23:43:39 +01:00
self.turn(0)
self.turn(1)
2020-11-10 23:56:21 +01:00
if __name__ == "__main__":
players = (
Player('Spiller 1', 'white'),
Player('Spiller 2', 'black'),
)
2020-11-12 19:17:16 +01:00
game = Chess(('Spiller 1', 'Spiller 2'))
game.loop()