I wrote a simulator that simulates chess games. The game uses probability to determine the player that is most likely to win. though they might be upsets(a low rated player winning the game). I would love insights and suggestions on how to improve on the algorithm, general review is also welcomed.
NOTE: The names and rating were gotten from chess.com
application and the code were written in jupyter-notebook
"""Chess Game simulator"""
import random
import time
NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson',
'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya',
'Danny', 'Engine']
RATINGS = [600, 900, 400, 700, 1000, 1100,
1300, 1500, 1600, 1800, 2000,
2200, 2300, 2650, 2500, 1000]
class Player:
"""This class holds the player information"""
def __init__(self, name, rating):
self.name = name
self.rating = rating
self.opponent = None
def __repr__(self):
return 'Player({}, {})'.format(self.name, self.rating)
class ChessGame():
def __init__(self, players):
self.players = players
self.tournament_rounds = {1: 'Round 1', 2: 'Round 2', 3: 'Semi-final', 4: 'Final'}
self.game_round = 0
def next_round(self):
"""Go the next round of the tournament"""
self.game_round += 1
try:
print(self.tournament_rounds[self.game_round])
except KeyError:
return
def make_pair(self):
"""Combine two players randomly to play a chess game"""
players = self.players[:]
new_players = []
while players:
player1 = random.choice(players)
players.remove(player1)
player2 = random.choice(players)
players.remove(player2)
player1.opponent = player2
player2.opponent = player1
new_players.append(player1)
self.players = new_players
def game(self):
"""run the simulation"""
if len(self.players) < 2:
print('Exception: Not enough players to play a game')
return
self.next_round()
print('--------------------------------------------')
self.make_pair()
for player in self.players:
print(f'{player.name}({player.rating}) vs {player.opponent.name}({player.opponent.rating})')
time.sleep(3)
print('--------------------------------------------')
self.players = self.score_game()
def score_game(self):
"""Score the game using probabilities"""
winners = []
for player in self.players:
total_rating = player.rating + player.opponent.rating
player_chance = player.rating / total_rating
maximum_range = 1000
player_range = [i for i in range(0, int(player_chance * maximum_range))]
choice = random.randint(0, maximum_range)
if choice in player_range:
print(f'{player.name} wins this round by checkmate')
player.rating += self.game_round * 200
winners.append(player)
else:
print(f'{player.opponent.name} wins this round by checkmate')
player.opponent.rating += self.game_round * 200
winners.append(player.opponent)
return winners
CHESS_PLAYERS = [Player(name, rating) for name, rating in zip(NAMES, RATINGS)]
CHESS_SIM = ChessGame(CHESS_PLAYERS)
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()