From 8abe9fdd63721b7b089e8ac29cda711e6a1f36be Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Mon, 19 Jul 2021 12:13:35 -0700 Subject: [PATCH] store camel stack positions (also slower apparently) --- game.nim | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/game.nim b/game.nim index f6e8d8a..9f6aa1b 100644 --- a/game.nim +++ b/game.nim @@ -53,9 +53,13 @@ type camels*: ColorStack tile*: Option[Tile] + CamelPos* = object + square*: range[1..16] + stackIdx*: int8 + Board* = object squares*: array[1..16, Square] - camels*: array[Color, range[1..16]] + camels*: array[Color, CamelPos] diceRolled*: array[Color, bool] leader*: Option[Color] gameOver*: bool @@ -103,13 +107,17 @@ proc setState*(b: var Board; tiles: openArray[tuple[t: Tile, p: int]]) = for (color, dest) in camels: # note that `camels` is ordered, as this determines stacking b[dest].camels.add(color) - b.camels[color] = dest + let height = b[dest].camels.high + b.camels[color] = CamelPos(square: dest, stackIdx: height) for (tile, dest) in tiles: b[dest].tile = some(tile) - let leadCamel = b[max(b.camels)].camels[^1] # top camel in the last currently-occupied space - b.leader = some(leadCamel) + for sq in b.squares: + if sq.camels.len > 0: + let squareLeader = sq.camels[^1] + if b.leader.isNone or b.leader.get != squareLeader: + b.leader = some(squareLeader) proc diceRemaining*(b: Board): ColorStack = @@ -126,7 +134,7 @@ proc resetDice*(b: var Board) = proc advance*(b: var Board, die: Die) = let (color, roll) = die - startPos = b.camels[color] + startPos = b.camels[color].square var endPos = startPos + roll if endPos > 16: # camel has passed the finish line @@ -144,18 +152,18 @@ proc advance*(b: var Board, die: Die) = if prepend: b[startPos].camels.moveSubstackPre(b[endPos].camels, stackStart) let stackLen = b[startPos].camels.len - stackStart - for i in 0 ..< stackLen: + for i in 0'i8 ..< stackLen: # we know how many camels we added to the bottom, so set the position for each of those - b.camels[b[endPos].camels[i]] = endPos + b.camels[b[endPos].camels[i]] = CamelPos(square: endPos, stackIdx: i) # replace with cast later? else: let dstPrevHigh = b[endPos].camels.high b[startPos].camels.moveSubstack(b[endPos].camels, stackStart) # the camels that have moved start immediately after the previous high camel for i in (dstPrevHigh + 1) .. b[endPos].camels.high: - b.camels[b[endPos].camels[i]] = endPos + b.camels[b[endPos].camels[i]] = CamelPos(square: endPos, stackIdx: i) # if we are stacking on or moving past the previous leader - if endPos >= b.camels[b.leader.get]: + if endPos >= b.camels[b.leader.get].square: b.leader = some(b[endPos].camels[^1]) b.diceRolled[color] = true \ No newline at end of file