Files
flutter_lua_runtime/example/assets/games/ludo/scripts/rules.lua
2026-06-07 22:53:58 +08:00

89 lines
2.0 KiB
Lua

local state = runtime.import("state")
local board = runtime.import("board")
local rules = {}
function rules.next_player()
if state.current_player == "red" then
return "blue"
end
return "red"
end
function rules.next_dice()
state.dice_index = state.dice_index + 1
if state.dice_index > #state.dice_values then
state.dice_index = 1
end
return state.dice_values[state.dice_index]
end
function rules.piece_home_position(piece)
if piece.owner == "red" then
if piece.id == "red_1" then return board.red_home[1] end
return board.red_home[2]
end
if piece.id == "blue_1" then return board.blue_home[1] end
return board.blue_home[2]
end
function rules.can_move(piece, dice)
if piece.status == "home" then
return dice == 6
end
return true
end
function rules.movable_pieces()
local result = {}
for id, piece in pairs(state.pieces) do
if piece.owner == state.current_player and rules.can_move(piece, state.dice) then
table.insert(result, id)
end
end
return result
end
function rules.all_piece_ids()
local result = {}
for id, _ in pairs(state.pieces) do
table.insert(result, id)
end
return result
end
function rules.calculate_path(piece, dice)
local path = {}
if piece.status == "home" then
local start_index = board.start[piece.owner]
local pos = board.path[start_index]
table.insert(path, {x = pos.x, y = pos.y})
return path
end
for i = 1, dice do
local index = piece.path_index + i
while index > #board.path do
index = index - #board.path
end
local pos = board.path[index]
table.insert(path, {x = pos.x, y = pos.y})
end
return path
end
function rules.apply_move(piece, dice)
if piece.status == "home" then
piece.status = "path"
piece.path_index = board.start[piece.owner]
return
end
piece.path_index = piece.path_index + dice
while piece.path_index > #board.path do
piece.path_index = piece.path_index - #board.path
end
end
return rules