Created
April 25, 2014 18:46
-
-
Save rigibun/11299294 to your computer and use it in GitHub Desktop.
This file contains 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
StageData = <<END | |
########## | |
#.dd..p..# | |
#........# | |
#.oo.....# | |
#........# | |
########## | |
END | |
class Tile | |
def initialize(c) | |
@status = case c | |
when "#" | |
:wall | |
when "." | |
:space | |
when "d" | |
:dest | |
when "o" | |
:object | |
end | |
end | |
def move(obj) | |
if obj.status == :object && @status == :dest | |
@status = :comp | |
obj.status = :space | |
elsif @status == :space | |
@status, obj.status = obj.status, @status | |
end | |
end | |
def canMove? | |
@status == :space || @status == :dest | |
end | |
def to_s | |
@@table = {space: " ", object: "o", wall: "#", dest: ".", comp: "o"} | |
@@table[@status] | |
end | |
def inspect | |
self.to_s | |
end | |
def comp? | |
@status == :comp | |
end | |
def object? | |
@status == :object | |
end | |
attr_accessor :status | |
end | |
class Game | |
def initialize(stageData) | |
@destList = [] | |
tmp = stageData.split("\n").map{|str| str.split //} | |
@height = tmp.size | |
@width = tmp[0].size | |
for y in 0...@height | |
for x in 0...@width | |
@playerPos, tmp[y][x] = [y, x], "." if tmp[y][x] == "p" | |
end | |
end | |
@stage = tmp.map{|line| line.map{|c| | |
t = Tile.new(c) | |
@destList.push(t) if c == "d" | |
t | |
}} | |
end | |
def run | |
until completed? | |
stagePrint | |
input = gets.chomp | |
move(input[0]) | |
end | |
stagePrint | |
puts "Congratulations!" | |
end | |
def stagePrint | |
for y in 0...@height | |
for x in 0...@width | |
if @playerPos == [y, x] | |
print("p") | |
else | |
print @stage[y][x].to_s | |
end | |
end | |
puts | |
end | |
end | |
def completed? | |
a = true | |
@destList.each{|d| | |
a = a && d.comp? | |
} | |
a | |
end | |
def move(c) | |
direction = case c | |
when "w" | |
[-1, 0] | |
when "a" | |
[0, -1] | |
when "s" | |
[1, 0] | |
when "d" | |
[0, 1] | |
else | |
nil | |
end | |
if direction | |
py, px = @playerPos | |
dy, dx = direction | |
if (dTile = @stage[py + dy][px + dx]).canMove? | |
@playerPos = py + dy, px + dx | |
elsif dTile.object? && (ddTile = @stage[py + 2 * dy][px + 2 * dx]).canMove? | |
ddTile.move(dTile) | |
@playerPos = py + dy, px + dx | |
end | |
end | |
end | |
def debugPrint | |
puts "w:#{@width} #h:{@height}" | |
puts "player x:#{@playerPos[1]} y:#{@playerPos[0]}" | |
stagePrint | |
end | |
end | |
g = Game.new(StageData) | |
g.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment