Creative Commons Licence This work is licensed under a Creative Commons
Attribution-ShareAlike 4.0 International License

Source: gitlab

Snake in Ruby

Andy Balaam
artificialworlds.net/blog

Contents

Snake

Ruby

Functions

def sum x, y
    x + y
end

Classes

class Game
    attr_accessor :grid_size

    def initialize grid_size
        @grid_size = grid_size
    #...
end

Classes

game = Game.new

# Equivalently:
game = Game.new()

Flow control

if v == Up or v == Down
    game.change_dir v
elsif v == Esc
    Gtk.main_quit
else
    puts v
end

Flow control

if is_apple pos then return false end

Flow control

for x in 1..3
    puts x
end
gives:
1
2
3

Blocks

Blocks

5.times { @snake_body.push( last ) }

Blocks

w.connect( "key_press" ) do |widget, event|
    v = event.keyval
    # ...
end

Sugar

Sugar

for x in 1...3
    puts x
end
gives:
1
2

Sugar

size = [ 3, 4 ]

@cr.rectangle 0, 0, *size

# (rectangle takes 4 arguments)

Sugar

@game.snake_body.each do |pos|
    gfx.dot Snake_color, pos
end

Sugar

case @snake_dir
when Up
    x = pos[0]
    y = pos[1] - 1
    # No fallthrough!
when Down
    x = pos[0]
    y = pos[1] + 1
end

Wrinkles

return a   # is not the same as:
return
    a

Wrinkles

Other features

Other features

More info

Patreon! patreon.com/andybalaam
Videos youtube.com/user/ajbalaam
Twitter @andybalaam
Blog artificialworlds.net/blog
Projects artificialworlds.net