knucklebones/states/game/placing.lua

103 lines
3.0 KiB
Lua
Raw Normal View History

2023-08-12 11:36:14 +02:00
include "ai"
function state_game_placing()
--- @type Die
local die
--- @type EventBus
local event_bus
--- @type 'player'|'enemy'
local turn
local placing = false
local waiting = 30
--- Click on a column to place the die
local function place_die(col_id)
if placing then return end
placing = true
local cell_id = 0
for i = 1, 3 do
if PLACED_DICE[turn][col_id][i] == 0 then
cell_id = i
break
end
end
step = "waiting"
addcoroutine(function()
-- move the die to its cell
local cell = get_cell_coords(turn, col_id, cell_id)
die.box = nil
die.angle = die.angle % 360
-- get value closest to 0. e.g. 270 -> -90
if die.angle > 180 then
die.angle = die.angle - 360
end
local tween = Tween.new(0.5, die, { x = cell.x + 3, y = cell.y + 1, angle = 0 }, "outQuad")
repeat
coroutine.yield()
until tween:update(dt)
PLACED_DICE:set(turn, col_id, cell_id, die.value)
-- Animate the dice and update the scores
event_bus:emit(EVENT_REMOVE_DIE)
event_bus:emit(EVENT_SET_STEP, "scoring")
end)
end
---@param self any
---@param _die Die
---@param _event_bus EventBus
---@param _turn 'player'|'enemy'
local _enter = function(self, _die, _event_bus, _turn)
assert(_die, "missing die")
assert(_event_bus, "missing event_bus")
assert(_turn, "missing turn")
die = _die
event_bus = _event_bus
turn = _turn
waiting = 30
placing = false
end
local update = function(self)
waiting = waiting - 1
if turn == "enemy" then
if waiting <= 0 and not placing then
local col = ai_pick_column(PLACED_DICE.enemy, PLACED_DICE.player, die.value)
place_die(col)
end
else -- turn == "player"
-- Highlight the hovered column
local columns = {
get_column_rect(turn, 1),
get_column_rect(turn, 2),
get_column_rect(turn, 3),
}
local col, col_id = table.find(columns, function(c)
return mouse_in_rect(c)
end)
if col then
if PLACED_DICE:has_free_slot(turn, col_id) then
-- draw hovered column
rect(col.x, col.y, col.width, col.height, 14)
-- place the die if clicked
if Input:mouse_released() then
place_die(col_id)
end
end
end
end
-- Redraw the board because the hovered column is drawn on top of it
-- and i'm too lazy to fix this properly.
draw_board()
end
return {
_enter = _enter,
update = update,
}
end