pixelfaucet/examples/procedural.cr

70 lines
1.9 KiB
Crystal
Raw Permalink Normal View History

2022-01-23 22:20:47 +01:00
require "../src/game"
require "../src/lehmer32"
module PF
class Proceedural < Game
@buffer_size : Int32
@buffer : Pointer(UInt32)
@pan : PF2d::Vec2(Float64) = PF2d::Vec[0.0, 0.0]
2022-01-23 22:20:47 +01:00
@seed : UInt32
@font = Pixelfont::Font.new("#{__DIR__}/../lib/pixelfont/fonts/pixel-5x7.txt")
2022-01-23 22:20:47 +01:00
def initialize(*args, **kwargs)
super
@buffer_size = width * height
@buffer = screen.pixel_pointer(0, 0)
@random = Lehmer32.new
@redraw = true
@controller = Controller(Keys).new({
Keys::LEFT => "left",
Keys::RIGHT => "right",
Keys::UP => "up",
Keys::DOWN => "down",
2022-01-23 22:20:47 +01:00
})
plug_in @controller
2022-01-23 22:20:47 +01:00
@speed = 100.0
@seed = str_to_seed("PixelFaucet")
end
def str_to_seed(str : String)
str.chars.map { |c| c.ord.to_u32! }.reduce(&.+)
end
def update(dt)
@redraw = true if @controller.any_held?
2022-01-23 22:20:47 +01:00
@pan.x += @speed * dt if @controller.held?("right")
@pan.x -= @speed * dt if @controller.held?("left")
@pan.y -= @speed * dt if @controller.held?("up")
@pan.y += @speed * dt if @controller.held?("down")
end
def draw
if @redraw
@redraw = false
start = elapsed_milliseconds
2022-01-23 22:20:47 +01:00
0.upto(height) do |y|
0.upto(width) do |x|
seed = ((@pan.x.to_u32! &+ x).to_u32! & 0xFFFF) << 16 | ((@pan.y.to_u32! &+ y).to_u32! & 0xFFFF)
@random.new_seed(seed)
n = (y * width + x)
if @random.rand(0..100) > 98
b = @random.rand(0u8..0xFFu8)
(@buffer + n).value = Pixel.new(b, b, b).to_u32
else
2022-03-30 04:54:31 +02:00
(@buffer + n).value = Pixel::Black.to_u32
2022-01-23 22:20:47 +01:00
end
end
end
time = elapsed_milliseconds - start
draw_string("frame: #{time.round(2)}ms", 5, 5, @font, Pixel::White)
2022-01-23 22:20:47 +01:00
end
end
end
end
PF::Proceedural.new(400, 300, 3).run!