ruby version

This commit is contained in:
Gwenhael Le Moine 2022-09-14 14:39:11 +02:00
parent ca1ab0a6f2
commit a84cd71053
No known key found for this signature in database
GPG key ID: FDFE3669426707A7

144
myhunt.rb Executable file
View file

@ -0,0 +1,144 @@
#!/usr/bin/env ruby
module MyHunt
class Cell
attr_accessor :mine,
:open
def initialize( mine: false, open: false )
@mine = mine
@open = open
end
def explore
@open = true
@mine
end
end
class Board
attr_reader :width,
:height,
:field,
:explorer_x,
:explorer_y
def initialize( number_of_mines = 20, height = 8, width = 16 )
@height = height
@width = width
@explorer_x = 0
@explorer_y = 0
@field = {}
@width.times do |x|
@height.times do |y|
puts "(#{x}, #{y})"
@field[[x, y]] = Cell.new( open: x.zero? && y.zero? )
end
end
placed_mines = 0
while placed_mines < number_of_mines
coordinates = [rand( @width ), rand( @height )]
next if coordinates == [0, 0]
next if @field[ coordinates ].mine
@field[ coordinates ].mine = true
placed_mines += 1
end
end
def display
puts "nearby: #{count_nearby_mines}"
@height.times do |y|
@width.times do |x|
if [@explorer_x, @explorer_y] == [x, y]
putc 'o'
elsif [@width, @height] == [x + 1, y + 1]
putc '_'
elsif @field[[x, y]].open
putc @field[[x, y]].mine ? '*' : ' '
else
putc '█'
end
end
putc "\n"
end
end
def update_explorer_location( direction )
case direction
when 'up'
@explorer_y -= 1 if @explorer_y.positive?
when 'right'
@explorer_x += 1 if @explorer_x < (@width - 1)
when 'down'
@explorer_y += 1 if @explorer_y < (@height - 1)
when 'left'
@explorer_x -= 1 if @explorer_x.positive?
when 'up-right'
if @explorer_x < (@width - 1) && @explorer_y.positive?
@explorer_x += 1
@explorer_y -= 1
end
when 'down-right'
if @explorer_x < (@width - 1) && @explorer_y < (@height - 1)
@explorer_x += 1
@explorer_y += 1
end
when 'down-left'
if @explorer_x.positive? && @explorer_y < (@height - 1)
@explorer_x -= 1
@explorer_y += 1
end
when 'up-left'
if @explorer_x.positive? && @explorer_y.positive?
@explorer_x -= 1
@explorer_y -= 1
end
end
end
def move( direction )
update_explorer_location( direction )
if @explorer_x == (@width - 1) && @explorer_y == (@height - 1)
puts 'Victory'
elsif @field[[@explorer_x, @explorer_y]].explore
puts 'Blown up'
end
end
def count_nearby_mines
counter = 0
[@explorer_x - 1, @explorer_x, @explorer_x + 1].each do |x|
[@explorer_y - 1, @explorer_y, @explorer_y + 1].each do |y|
next if x.negative?
next if y.negative?
next if x == @width
next if y == @height
next if x == @explorer_x && y == @explorer_y
puts "(#{x}, #{y})"
counter += 1 if @field[[x, y]].mine
end
end
counter
end
def debug
@height.times { move('down-right') }
move( 'right' )
@height.times { move('up-right') }
end
end
end
field = MyHunt::Board.new
field.display
field.debug
field.display