/
kerry_player.rb
executable file
·95 lines (81 loc) · 1.59 KB
/
kerry_player.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
module Randomiser
class << self
def coordinate
rand 10
end
def start_of_ship_with_length length
rand(10 - length)
end
def direction
[:across, :down][rand(2)]
end
end
end
class ShipPlacer
def initialize
@taken = []
end
def carrier
ship_of_length 5
end
def battleship
ship_of_length 4
end
def sub
ship_of_length 3
end
def cruiser
ship_of_length 3
end
def destroyer
ship_of_length 2
end
private
def ship_of_length length
direction = Randomiser.direction
across_coord = Randomiser.coordinate
along_coord = Randomiser.start_of_ship_with_length length
try_again = false
taken = @taken
if direction == :across
x, y = along_coord, across_coord
(y..y+length).each do |y|
try_again ||= @taken.include? [x, y]
@taken << [x, y]
end
else
x, y = across_coord, along_coord
(x..x+length).each do |x|
try_again ||= @taken.include? [x, y]
@taken << [x, y]
end
end
if try_again
ship_of_length(length)
else
@taken = taken
[x, y, length, direction]
end
end
end
class KerryPlayer
def initialize
@tried = []
end
def name
"Kerry"
end
def new_game
placer = ShipPlacer.new
[placer.carrier, placer.battleship, placer.sub, placer.cruiser, placer.destroyer]
end
def take_turn state, ships_remaining
x, y = Randomiser.coordinate, Randomiser.coordinate
if @tried.include? [x, y]
take_turn state, ships_remaining
else
@tried << [x, y]
[x, y]
end
end
end