Skip to content

Instantly share code, notes, and snippets.

@alexyoung
Created April 2, 2009 21:17
Show Gist options
  • Select an option

  • Save alexyoung/89496 to your computer and use it in GitHub Desktop.

Select an option

Save alexyoung/89496 to your computer and use it in GitHub Desktop.
class GameItem
attr_accessor :x, :y
def initialize(app, x, y, colour = '#fff')
@app = app
@x = x
@y = y
@app.stroke colour
@rect = app.rect x * cell_size, y * cell_size, cell_size - 1, cell_size - 1
end
def move_to(x, y)
@x = x
@y = y
move_rect
end
def move_by(x, y)
@x += x
@y += y
move_rect
end
def cell_size
10
end
# This removes the item from the game
def remove
@rect.hide
true
end
private
def move_rect
@rect.move @x * cell_size, @y * cell_size
end
end
class Snake
attr_accessor :segments, :x, :y
class Segment < GameItem
end
def initialize(app, x, y)
@app = app
change_direction :left
@segments = []
@x = x
@y = y
add_segment
end
def length
@segments.size
end
def add_segment
segment = nil
if @segments.empty?
segment = Segment.new @app, @x, @y, '#ff0000'
else
segment = Segment.new @app, @segments.last.x, @segments.last.y
segment.move_by @direction_x * -1, @direction_y * -1
end
# Make sure the segment is added to the back
@segments << segment
end
def move
@segments.reverse.each_with_index do |segment, i|
if i + 1 == length
segment.move_by @direction_x, @direction_y
else
next_segment = @segments.reverse[i + 1]
segment.move_to next_segment.x, next_segment.y
end
end
@x = @segments.first.x
@y = @segments.first.y
end
def change_direction(direction)
@direction = direction
case direction
when :up
@direction_x = 0
@direction_y = -1
when :down
@direction_x = 0
@direction_y = 1
when :left
@direction_x = -1
@direction_y = 0
when :right
@direction_x = 1
@direction_y = 0
end
end
end
class GameBoard
class Food < GameItem
def initialize(app, x, y, colour = '#00ff00')
super
end
end
def initialize(app)
@food_items = []
@app = app
end
def add_food(x, y)
@food_items << Food.new(@app, x, y)
end
def collision_at?(x, y)
@food_items.find do |item|
item.x == x and item.y == y
end
end
def remove_food_at(x, y)
@food_items.delete_if do |item|
if item.x == x and item.y == y
item.remove
end
end
end
end
Shoes.app do
background '#000'
snake = Snake.new self, 25, 25
board = GameBoard.new self
delay = 1
stroke '#fff'
# Add some food at random positions
10.times do
board.add_food rand(50), rand(50)
end
animate 5 do
keypress do |key|
case key
when :up, :down, :left, :right
snake.change_direction key
end
end
snake.move
if board.collision_at? snake.x, snake.y
snake.add_segment
board.remove_food_at snake.x, snake.y
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment