-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgame.rb
126 lines (101 loc) · 2.76 KB
/
game.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
require 'json'
require_relative 'ship'
require_relative 'torpedo'
require_relative 'torpedo'
class Game
attr_accessor :width, :height, :turn, :game_state, :players
def scaffold
@players.first.ships << Ship.new(:LITTLE, [{"row" => 0, "col" => 0}, {"row" => 0, "col" => 1}])
@players.last.ships << Ship.new(:LITTLE, [{"row" => 1, "col" => 2}, {"row" => 2, "col" => 2}])
@players.first.torpedos << Torpedo.new(2, 3)
torpedo = Torpedo.new(0, 1)
torpedo.hit!
@players.last.torpedos << torpedo
end
def initialize(width, height)
@width = width
@height = height
@players = []
end
def add_player(name)
player = Player.new(name)
player.game = self
@players << player
player
end
def start
@players.shuffle!
@turn = :p1
@state = 'active'
end
def self.from_json(json)
from_hash(JSON.parse(json))
end
def self.from_hash(hash)
game = Game.new(hash['width'], hash['height'])
hash['players'].each do |player|
player = Player.from_hash(player)
player.game = game
game.players << player
end
game.turn = (hash['turn'] == game.players.first.name ? :p1 : :p2)
game.game_state = hash['game_state']
game
end
def to_hash
{
'players' => players.map(&:to_hash),
'height' => height,
'width' => width,
'turn' => current_player.name,
'game_state' => game_state
}
end
def opponent_for(player)
@players.detect{ |p| p != player }
end
def take_turn(player_id, row, col)
raise unless valid_turn?(player_id)
raise unless valid_move?(row, col)
# see if this is a hit
ships = opponent_for(current_player).ships
torpedo = Torpedo.new(row, col)
hit = ships.detect{ |s| s.hit_by_torpedo?(torpedo) }
torpedo.hit! if hit
current_player.torpedos << torpedo
toggle_turn!
# clear winner cache
@winner = nil
torpedo
end
def valid_turn?(player_id)
player_id == current_player.name
end
def valid_move?(row, col)
in_bounds = row >= 0 && row < height && col >= 0 && col < width
previous_move = current_player.torpedos.detect do |t|
t.row == row && t.col == col
end
in_bounds && !previous_move
end
def toggle_turn!
@turn = (@turn == :p1 ? :p2 : :p1)
end
def current_player
@turn == :p1 ? @players.first : @players.last
end
def winner
@winner ||= @players.detect do |player|
opponent = opponent_for(player)
alive_ship = opponent.ships.detect do |ship|
hit_coords = ship.coords.select do |coord|
player.torpedos.detect do |torpedo|
torpedo.row == coord['row'] && torpedo.col == coord['col']
end
end
hit_coords.length < ship.coords.length
end
!alive_ship
end
end
end