bomberpac/game/entities/bomberman.fnl

71 lines
3 KiB
Fennel

(local util (require :lib.util))
(local dim (require :game.dim))
(local {: direct : move} (util.require :game.entity))
(local {: edge : edge-crosses : vec*} (util.require :game.helpers))
(local map (require :game.tilemap))
(local bomberman (util.hot-table ...))
(set bomberman.keymap {:up :w :down :s :left :a :right :d :bomb :x})
(fn bomberman.draw [entity]
(love.graphics.setColor 0.2 0.2 0.2)
(love.graphics.circle :fill (. entity.pos 1) (. entity.pos 2) (/ dim.tilesize 2)))
(fn tile-at [x y rules]
(-?> [x y]
(map.world-to-tile)
(rules.tile-at)))
(fn bomberman.collides? [[x y] rules]
(let [tile (tile-at x y rules)]
(and tile (or tile.bomb tile.wall))))
(fn bomberman.tile-edge [c dc]
(let [tc (math.floor (/ c dim.tilesize))
cfloor (* tc dim.tilesize)]
(if (= dc 0) c
(> dc 0) (- cfloor dim.halftile)
(+ cfloor dim.tilesize dim.halftile))))
; Collision model for Bomberman works like this (in order):
; * if the moving edge is NOT crossing over a tile boundary, allow the movement
; * if there is no solid tile in in front of Bomberman, allow the movement
; * if there are two solid tiles in front of Bomberman, push Bomberman back onto
; the tile boundary
; * if there is one solid and one empty tile in front of Bomberman, push Bomberman
; back onto the tile boundary, and push Bomberman towards the empty tile in the
; other axis
; repeat for both x and y axis
; TODO: do we add the two vectors? is it acceptable that diagonal movement is faster?
(fn horizontal [x y] (fn [dx dy] [(+ x dx) (+ y dy)]))
(fn vertical [x y] (fn [dy dx] [(+ x dx) (+ y dy)]))
(fn bomberman.axis-movement [off c copp dc rules]
(let [d (fn [cnew] (- cnew c))
(edge-prev edge-next) (edge c dc dim.halftile)
crosses (edge-crosses edge-prev edge-next dim.tilesize)
neg-collides (bomberman.collides? (off (d edge-next) (- dim.halftile)) rules)
pos-collides (bomberman.collides? (off (d edge-next) (- dim.halftile 0.01)) rules)
dc-edge (d (bomberman.tile-edge edge-next dc))
dcopp (math.abs dc)]
(if (not crosses) [dc 0]
(and (not neg-collides) (not pos-collides)) [dc 0]
(and neg-collides pos-collides) [dc-edge 0]
neg-collides [dc-edge (math.min dcopp (- (bomberman.tile-edge (+ copp dim.tilesize (- dim.halftile 0.01)) 1) copp))]
pos-collides [dc-edge (math.max (- dcopp) (- (bomberman.tile-edge (- copp dim.tilesize dim.halftile) -1) copp))])))
(fn bomberman.update [entity dt rules]
(set entity.vel (direct bomberman.keymap (* dim.tilesize 3)))
(let [[x y] entity.pos
[dx dy] (vec* entity.vel dt)
[dx1 dy1] (bomberman.axis-movement (horizontal x y) x y dx rules)
[dy2 dx2] (bomberman.axis-movement (vertical x y) y x dy rules)
[dx dy] (if (not= dx 0) [dx1 dy1] [dx2 dy2])]
(set entity.pos [(+ x dx) (+ y dy)]))
(when (love.keyboard.isDown bomberman.keymap.bomb)
(rules.place-bomb (map.world-to-tile entity.pos))))
(fn bomberman.new [pos]
{: pos :vel [0 0] :draw #(bomberman.draw $...) :update #(bomberman.update $...)})
bomberman.hot