I've very recently started using OOP paradigms for the code in my work (academic research). As an exercise I tried coding this quick scoreboard.
I'm not interested in improving the 'display' part, I know there would be a lot to do there, but does my use of classes make any sense?
import os
from numpy import nan, nansum
from matplotlib import interactive
import matplotlib.pyplot as plt
class Player:
def __init__(self, name):
self.name = name
self.score = []
self.cumulative_score = []
self.total_score = 0
def add_score(self, score):
self.score[-1] = score
self.cumulative_score[-1] = self.total_score + score
self.total_score = nansum(self.score)
class ScoreBoard:
def __init__(self):
plt.style.use('ggplot')
interactive(True)
player_name = True
self.players = []
while player_name:
player_name = input('Player name ? ')
if player_name:
self.players += [Player(player_name)]
self.round = 0
self.figure = plt.figure()
self.ax = self.figure.add_subplot(111)
self.plots = {}
for player in self.players:
self.plots[player.name], = plt.plot(range(1, self.round + 1),
player.cumulative_score,
label=player.name, marker='*')
plt.legend()
def new_round(self):
self.round += 1
for player in self.players:
player.score += [nan]
player.cumulative_score += [nan]
for i, player in enumerate(self.players):
self.display()
new_score = input('Score pour {}: '.format(player.name))
if new_score:
player.add_score(int(new_score))
def display(self):
self.ax.clear()
for player in self.players:
self.plots[player.name], = plt.plot(range(1, self.round + 1),
player.cumulative_score,
label=player.name, marker='*')
plt.legend()
os.system('cls' if os.name == 'nt' else 'clear')
print(' \t| '.join(player.name for player in self.players))
print(''.join(['-'] * 80))
for round in range(self.round):
print(' \t| '.join(str(player.score[round]) for player in
self.players))
print(''.join(['-'] * 80))
print(' \t| '.join(str(player.total_score)
for player in self.players))
score_board = ScoreBoard()
while True:
score_board.new_round()