module BattleshipAi
Constants
- AI_OPPONENT
Public Instance Methods
Source
# File lib/battleship_ai.rb, line 22 def hunt_coord(shots) hits = shots.select { |_, result| %i[hit sunk].include?(result) }.keys hits.each do |coord| index = BattleshipBoard.coord_to_index(coord) BattleshipBoard.neighbors(index).each do |neighbor| neighbor_coord = BattleshipBoard.index_to_coord(neighbor) return neighbor_coord unless shots.key?(neighbor_coord) end end nil end
Source
# File lib/battleship_ai.rb, line 10 def pick_shot(game:, rand: ->(max) { Random.rand(0...max) }) player = AI_OPPONENT shots = game["shots"][player] || {} hunt = hunt_coord(shots) return hunt if hunt untried = (0...(BattleshipBoard::SIZE * BattleshipBoard::SIZE)).reject do |index| shots.key?(BattleshipBoard.index_to_coord(index)) end BattleshipBoard.index_to_coord(untried[rand.call(untried.length)]) end