Skip to content

Instantly share code, notes, and snippets.

@swordray
Last active November 27, 2021 07:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save swordray/a04e9fda23107f26f284 to your computer and use it in GitHub Desktop.
Save swordray/a04e9fda23107f26f284 to your computer and use it in GitHub Desktop.
Implement game 2048 in less than 30 lines of Ruby code
class Game2048
def initialize
@array = 4.times.map { [ nil ] * 4 }
2.times { fill }
end
def fill
i, j = rand(4), rand(4)
return fill if @array[i][j]
@array[i][j] = [2, 2, 2, 2, 4].shuffle.first
end
def move(direction)
@array = @array.transpose if %w[up down].include?(direction)
@array.each(&:reverse!) if %w[right down].include?(direction)
4.times do |i|
a = @array[i].compact
4.times { |x| a[x], a[x + 1] = a[x] * 2, nil if a[x].to_i == a[x + 1] }
@array[i] = a.compact.concat([ nil ] * 4)[0..3]
end
@array.each(&:reverse!) if %w[right down].include?(direction)
@array = @array.transpose if %w[up down].include?(direction)
end
def play
puts @array.map { |line| "[%5s] " * 4 % line }
move({ a: 'left', s: 'down', d: 'right', w: 'up' }[gets.strip.to_sym])
fill && play if @array.flatten.include?(nil)
end
end
Game2048.new.play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment