Coverage for rollnjump/score.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Roll 'n' Jump
2# Written in 2020, 2021 by Samuel Arsac, Hugo Buscemi,
3# Matteo Chencerel, Rida Lali
4# To the extent possible under law, the author(s) have dedicated all
5# copyright and related and neighboring rights to this software to the
6# public domain worldwide. This software is distributed without any warranty.
7# You should have received a copy of the CC0 Public Domain Dedication along
8# with this software. If not, see
9# <http://creativecommons.org/publicdomain/zero/1.0/>.
11"""Gestion du score."""
12import os
13import rollnjump.conf as cf
14import rollnjump.menu as mn
15import rollnjump.utilities as ut
16import rollnjump.player as plyr
18PLAYER = "Player"
19"""Nom par défaut du joueur"""
21NAMEASK = {
22 "fr": "Quel est votre nom ?",
23 "en": "Who are you?"
24}
25"""Message demandant le pseudo du joueur."""
28def init_best_score():
29 """Initialise le fichier `score.txt`."""
30 open(cf.SCORES, "w").close()
33def score(pts):
34 """
35 Afficher le score durant la partie.
37 Parameters
38 ----------
39 pts : int
40 Nombre de points du joueur
41 """
42 font = ut.font(mn.FONT_PIXEL, cf.SCORE_FONT_SIZE)
43 font.set_bold(True)
44 text = font.render("Score: " + str(pts), True, cf.BLACK)
45 cf.DISPLAYSURF.blit(text, (0, 0))
48def score_endgame(pts):
49 """
50 Affiche le score à la fin de la partie.
52 Parameters
53 ----------
54 pts : int
55 Nombre de points du joueur
56 """
57 mn.print_text("Score : " + str(pts), (640, 300), cf.GREY,
58 ut.font(mn.FONT_PIXEL, cf.RESULT_FONT_SIZE), True)
61def winner_endgame():
62 """Affiche le gagnant à la fin de la partie."""
63 if cf.LANG == "fr":
64 message = "Victoire du joueur "
65 message += cf.COLORSTRAD[cf.LANG][plyr.WINNER]
66 else:
67 message = cf.COLORS[plyr.WINNER]
68 message += " player wins!"
69 mn.print_text(message, (640, 250), cf.GREY,
70 ut.font(mn.FONT_PIXEL, cf.RESULT_FONT_SIZE), True)
71 mono = "mono" + cf.COLORS[plyr.WINNER]
72 img_path = os.path.join(cf.ASSETS, "img", mono, mono + "3.png")
73 img = ut.load_image(img_path)
74 w, h = img.get_rect().size
75 scale_factor = 4
76 position = (int(cf.SCREEN_WIDTH / 2 - scale_factor * (w / 2)),
77 int(cf.SCREEN_HEIGHT / 2 - scale_factor * (h / 4)))
78 mn.print_image(img_path, position, scale_factor)
81def get_scores():
82 """
83 Récupère le score sauvegardé dans le scoreboard.
85 Returns
86 -------
87 (int * str) list
88 Une liste contenant un score et un nom de joueur associé
89 """
90 try:
91 with open(cf.SCORES, 'r') as board:
92 scores = board.readlines()
93 if len(scores) < 2:
94 return []
95 scores[0] = scores[0].split(";")
96 scores[1] = scores[1].split(";")
97 ordered_list = []
98 for duo in range(len(scores[0])):
99 if ut.onlydigits(scores[1][duo]) != '':
100 score_value = int(ut.onlydigits(scores[1][duo]))
101 score_name = ut.onlyalphanum(scores[0][duo])
102 element = (score_value, score_name)
103 ordered_list.append(element)
104 ordered_list = list(sorted(ordered_list, key=lambda x: -x[0]))
105 return ordered_list
106 except (ValueError, IndexError):
107 board.close()
108 init_best_score()
109 return []
112def get_last_best_score():
113 """
114 Renvoie le plus petit score du leaderboard.
116 Returns
117 -------
118 int
119 Le score recherché
120 """
121 scores = get_scores()
122 if len(scores) == 0:
123 return 0
124 last = min(scores)
125 return last[0]
128def get_best_score():
129 """
130 Renvoie le meilleur score du leaderboard.
132 Returns
133 -------
134 int
135 Le score recherché
136 """
137 scores = get_scores()
138 if len(scores) == 0:
139 return 0
140 last = max(scores)
141 return last[0]
144def set_best_score(value):
145 """
146 Ajoute un score au leaderboard.
148 Parameters
149 ----------
150 value : int
151 Score à ajouter
152 """
153 scores_board = get_scores()
154 with open(cf.SCORES, "w") as board:
155 must_be_added = True
156 new_scores = ""
157 new_players = ""
158 if len(scores_board) == 0:
159 board.write(PLAYER + "\n" + str(value))
160 else:
161 for i in range(min(len(scores_board), 4)):
162 if must_be_added and scores_board[i][0] < value:
163 new_scores += str(value) + ";"
164 new_players += PLAYER + ";"
165 must_be_added = False
166 new_scores += str(scores_board[i][0]) + ";"
167 new_players += scores_board[i][1] + ";"
168 if must_be_added:
169 new_scores += str(value)
170 new_players += PLAYER
171 board.write(new_players + "\n" + new_scores)
174def maj(pts):
175 """
176 Si le score obtenu est parmi les meilleurs, met à jour le leaderboard.
178 Parameters
179 ----------
180 pts : int
181 Le score obtenu
183 Returns
184 -------
185 bool
186 `True` si le score a été ajouté, `False` sinon
187 """
188 minimal_score = get_last_best_score()
189 if len(get_scores()) < 5 or minimal_score < pts:
190 cf.CAPT = True
191 return True
192 return False
195if not os.path.isfile(cf.SCORES): # pragma: no cover
196 init_best_score()