Last active
December 17, 2015 23:59
-
-
Save sld/5693285 to your computer and use it in GitHub Desktop.
snake
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
require 'Win32API' | |
def field( size ) | |
array = Array.new(size) | |
for i in 0...size | |
array[i] = Array.new(size, 1) | |
end | |
for i in 1...size-1 | |
for j in 1...size-1 | |
array[i][j] = 0 | |
end | |
end | |
return array | |
end | |
def add_snake_to_field(x, y, field) | |
field[x][y] = 2 | |
# Возвращет текущие координаты | |
return [x, y] | |
end | |
def get_pressed_key | |
if ENV['OS'] == "Windows_NT" | |
return Win32API.new('crtdll','_getch', [], 'L').Call | |
end | |
begin | |
system("stty raw -echo") | |
str = STDIN.getc | |
ensure | |
system("stty -raw echo") | |
end | |
return str | |
end | |
def update_game_field (game_field, old_coordinates, new_coordinates) | |
game_field[old_coordinates[0]][old_coordinates[1]] = 0 | |
game_field[new_coordinates[0]][new_coordinates[1]] = 2 | |
end | |
def snake_move(current_coordinates, game_field, direction) | |
old_coordinates = current_coordinates.clone() | |
case direction | |
when :up | |
current_coordinates[0] = current_coordinates[0] - 1 | |
when :down | |
current_coordinates[0] = current_coordinates[0] + 1 | |
when :right | |
current_coordinates[1] = current_coordinates[1] + 1 | |
when :left | |
current_coordinates[1] = current_coordinates[1] - 1 | |
end | |
update_game_field(game_field, old_coordinates, current_coordinates) | |
end | |
def print_game_field( game_field ) | |
system("clear") | |
game_field.each do |array| | |
array.each do |element| | |
print " #{element} " | |
end | |
print "\n" | |
end | |
end | |
KEY_UP = "i" | |
KEY_DOWN = "k" | |
KEY_LEFT = "j" | |
KEY_RIGHT = "l" | |
KEY_EXIT = "e" | |
def run_game() | |
game_field = field( 10 ) | |
current_coordinates = add_snake_to_field(5, 5, game_field) | |
print_game_field( game_field ) | |
loop do | |
key = get_pressed_key() | |
if key == KEY_UP | |
snake_move(current_coordinates, game_field, :up) | |
elsif key == KEY_RIGHT | |
snake_move(current_coordinates, game_field, :right) | |
elsif key == KEY_LEFT | |
snake_move(current_coordinates, game_field, :left) | |
elsif key == KEY_DOWN | |
snake_move(current_coordinates, game_field, :down) | |
else key == KEY_EXIT | |
return "Exit!" | |
end | |
#sleep 0.5 | |
print_game_field( game_field ) | |
end | |
end | |
run_game() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment