-
Notifications
You must be signed in to change notification settings - Fork 0
/
scores
96 lines (86 loc) · 2.12 KB
/
scores
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
#! /usr/bin/env bash
declare -a SCORES
SCOREDIR="$HOME/.config/hangman"
[[ -d $SCOREDIR ]] || mkdir -p "$SCOREDIR"
score_regex="^(.+)[[:space:]](.+)[[:space:]](.+)$"
score_format="^.*[[:space:]](.+)[[:space:]].+$"
fetch_scores() {
local score
SCOREFILE="$SCOREDIR/.scores_${MODE,,}"
[[ -a $SCOREFILE ]] || return 1
SCORES=()
while read -r score; do
[[ $score =~ ^(.*)[[:space:]](.*)$ ]] &&
SCORES+=("${BASH_REMATCH[1]} ${BASH_REMATCH[2]}")
done < "$SCOREFILE"
[[ -z ${SCORES[*]} ]] && return 1
return 0
}
get_top_score() {
fetch_scores || echo 0
[[ ${SCORES[0]} =~ $score_format ]] &&
echo "${BASH_REMATCH[1]}"
}
compare_scores() {
local len score index insert
insert="$1"
len="${#SCORES[@]}"
[[ -z ${SCORES[*]} ]] && {
[[ $insert ]] && insert_score
return 0
}
POSITION=0
for score in "${SCORES[@]}"; do
[[ $score =~ $score_format ]] && {
score="${BASH_REMATCH[1]}"
if ((SCORE>=score)); then
[[ $insert ]] && insert_score $((POSITION))
return 0
fi
((POSITION++))
((POSITION==9)) && return 1
}
done
[[ $insert ]] && insert_score
return 0
}
insert_score() {
local index len i scores
scores=()
index="$1"
[[ $index ]] || { SCORES+=("$PLAYER $SCORE $TOPWORDSCORE"); return 0; }
len="${#SCORES[@]}"
for ((i=0;i<len;i++)); do
if ((i==index)); then
scores+=("$PLAYER $SCORE $TOPWORDSCORE")
((i<9)) && scores+=("${SCORES[$i]}")
elif ((i<9)); then
scores+=("${SCORES[$i]}")
fi
done
SCORES=("${scores[@]}")
}
write_scores() {
local score
SCOREFILE="$SCOREDIR/.scores_${MODE,,}"
{
for score in "${SCORES[@]}"; do
echo "$score"
done
} > "$SCOREFILE"
}
display_scores() {
local score rank player score topword
fetch_scores || return 1
rank=1
printf "> TOP RANKING - %-7s MODE <\n" "$MODE"
for score in "${SCORES[@]}"; do
[[ $score =~ $score_regex ]] && {
player="${BASH_REMATCH[1]}"
score="${BASH_REMATCH[2]}"
topword="${BASH_REMATCH[3]}"
printf "%02d. %s ---------- %06d | %06d\n" "$rank" "$player" "$score" "$topword"
((rank++))
}
done
}