-
Notifications
You must be signed in to change notification settings - Fork 0
/
Matboj.py
205 lines (167 loc) · 6.75 KB
/
Matboj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""Ranking system for individual Matboj-style competition."""
import json
import os
import re
import readline # For a nice UNIX-like command line within the program.
import sys
class Person(object):
def __init__(self, name, rank=1000.0, old_ranks=None):
self.name = name
self.rank = rank
self.old_ranks = old_ranks if old_ranks else []
def __lt__(self, other):
return self.rank - other.rank
def update_rank(self, new_rank):
self.old_ranks.append(self.rank)
self.rank = new_rank
def undo(self):
if self.old_ranks:
self.rank = self.old_ranks[-1]
del self.old_ranks[-1]
def to_dict(self):
return {'name': self.name, 'rank': self.rank, 'old_ranks': self.old_ranks}
@classmethod
def from_dict(cls, d):
return Person(name=d['name'], rank=d['rank'], old_ranks=d['old_ranks'])
def load_people(path):
"""Loads a list of people from the path and assigns each default score."""
people = []
with open(path, 'r') as people_file:
for line in people_file.readlines():
people.append(Person(line.strip()))
return people
def print_list(lst, cols=3):
# Make sure the length of the list is an exact multiple of cols.
lst.extend([''] * (-len(lst) % cols))
num_rows = len(lst) // cols
for elements in [lst[i::num_rows] for i in range(num_rows)]:
print(' │ '.join(elements))
def print_error(text):
print(f'\033[91m{text}\033[0m')
def new_ranks(winner, loser):
new_winner_rank = winner.rank + 100 - (winner.rank - loser.rank) / 3
new_loser_rank = loser.rank - 100 - (loser.rank - winner.rank) / 3
return new_winner_rank, new_loser_rank
class Matboj(object):
def __init__(self, people, match_list=None):
self._people = people
self._names_to_people = {p.name: p for p in self._people}
self._match_list = match_list or []
def save_game_state(self):
dirname = os.path.dirname(__file__)
with open(os.path.join(dirname, 'game_state.json'), 'w') as output:
game_state = {
'people': [p.to_dict() for p in
sorted(self._people, key=lambda e: -e.rank)],
'match_list': self._match_list}
output.write(json.dumps(game_state, indent=2))
def load_game_state(self):
dirname = os.path.dirname(__file__)
with open(os.path.join(dirname, 'game_state.json'), 'r') as game_state:
game_state = json.loads(game_state.read())
self._people = [Person.from_dict(p) for p in game_state['people']]
self._names_to_people = {p.name: p for p in self._people}
self._match_list = game_state['match_list']
def print_ranking(self, winner_name=None, loser_name=None):
name_len = max(len(p.name) for p in self._people)
to_print = []
for i, person in enumerate(sorted(self._people, key=lambda e: -e.rank), 1):
name = person.name.ljust(name_len + 1).title()
if person.name == winner_name or person.name == loser_name:
name = f'\033[93m{name}\033[0m'
to_print.append(f'{i:2d}. {name}: {person.rank:4.0f}')
print_list(to_print)
print()
def _undo_match(self, match):
self._names_to_people[match[0]].undo()
self._names_to_people[match[1]].undo()
def undo(self, position):
if not self._match_list:
print_error('Nothing to undo.')
return
if position > len(self._match_list):
print_error(f'Not enough matches ({len(self._match_list)}) to undo '
f'position match at position {position}')
return
position = len(self._match_list) - position + 1
undo_winner_name, undo_loser_name = self._match_list[-position]
answer = input(f'Undo {undo_winner_name}:{undo_loser_name}? [y/n] ').strip()
if answer == 'y':
# Undo all the matches up to the bad one, then redo them since somebody
# has maybe already played with the players whose match we are undoing.
redo_buffer = []
for _ in range(position - 1):
current_match = self._match_list.pop()
redo_buffer.append(current_match)
self._undo_match(current_match)
# Undo the actual bad match.
bad_match = self._match_list.pop()
self._undo_match(bad_match)
# Redo the matches.
for redo_match in redo_buffer:
self.rerank(*redo_match)
print(f'Undo done for {undo_winner_name}:{undo_loser_name}')
self.print_ranking()
def rerank(self, winner_name, loser_name):
winner = self._names_to_people[winner_name.lower()]
loser = self._names_to_people[loser_name.lower()]
new_winner_rank, new_loser_rank = new_ranks(winner=winner, loser=loser)
winner.update_rank(new_winner_rank)
loser.update_rank(new_loser_rank)
self._match_list.append((winner.name, loser.name))
self.save_game_state()
def run(self):
self.print_ranking()
print('Welcome to Matboj! Type "help" to show available commands.')
while True:
command = input('\033[94m$\033[0m\033[92m ').strip()
print('\033[0m', end='')
if command == '':
continue
if command == 'about':
print('Written by Augustin Zidek in 2020.')
elif command in ('quit', 'exit', ':q!'):
self.save_game_state()
exit()
elif command in ('status', 'print'):
self.print_ranking()
elif command == 'matches':
print(', '.join([f'{w}:{l} ({n})'
for n, (w, l) in enumerate(self._match_list, 1)]))
elif command == 'save':
self.save_game_state()
print('Game state saved.')
elif command == 'load':
self.load_game_state()
print('Game state loaded.')
self.print_ranking()
elif command == 'help':
print('Commands: about, quit, print, matches, save, load, undo [num], '
'<winner name>:<loser name>')
elif command == 'undo':
self.undo(position=len(self._match_list))
elif re.match('undo [0-9]+', command):
undo_position = int(re.match('undo ([0-9]+)', command).group(1))
self.undo(position=undo_position)
elif re.match(r'\w+:\w+', command):
winner_name, loser_name = command.split(':')
if winner_name == loser_name:
print_error('The two player names must be distinct.')
continue
elif winner_name not in self._names_to_people:
print_error(f'Unknown winner name: {winner_name.title()}.')
continue
elif loser_name not in self._names_to_people:
print_error(f'Unknown loser name: {loser_name.title()}.')
continue
self.rerank(winner_name=winner_name, loser_name=loser_name)
self.print_ranking(winner_name=winner_name, loser_name=loser_name)
else:
print_error('Unknown command.')
def main(unused_args):
dirname = os.path.dirname(__file__)
people = load_people(os.path.join(dirname, 'people.txt'))
matboj = Matboj(people)
matboj.run()
if __name__ == "__main__":
main(sys.argv)