TDT4109/Exercise 9/10.py

154 lines
6.4 KiB
Python
Raw Normal View History

2020-10-27 23:07:19 +01:00
from os import system
class TicTacToe:
def __init__(self, playerSymbols=['0', 'X']):
self.board = [0 for _ in range(9)]
name1, name2 = self.getUsernames()
self.players = [
{
'name': name1,
'sym': playerSymbols[0],
'num': 1
},
{
'name': name2,
'sym': playerSymbols[1],
'num': 4
}
]
def getUsernames(self):
return [input(f'Spiller {i+1} sitt navn: ') for i in range(2)]
def toPieceArray(self): return \
[ self.players[0]['sym'] if i==self.players[0]['num'] else \
self.players[1]['sym'] if i==self.players[1]['num'] else \
' ' for i in self.board ]
def pieceExistAt(self, pos):
return self.board[pos] == self.players[0]['num'] or self.board[pos] == self.players[1]['num']
def hasWon(self, userId):
getPiecesFromIndexes = lambda indexes: [self.board[i] for i in indexes]
indexesList = [[0,4,8], [1,4,7], [2,4,6], [3,4,5], [0,3,6], [0,1,2], [2,5,8], [6,7,8]]
winningSum = self.players[userId]['num'] * 3
return any([sum(getPiecesFromIndexes(indexes)) == winningSum for indexes in indexesList])
def __str__(self):
pieces = self.toPieceArray()
return """╭───┬───┬───╮
{} {} {}
{} {} {}
{} {} {}
""".format(*pieces)
def selectedBoardAt(self, x, y) -> str:
characterMap = {
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
'': '',
}
pointsToChange = \
[(0 + x * 4, i + y * 2) for i in range(3)] + \
[(4 + x * 4, i + y * 2) for i in range(3)] + \
[(i + x * 4, 0 + y * 2) for i in range(1,4)] + \
[(i + x * 4, 2 + y * 2) for i in range(1,4)]
board = [list(line) for line in str(self).split('\n')]
for x,y in pointsToChange:
board[y][x] = characterMap[board[y][x]]
return '\n'.join([''.join(line) for line in board])
def drawBoard(self, userId, x=-1, y=-1):
system('clear')
print(f'({self.players[userId]["sym"]}) - {self.players[userId]["name"].upper()}\'S TURN\n')
print(self.selectedBoardAt(x,y) if (x,y) != (-1,-1) else str(self))
def selectPiece(self, userId) -> int:
x, y = 0, 0
while True:
self.drawBoard(userId, x,y)
key = input(f" W E\n A S D <- Enter : ")[0]
if key in ['s', 'j'] and y!=2: y+=1
elif key in ['w', 'k'] and y!=0: y-=1
elif key in ['d', 'l'] and x!=2: x+=1
elif key in ['a', 'h'] and x!=0: x-=1
elif key == 'e' and not self.pieceExistAt(3*y + x): return 3*y + x
def youWinTheGameItsHalloweenBois(self, userId):
print(f"""
{self.players[userId]['name']}
""")
def spookyTie(self):
print("""
""")
def checkGameStatus(self,userId):
if self.hasWon(userId):
self.drawBoard(userId)
# print(self.players[userId]['name'], 'has won!')
self.youWinTheGameItsHalloweenBois(userId)
exit(0)
elif not 0 in self.board:
self.drawBoard(userId)
self.spookyTie()
exit(0)
def loop(self):
while True:
piece = self.selectPiece(0)
self.board[piece] = self.players[0]['num']
self.checkGameStatus(0)
piece = self.selectPiece(1)
self.board[piece] = self.players[1]['num']
self.checkGameStatus(1)
if __name__ == "__main__":
game = TicTacToe()
game.loop()
print(game)