-
Notifications
You must be signed in to change notification settings - Fork 0
/
historyOfGameResults.nim
189 lines (143 loc) · 5.98 KB
/
historyOfGameResults.nim
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
import
anarchyParameters,
log
import std/[
strutils,
strformat,
os,
random
]
type HistoryOfGameResults = object
sumOpponentRating: float = 1500.0
sumScore: float = 0.5
numGames: int = 0
let
baseLockFileName = "lockFile_historyOfGameResults"
unlockedFileName = baseLockFileName & ".unlocked"
lockedFileName = baseLockFileName & ".locked." & $getCurrentProcessId()
expectedMoveError = "No such file or directory"
func getBaseDir(fileName: string): string =
doAssert fileName.len > 0 and fileName[0] == '/', "fileName must be an absolute path"
fileName.splitFile.dir & "/"
proc historyOfGameResultsResetAllLockFiles*(fileName: string) =
let baseDir = getBaseDir fileName
for lockFileName in walkFiles baseDir & baseLockFileName & "*":
removeFile baseDir & lockFileName
writeFile baseDir & unlockedFileName, ""
proc lockFile(fileName: string) =
let
baseDir = getBaseDir fileName
unlockedFileName = baseDir & unlockedFileName
lockedFileName = baseDir & lockedFileName
while true:
try:
moveFile(unlockedFileName, lockedFileName)
logInfo "Moved file: ", unlockedFileName, " -> ", lockedFileName
break
except OSError:
if getCurrentExceptionMsg().len < expectedMoveError.len or expectedMoveError[0..<expectedMoveError.len] != expectedMoveError:
raise
sleep 1000
proc unlockFile(fileName: string) =
let
baseDir = getBaseDir fileName
unlockedFileName = baseDir & unlockedFileName
lockedFileName = baseDir & lockedFileName
doAssert fileExists lockedFileName
moveFile(lockedFileName, unlockedFileName)
logInfo "Moved file: ", lockedFileName, " -> ", unlockedFileName
proc getHistoryOfGameResults(file: File): array[DifficultyLevel, HistoryOfGameResults] =
## each line has the following formatting:
## difficultyLevel sumOpponentRating sumScore numGames
let lines = file.readAll.splitLines
for line in lines:
if line == "":
continue
let words = line.splitWhitespace
doAssert words.len == 4
let difficultyLevelAsInt = words[0].parseInt
doAssert difficultyLevelAsInt in DifficultyLevel.low.int ..
DifficultyLevel.high.int
let difficultyLevel = difficultyLevelAsInt
result[difficultyLevel].sumOpponentRating = words[1].parseFloat
result[difficultyLevel].sumScore = words[2].parseFloat
result[difficultyLevel].numGames = words[3].parseInt
func getElo(hgr: HistoryOfGameResults): float =
let
averageScore = hgr.sumScore / hgr.numGames.float
averageOpponentRating = hgr.sumOpponentRating / hgr.numGames.float
averageOpponentRating + 800.0 * (averageScore - 0.5)
proc writeHistoryOfGameResults(file: File, hgrArray: array[DifficultyLevel, HistoryOfGameResults]) =
var s = ""
for difficultyLevel, hgr in hgrArray:
s &= &"{difficultyLevel} {hgr.sumOpponentRating} {hgr.sumScore} {hgr.numGames}\n"
s &= '\n'
file.write s
proc updateHistoryOfGameResults*(fileName: string, difficultyLevel: DifficultyLevel, opponentElo: float, score: float) =
lockFile fileName
var file = fileName.open(mode = fmReadWriteExisting)
defer:
file.close()
unlockFile fileName
var historyOfGameResults = file.getHistoryOfGameResults
discard reopen(file, fileName, mode = fmWrite)
historyOfGameResults[difficultyLevel].sumOpponentRating += opponentElo
historyOfGameResults[difficultyLevel].sumScore += score
historyOfGameResults[difficultyLevel].numGames += 1
file.writeHistoryOfGameResults historyOfGameResults
proc getDifficultyLevel*(fileName: string, opponentElo: float): DifficultyLevel =
if not fileExists fileName:
lockFile fileName
var file = fileName.open(mode = fmWrite)
defer:
file.close()
unlockFile fileName
var s: array[DifficultyLevel, HistoryOfGameResults]
for difficulty, historyOfGameResults in s.mpairs:
historyOfGameResults = HistoryOfGameResults(
sumOpponentRating: difficulty.difficultyEloEstimate,
sumScore: 0.5,
numGames: 1
)
file.writeHistoryOfGameResults s
doAssert fileExists fileName
lockFile fileName
var file = fileName.open(mode = fmRead)
defer:
file.close()
unlockFile fileName
let historyOfGameResultsSeq = file.getHistoryOfGameResults
const offsetElo = 50.0
let optimalElo = opponentElo + offsetElo
var
bestHigherElo: float = float.high
bestLowerElo: float = float.low
bestHigherDifficulty = DifficultyLevel.high
bestLowerDifficulty = DifficultyLevel.low
highestEloSoFar = 0.0
result = 1.DifficultyLevel
for difficulty, historyOfGameResults in historyOfGameResultsSeq:
var elo = historyOfGameResults.getElo
logInfo fmt"Elo for difficulty {difficulty}: {elo}"
# because we know that the difficulty should be strict monotonically increase
# we need to adjust if that's not the case in our historic results
if highestEloSoFar >= elo:
elo = highestEloSoFar + 50.0
logInfo fmt"Updated elo for difficulty {difficulty}: {elo}"
highestEloSoFar = elo
if elo >= optimalElo and elo < bestHigherElo:
bestHigherElo = elo
bestHigherDifficulty = difficulty
if elo <= optimalElo and elo > bestLowerElo:
bestLowerElo = elo
bestLowerDifficulty = difficulty
logInfo fmt"{optimalElo = }"
logInfo fmt"{bestHigherElo = }"
logInfo fmt"{bestHigherDifficulty = }"
logInfo fmt"{bestLowerElo = }"
logInfo fmt"{bestLowerDifficulty = }"
# we want to choose the level that closer to the optimal elo more often
if rand(bestLowerElo..bestHigherElo) > optimalElo:
result = bestLowerDifficulty
else:
result = bestHigherDifficulty