fortunes-foundation/src/game.odin
2026-10-04 17:58:52 +02:00

757 lines
20 KiB
Odin

package game
import "base:builtin"
import "base:intrinsics"
import "base:runtime"
import "core:c"
import hm "core:container/handle_map"
import "core:container/queue"
import "core:container/topological_sort"
import "core:fmt"
import "core:log"
import "core:math/rand"
import "core:mem"
import "core:slice"
import "core:strings"
import ray "vendor:raylib"
MAJOR_COUNT :: 22
MINOR_COUNT :: 14
TAROT_COUNT :: MAJOR_COUNT + 4 * MINOR_COUNT
CARD_PROPORTIONS :: 4.75 / 2.75
CARD_SIZE :: Vec2{100, 100 * CARD_PROPORTIONS}
CARD_ROUNDNESS :: 0.05
SUIT_TEX_SIZE :: Vec2{128, 128}
COLUMN_COUNT :: 11
ROUNDED_RECT_SEGMENTS :: 6
GAP :: 16
CARD_SEPARATION :: 24
CARD_DAMPING :: 70
AUTO_MOVE_INTERVAL :: 0.2
game: Game
Game :: struct {
run: bool,
assets: map[string]runtime.Load_Directory_File,
static_arena: mem.Arena,
static_arena_data: [1 * mem.Megabyte]byte,
// Allocations here will never be freed
static_allocator: runtime.Allocator,
cards: [TAROT_COUNT]Card,
entities: [TAROT_COUNT]Card_Entity,
state: State,
displayed_state: State,
card_font: ray.Font,
suit_textures: [Suit]ray.Texture,
dragged_card: Maybe(Card_Handle),
dragged_card_position: Vec2,
auto_moves: queue.Queue(Move),
auto_move_cooldown: f32,
}
Vec2 :: [2]f32
Card :: struct {
suit: Suit,
number: i8,
}
Suit :: enum {
Major = 0,
Chalice = 1,
Coin = 2,
Sword = 3,
Wand = 4,
}
Card_Handle :: distinct i8
Card_Entity :: struct {
position: Vec2,
target_position: Vec2,
velocity: Vec2,
is_draggable: bool,
state: Card_State_Kind,
}
Card_State_Kind :: enum {
Idle,
Dragged,
Locked,
}
State :: struct {
columns: [COLUMN_COUNT][dynamic; 32]Card_Handle,
major_low: [dynamic; MAJOR_COUNT]Card_Handle,
major_high: [dynamic; MAJOR_COUNT]Card_Handle,
suits: [4][dynamic; MINOR_COUNT]Card_Handle,
aside: [dynamic; 1]Card_Handle,
}
Move :: struct {
card: Card_Handle,
from: Place,
to: Place,
}
Place :: struct {
kind: Place_Kind,
index: int,
}
Place_Kind :: enum {
Column,
Major_Low,
Major_High,
Suit,
Aside,
}
init :: proc() {
game.run = true
ray.SetConfigFlags({.WINDOW_RESIZABLE, .VSYNC_HINT, .MSAA_4X_HINT})
ray.InitWindow(1600, 900, "Fortune's Foundation")
// NOTE(lilith): Sorting statically included assets
assets := #load_directory("assets")
game.assets = make(
map[string]runtime.Load_Directory_File,
len(assets),
allocator = game.static_allocator,
)
for asset in assets {
game.assets[asset.name] = asset
}
queue.init(&game.auto_moves, 128, game.static_allocator)
suit_texture_files := []string{"chalice.png", "coin.png", "sword.png", "wand.png"}
for file_name, index in suit_texture_files {
suit := Suit(index + 1)
image := ray.LoadImageFromMemory(".png", psz_from_slice(game.assets[file_name].data))
game.suit_textures[suit] = ray.LoadTextureFromImage(image)
ray.GenTextureMipmaps(&game.suit_textures[suit])
ray.SetTextureFilter(game.suit_textures[suit], .TRILINEAR)
}
for number in 0 ..< MAJOR_COUNT {
game.cards[number] = Card {
suit = .Major,
number = i8(number),
}
}
for suit in Suit.Chalice ..= Suit.Wand {
suit_offset := MAJOR_COUNT + (int(suit) - 1) * MINOR_COUNT
for number in 1 ..= MINOR_COUNT {
game.cards[suit_offset + number - 1] = Card {
suit = suit,
number = i8(number),
}
}
}
game.card_font = ray.LoadFontFromMemory(
".ttf",
psz_from_slice(game.assets["Besley-Bold.ttf"].data),
fontSize = 24,
codepoints = nil,
codepointCount = 0,
)
state_init(&game.state)
for &obj in game_cards_zipped() {
obj.entity.position = card_position({.Column, 5})
obj.entity.is_draggable = true
}
game.displayed_state = game.state
log.infof("%#v", game.state)
}
update :: proc() {
free_all(context.temp_allocator)
delta := ray.GetFrameTime()
ray.BeginDrawing(); defer ray.EndDrawing()
ray.ClearBackground({30, 50, 40, 255})
for &entity in game.entities {entity.is_draggable = false}
for &column in game.state.columns {
if len(column) > 0 {
game.entities[int(slice.last(column[:]))].is_draggable = true
}
}
if len(game.state.aside) > 0 {
game.entities[game.state.aside[0]].is_draggable = true
}
mouse_position := ray.GetMousePosition()
game.dragged_card_position = mouse_position - CARD_SIZE * 0.5
if ray.IsMouseButtonPressed(.LEFT) {
for &obj, index in game_cards_zipped() {
handle := Card_Handle(index)
if rect_contains(rrect_from_pos_sz(obj.entity.position, CARD_SIZE), mouse_position) &&
game.entities[int(handle)].is_draggable {
game.dragged_card = handle
obj.entity.state = .Dragged
break
}
}
}
if dragged_card, ok := game.dragged_card.?; ok {
obj := &game_cards_zipped()[int(dragged_card)]
if ray.IsMouseButtonReleased(.LEFT) {
old_place := state_card_place(&game.state, dragged_card)
new_place := place_from_position(mouse_position)
move := Move {
from = old_place,
to = new_place,
card = dragged_card,
}
effects, ok := state_perform_move(&game.state, move)
obj.entity.state = .Idle
game.dragged_card = nil
for auto_move in effects {
queue.push(&game.auto_moves, auto_move)
auto_obj := &game_cards_zipped()[int(auto_move.card)]
auto_obj.entity.state = .Locked
}
}
}
game.auto_move_cooldown -= ray.GetFrameTime()
if game.auto_move_cooldown <= 0 {
if auto_move, ok := queue.pop_front_safe(&game.auto_moves); ok {
game.auto_move_cooldown = AUTO_MOVE_INTERVAL
state_apply_single_move(&game.displayed_state, auto_move)
}
}
game.auto_move_cooldown = max(0, game.auto_move_cooldown)
if queue.len(game.auto_moves) == 0 {
for &entity in game.entities {
if entity.state == .Locked {entity.state = .Idle}
}
}
// NOTE(lilith): Draw slots and set card target positions
slot_draw(card_position({.Major_Low, 0}))
for handle in game.displayed_state.major_low {
game.entities[int(handle)].target_position = card_position({.Major_Low, 0})
}
slot_draw(card_position({.Major_High, 0}))
for handle in game.displayed_state.major_high {
game.entities[int(handle)].target_position = card_position({.Major_High, 0})
}
for suit in Suit.Chalice ..= Suit.Wand {
suit_index := int(suit) - 1
suit_position := card_position({.Suit, suit_index})
slot_draw(suit_position)
icon_size :: Vec2{40, 40}
ray.DrawTexturePro(
game.suit_textures[suit],
source = rrect_from_pos_sz({0, 0}, SUIT_TEX_SIZE),
dest = rrect_from_pos_sz(suit_position + CARD_SIZE * 0.5 - icon_size * 0.5, icon_size),
origin = {0, 0},
rotation = 0,
tint = {255, 255, 255, 100},
)
for handle in game.displayed_state.suits[suit_index] {
game.entities[int(handle)].target_position = suit_position
}
}
for column, column_index in game.displayed_state.columns {
slot_draw(card_position({.Column, column_index}))
for handle, cc_index in column {
position := card_position({.Column, column_index}, cc_index)
game.entities[int(handle)].target_position = position
}
}
// NOTE(lilith): Update card transforms
for &obj in game_cards_zipped() {
entity := &obj.entity
target_position :=
obj.entity.state != .Dragged ? entity.target_position : game.dragged_card_position
entity.position, entity.velocity = critical_spring_vec2(
entity.position,
entity.velocity,
target_position,
dt = delta,
)
}
// NOTE(lilith): Draw cards
for handle in game.displayed_state.major_low {
card_draw(handle)
}
for handle in game.displayed_state.major_high {
card_draw(handle)
}
for suit in Suit.Chalice ..= Suit.Wand {
suit_index := int(suit) - 1
for handle in game.displayed_state.suits[suit_index] {
card_draw(handle)
}
}
if len(game.displayed_state.aside) > 0 {
card_draw(game.displayed_state.aside[0])
}
for column, column_index in game.displayed_state.columns {
for handle, cc_index in column {
card_draw(handle)
}
}
if handle, ok := game.dragged_card.?; ok {
card_draw(handle)
}
}
slot_draw :: proc(position: Vec2) {
ray.DrawRectangleRounded(
rrect_from_pos_sz(position, CARD_SIZE),
CARD_ROUNDNESS,
ROUNDED_RECT_SEGMENTS,
color = ray.Color{0, 0, 0, 90},
)
}
card_draw :: proc(handle: Card_Handle) {
obj := game_cards_zipped()[int(handle)]
card := obj.card
entity := obj.entity
ray.DrawRectangleRounded(
rrect_from_pos_sz(entity.position, CARD_SIZE),
CARD_ROUNDNESS,
ROUNDED_RECT_SEGMENTS,
color = background_color(card),
)
ray.DrawRectangleRoundedLinesEx(
rrect_from_pos_sz(entity.position, CARD_SIZE),
CARD_ROUNDNESS,
ROUNDED_RECT_SEGMENTS,
lineThick = 2,
color = outline_color(card),
)
text := strings.clone_to_cstring(short_title(card), context.temp_allocator)
font_size := f32(24)
text_size := ray.MeasureTextEx(game.card_font, text, font_size, spacing = 0)
offset: Vec2
#partial switch card.suit {
case .Major:
offset = {(CARD_SIZE.x - text_size.x) * 0.5, 0}
case:
offset = {4, 0}
}
ray.DrawTextEx(
game.card_font,
text,
position = entity.position + offset,
fontSize = font_size,
spacing = 0,
tint = text_color(card),
)
if card.suit != .Major {
ray.DrawTexturePro(
game.suit_textures[card.suit],
source = rrect_from_pos_sz({0, 0}, SUIT_TEX_SIZE),
dest = rrect_from_pos_sz(
entity.position + offset + {text_size.x, 3},
text_size.yy * 0.7,
),
origin = {0, 0},
rotation = 0,
tint = text_color(card),
)
}
}
state_init :: proc(state: ^State) {
deck := [TAROT_COUNT]Card_Handle{}
for &handle, index in deck {handle = Card_Handle(index)}
rand.shuffle(deck[:])
target_column: int
for handle, index in deck {
append(&state.columns[target_column], handle)
target_column += 1
if target_column == 5 {target_column += 1}
if target_column >= COLUMN_COUNT {target_column = 0}
}
for column, column_index in game.state.columns {
for handle, cc_index in column {
position := card_position({.Column, column_index}, cc_index)
obj := &game_cards_zipped()[int(handle)]
obj.entity.target_position = position
}
}
}
state_perform_move :: proc(
state: ^State,
move: Move,
allocator := context.allocator,
) -> (
auto_moves: [dynamic]Move,
ok: bool,
) {
if !state_apply_single_move(state, move) {return nil, false}
auto_moves = make([dynamic]Move, allocator = allocator)
append(&auto_moves, move)
if move.from.kind == .Column && move.to.kind == .Column {
from_col := &state.columns[move.from.index]
last_moved_handle := move.card
last_moved_card := card_from_handle(move.card)
for len(from_col) > 0 {
next_handle := slice.last(from_col[:])
next_card := card_from_handle(next_handle)
if next_card.suit == last_moved_card.suit &&
abs(next_card.number - last_moved_card.number) == 1 {
next_move := move
next_move.card = next_handle
state_apply_single_move(state, next_move)
append(&auto_moves, next_move)
} else {break}
}
}
state_get_auto_moves(state, &auto_moves)
return auto_moves, true
}
state_get_auto_moves :: proc(state: ^State, auto_moves: ^[dynamic]Move) {
}
state_apply_single_move :: proc(state: ^State, move: Move) -> (ok: bool) {
if !state_is_move_valid(state, move) {return false}
moved_card, pop_ok := state_pop(state, move.from)
assert(pop_ok)
assert(moved_card == move.card)
state_push(state, move.to, moved_card)
return true
}
state_pop :: proc(state: ^State, place: Place) -> (handle: Card_Handle, ok: bool) {
switch place.kind {
case .Column:
return pop_safe(&state.columns[place.index])
case .Major_Low:
return pop_safe(&state.major_low)
case .Major_High:
return pop_safe(&state.major_high)
case .Suit:
return pop_safe(&state.suits[place.index])
case .Aside:
return pop_safe(&state.aside)
}
unreachable()
}
state_push :: proc(state: ^State, place: Place, handle: Card_Handle) {
switch place.kind {
case .Column:
append(&state.columns[place.index], handle)
case .Major_Low:
append(&state.major_low, handle)
case .Major_High:
append(&state.major_high, handle)
case .Suit:
append(&state.suits[place.index], handle)
case .Aside:
append(&state.aside, handle)
}
}
state_is_move_valid :: proc(state: ^State, move: Move) -> (ok: bool) {
if move.from == move.to {return false}
moved_card := card_from_handle(move.card)
from_pile := state_get_pile(state, move.from)
if len(from_pile) == 0 {return false}
if slice.last(from_pile) != move.card {return false}
to_pile := state_get_pile(state, move.to)
switch move.to.kind {
case .Column:
if len(to_pile) == 0 {return true}
top_card := card_from_handle(slice.last(to_pile))
return top_card.suit == moved_card.suit && abs(top_card.number - moved_card.number) == 1
case .Major_Low:
if moved_card.suit != .Major {return false}
if len(to_pile) == 0 {return moved_card.number == 0}
return card_from_handle(slice.last(to_pile)).number == moved_card.number - 1
case .Major_High:
if moved_card.suit != .Major {return false}
if len(to_pile) == 0 {return moved_card.number == MAJOR_COUNT - 1}
return card_from_handle(slice.last(to_pile)).number == moved_card.number + 1
case .Suit:
if len(state.aside) > 0 {return false}
if int(moved_card.suit) - 1 != move.to.index {return false}
if len(to_pile) == 0 {return moved_card.number == 1}
return card_from_handle(slice.last(to_pile)).number == moved_card.number - 1
case .Aside:
return len(to_pile) == 0
}
unreachable()
}
state_get_pile :: proc(state: ^State, place: Place) -> (pile: []Card_Handle) {
switch place.kind {
case .Column:
assert(0 <= place.index && place.index < COLUMN_COUNT)
return state.columns[place.index][:]
case .Major_Low:
return state.major_low[:]
case .Major_High:
return state.major_high[:]
case .Suit:
assert(0 <= place.index && place.index < 4)
return state.suits[place.index][:]
case .Aside:
return state.aside[:]
}
unreachable()
}
state_card_place :: proc(state: ^State, handle: Card_Handle) -> Place {
for column_index in 0 ..< COLUMN_COUNT {
if slice.contains(state.columns[column_index][:], handle) {return {.Column, column_index}}
}
if slice.contains(state.major_low[:], handle) {return {.Major_Low, 0}}
if slice.contains(state.major_high[:], handle) {return {.Major_High, 0}}
for suit in 0 ..< 4 {
if slice.contains(state.suits[suit][:], handle) {return {.Suit, suit}}
}
if slice.contains(state.aside[:], handle) {return {.Aside, 0}}
unreachable()
}
card_from_handle :: proc(handle: Card_Handle) -> Card {return game.cards[int(handle)]}
card_position :: proc(place: Place, pile_index: int = 0) -> (position: Vec2) {
global_offset := Vec2{GAP, GAP}
top_section_offset := global_offset
column_section_offset := global_offset + Vec2{0, CARD_SIZE.y + 2 * GAP}
suits_section_offset := global_offset + Vec2{7 * (CARD_SIZE.x + GAP), 0}
switch place.kind {
case .Column:
column_offset := Vec2{f32(place.index) * (CARD_SIZE.x + GAP), 0} + column_section_offset
return Vec2{0, f32(pile_index) * CARD_SEPARATION} + column_offset
case .Major_Low:
return top_section_offset
case .Major_High:
return top_section_offset + Vec2{CARD_SIZE.x + GAP, 0}
case .Suit:
return suits_section_offset + Vec2{f32(place.index) * (CARD_SIZE.x + GAP), 0}
case .Aside:
return suits_section_offset + Vec2{1.5 * (CARD_SIZE.x + GAP), 0}
}
unreachable()
}
place_from_position :: proc(p: Vec2) -> (place: Place) {
for column_index in 0 ..< COLUMN_COUNT {
place := Place{.Column, column_index}
pos := card_position(place)
rect := rrect_from_pos_sz(pos, {CARD_SIZE.x, 10000})
if rect_contains(rect, p) {return place}
}
for place in ([]Place{{.Major_Low, 0}, {.Major_High, 0}, {.Suit, 0}, {.Suit, 1}, {.Suit, 2}, {.Suit, 3}}) {
pos := card_position(place)
rect := rrect_from_pos_sz(pos, CARD_SIZE)
if rect_contains(rect, p) {return place}
}
return {}
}
card_is_draggable :: proc(handle: Card_Handle) -> bool {
return game.entities[int(handle)].is_draggable
}
index_from_card :: proc(card: Card) -> int {
suit_offset: int
switch card.suit {
case .Major:
suit_offset = 0
case .Chalice:
suit_offset = MAJOR_COUNT
case .Coin:
suit_offset = MAJOR_COUNT + 1 * MINOR_COUNT
case .Sword:
suit_offset = MAJOR_COUNT + 2 * MINOR_COUNT
case .Wand:
suit_offset = MAJOR_COUNT + 3 * MINOR_COUNT
}
number_offset := card.suit == .Major ? card.number : card.number - 1
return suit_offset + int(number_offset)
}
game_cards_zipped :: proc() -> #soa[]struct {
card: Card,
entity: Card_Entity,
} {
return soa_zip(card = game.cards[:], entity = game.entities[:])
}
text_color :: proc(card: Card) -> ray.Color {
switch card.suit {
case .Major:
// return ray.Color{250, 220, 120, 255}
return ray.Color{250, 230, 190, 255}
case .Chalice:
return ray.Color{20, 50, 70, 255}
case .Coin:
return ray.Color{12, 90, 10, 255}
case .Sword:
return ray.Color{100, 90, 0, 255}
case .Wand:
return ray.Color{80, 0, 0, 255}
}
unreachable()
}
background_color :: proc(card: Card) -> ray.Color {
switch card.suit {
case .Major:
return ray.Color{0, 0, 0, 255}
case .Chalice, .Coin, .Sword, .Wand:
return ray.Color{250, 240, 235, 255}
}
unreachable()
}
outline_color :: proc(card: Card) -> ray.Color {
return text_color(card)
// switch card.suit {
// case .Major:
// return ray.Color{250, 230, 190, 255}
// case .Chalice:
// return ray.Color{20, 50, 70, 255}
// case .Coin:
// return ray.Color{12, 90, 10, 255}
// case .Sword:
// return ray.Color{90, 80, 50, 255}
// case .Wand:
// return ray.Color{80, 0, 0, 255}
// }
// unreachable()
}
short_title :: proc(card: Card) -> string {
suit_name: string
switch card.suit {
case .Major:
return fmt.tprintf("%d", card.number)
case .Chalice:
suit_name = "Chalices"
case .Coin:
suit_name = "Coins"
case .Sword:
suit_name = "Swords"
case .Wand:
suit_name = "Wands"
}
number_name: string
switch card.number {
case 1:
number_name = "A"
case 11:
number_name = "P"
case 12:
number_name = "J"
case 13:
number_name = "Q"
case 14:
number_name = "K"
case:
return fmt.tprintf("%d", card.number)
}
return number_name
}
// In a web build, this is called when browser changes size. Remove the
// `ray.SetWindowSize` call if you don't want a resizable game.
parent_window_size_changed :: proc(w, h: int) {
ray.SetWindowSize(c.int(w), c.int(h))
}
shutdown :: proc() {
ray.CloseWindow()
}
should_run :: proc() -> bool {
when ODIN_OS != .JS {
// Never run this proc in browser. It contains a 16 ms sleep on web!
if ray.WindowShouldClose() {
game.run = false
}
}
return game.run
}
rrect_from_pos_sz :: proc(pos: Vec2, sz: Vec2) -> ray.Rectangle {
return {pos.x, pos.y, sz.x, sz.y}
}
psz_from_slice :: proc(slice: []$T) -> (rawptr, i32) {
return raw_data(slice), i32(len(slice))
}
import "core:math"
critical_spring_scalar :: proc(
position: f32,
velocity: f32,
goal_position: f32,
goal_velocity: f32,
damping: f32,
dt: f32,
) -> (
new_position: f32,
new_velocity: f32,
) {
y := damping / 2
c := goal_position + (damping * goal_velocity / (damping * damping / 4))
o := position - c
j1 := velocity + (o * y)
exponential := math.exp(-y * dt)
new_position = (exponential * (o + (j1 * dt))) + c
new_velocity = exponential * (velocity - (j1 * y * dt))
return
}
critical_spring_vec2 :: proc(
position: Vec2,
velocity: Vec2,
goal_position: Vec2,
goal_velocity: Vec2 = Vec2{},
damping: f32 = CARD_DAMPING,
dt: f32 = 1,
) -> (
new_position: Vec2,
new_velocity: Vec2,
) {
new_position.x, new_velocity.x = critical_spring_scalar(
position.x,
velocity.x,
goal_position.x,
goal_velocity.x,
damping,
dt,
)
new_position.y, new_velocity.y = critical_spring_scalar(
position.y,
velocity.y,
goal_position.y,
goal_velocity.y,
damping,
dt,
)
return
}
rect_contains :: proc(rect: ray.Rectangle, p: Vec2) -> bool {
return(
rect.x <= p.x &&
p.x <= rect.x + rect.width &&
rect.y <= p.y &&
p.y <= rect.y + rect.height \
)
}