Snake: Difference between revisions

Content added Content deleted
m (→‎{{header|Julia}}: update for Makie changes to Observables)
Line 3,261: Line 3,261:


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang="julia">using GLMakie, GeometryBasics
Makie version in 99 lines.
<syntaxhighlight lang="julia">using Makie


mutable struct SnakeGame
mutable struct SnakeGame
height
height::Int
width
width::Int
snake
snake::Vector{CartesianIndex{2}}
food
food::CartesianIndex{2}
end
end


Line 3,307: Line 3,306:


function play(;n=10,t=0.5)
function play(;n=10,t=0.5)
game = Node(SnakeGame(;width=n,height=n))
game = Observable(SnakeGame(;width=n,height=n))
scene = Scene(resolution = (1000, 1000), raw = true, camera = campixel!)
scene = Scene(resolution = (1000, 1000), raw = true, camera = campixel!)
display(scene)
display(scene)
Line 3,328: Line 3,327:


score_text = @lift("Score: $(length($game.snake)-1)")
score_text = @lift("Score: $(length($game.snake)-1)")
text!(scene, score_text, color=:gray, position = @lift((widths($area)[1]/2, widths($area)[2])), textsize = 50, align = (:center, :top))
text!(scene, score_text, color=:gray, position = @lift((widths($area)[1]/2, widths($area)[2])), fontsize = 50, align = (:center, :top))


direction = Ref{Any}(nothing)
direction = Ref{Any}(nothing)


on(scene.events.keyboardbuttons) do but
on(events(scene).keyboardbutton) do but
if ispressed(but, Keyboard.left)
if but.action == Keyboard.press || but.action == Keyboard.repeat
direction[] = CartesianIndex(-1,0)
if but.key == Keyboard.left
direction[] = CartesianIndex(-1,0)
elseif ispressed(but, Keyboard.up)
direction[] = CartesianIndex(0,1)
elseif but.key == Keyboard.up
direction[] = CartesianIndex(0,1)
elseif ispressed(but, Keyboard.down)
direction[] = CartesianIndex(0,-1)
elseif but.key == Keyboard.down
direction[] = CartesianIndex(0,-1)
elseif ispressed(but, Keyboard.right)
direction[] = CartesianIndex(1,0)
elseif but.key == Keyboard.right
direction[] = CartesianIndex(1,0)
end
end
end
end
end