Skip to content

Instantly share code, notes, and snippets.

@ianwhite
Created October 15, 2011 16:12
Show Gist options
  • Save ianwhite/1289785 to your computer and use it in GitHub Desktop.
Save ianwhite/1289785 to your computer and use it in GitHub Desktop.
battleship FAIL
class I2wPlayer
attr_accessor :current_state, :board
attr_reader :shots
def initialize
@shots = []
@board = []
end
def name
"i2w"
end
def new_game
[5,4,3,3,2].map {|size| place_ship(size)}
end
# need to place ship,
# check within bounds
# check no overlap
def place_ship(size)
orientation = rand(2) == 0 ? :across : :down
pos = [rand(10), rand(10)]
if ship_valid?(size, pos, orientation)
return pos + [size, orientation]
else
place_ship(size)
end
end
def ship_valid?(size, pos, orientation)
if orientation == :across
return false if pos.last + size > 10
our_squares = (pos.last..pos.last+size).map {|x| [pos.first, x]}
else
return false if pos.first + size > 10
our_squares = (pos.first..pos.first+size).map {|y| [y, pos.last]}
end
# overlap
return false unless (board - our_squares) == board
self.board += our_squares
true
end
def take_turn(state, ships_remaining)
self.current_state = state
if shots.any? && hit?(shots.last)
shoot shot_next_to(shots.last)
else
shoot random_pot_shot
end
end
def shoot(shot)
@shots << shot
shot
end
def hit?(shot)
current_state[shot.last][shot.first] == :hit
end
def unknown?(shot)
current_state[shot.last][shot.first] == :unknown
end
def miss?(shot)
current_state[shot.last][shot.first] == :miss
end
def random_pot_shot
shot = [rand(10), rand(10)]
unknown?(shot) ? shot : random_pot_shot
end
def valid_shot?(shot)
unknown?(shot) && in_bounds?(shot)
end
def shot_next_to(shot)
new_shot = case rand(4)
when 0 then [shot.first - 1,shot.last]
when 1 then [shot.first + 1,shot.last]
when 2 then [shot.first, shot.last - 1]
when 3 then [shot.first, shot.last + 1]
end
valid_shot?(new_shot) ? new_shot : random_pot_shot
end
def in_bounds?(shot)
(0..9).include?(shot.first) && (0..9).include?(shot.last)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment