Created
April 2, 2009 10:33
-
-
Save alexyoung/89128 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| private | |
| def move_rect | |
| @rect.move @x * cell_size, @y * cell_size | |
| end | |
| end | |
| class Snake | |
| attr_accessor :segments | |
| 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 | |
| Shoes.app do | |
| background '#000' | |
| snake = Snake.new self, 25, 25 | |
| cell_size = 10 | |
| delay = 1 | |
| stroke '#fff' | |
| 20.times do | |
| snake.add_segment | |
| end | |
| animate 5 do | |
| keypress do |key| | |
| case key | |
| when :up, :down, :left, :right | |
| snake.change_direction key | |
| end | |
| end | |
| snake.move | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment