myhunt/ruby/bin/gosuhunt
2023-02-09 15:53:48 +01:00

89 lines
2.7 KiB
Ruby
Executable file

#!/usr/bin/env ruby
# frozen_string_literal: true
require 'gosu'
require 'minehunt'
class GosuHunt < Gosu::Window
def initialize( number_of_mines = 20 )
super 640, 480
self.caption = "Gosu Hunt"
@number_of_mines = number_of_mines
@field = MineHunt::Board.new( @number_of_mines )
@finished = false
@state = { dead: false, victory: false }
end
def button_up(id)
case id
when Gosu::KB_ESCAPE, Gosu::KB_Q
close
when Gosu::KB_R
@field = MineHunt::Board.new( @number_of_mines )
@state = { dead: false, victory: false }
when Gosu::KB_NUMPAD_1
@state = @field.move 'down-left'
when Gosu::KB_NUMPAD_2, Gosu::KB_DOWN
@state = @field.move 'down'
when Gosu::KB_NUMPAD_3
@state = @field.move 'down-right'
when Gosu::KB_NUMPAD_4, Gosu::KB_LEFT
@state = @field.move 'left'
when Gosu::KB_NUMPAD_6, Gosu::KB_RIGHT
@state = @field.move 'right'
when Gosu::KB_NUMPAD_7
@state = @field.move 'up-left'
when Gosu::KB_NUMPAD_8, Gosu::KB_UP
@state = @field.move 'up'
when Gosu::KB_NUMPAD_9
@state = @field.move 'up-right'
else
super
end
@finished = @state[:dead] || @state[:victory]
end
def update; end
def draw
if @state[:dead]
self.caption = "You died! :(, score #{@field.score} "
elsif @state[:victory]
self.caption = "You won!! :), score #{@field.score} "
else
self.caption = "#{@field.number_of_mines} mines, #{@field.count_nearby_mines} nearby, score #{@field.score}"
end
theme = { explorer: '()',
dead_explorer: '☠ ',
door: '=>',
mine: '<>',
cell: '██',
visited_cell: ' ' }
@field.height.times do |y|
@field.width.times do |x|
Gosu::Image.from_text( if [@field.explorer_x, @field.explorer_y] == [x, y]
@state[:dead] ? theme[:dead_explorer] : theme[:explorer]
elsif [@field.width, @field.height] == [x + 1, y + 1]
theme[:door]
elsif @field.field[[x, y]].open
theme[:visited_cell]
elsif @field.field[[x, y]].mine && ( @state[:dead] || @state[:victory] )
theme[:mine]
else
theme[:cell]
end, 20 )
.draw( x * 2 * 10, y * 20, 0 )
end
end
end
end
number_of_mines = 20
number_of_mines = ARGV.first.to_i if ARGV.length == 1
GosuHunt.new( number_of_mines ).show