Class: ConnectNGame::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/connect_n_game/game.rb

Overview

The Game class of the connect_n_game.
Responsibility

  • This class is responsible for the overall operation of the game. It holds

the playing "rack", and the players. It also keeps a log of moves,
determines if the game has been won or if a stalemate has occurred.


Notes

  • The Game class does NOT interact with the outside world. That is the

job of the UI object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(player_ex, player_oh, game_size = 4) ⇒ Game

Create an instance of a game object.
Parameters

  • player_ex - The player who moves first

  • payer_oh - The player who moves next

  • game_size - The size of the game connection (4..8). Default: 4


Returns

  • An instance of a Game.



39
40
41
42
43
# File 'lib/connect_n_game/game.rb', line 39

def initialize(player_ex, player_oh, game_size=4)
  @game_size = game_size
  #Set up player related data.
  @players = { 1 => player_ex, 2 => player_oh }
end

Instance Attribute Details

#currentObject (readonly)

The current player number.



27
28
29
# File 'lib/connect_n_game/game.rb', line 27

def current
  @current
end

#logObject (readonly)

The play log.



24
25
26
# File 'lib/connect_n_game/game.rb', line 24

def log
  @log
end

#playersObject (readonly)

Whose playing?



21
22
23
# File 'lib/connect_n_game/game.rb', line 21

def players
  @players
end

#rackObject (readonly)

The game playing surface



18
19
20
# File 'lib/connect_n_game/game.rb', line 18

def rack
  @rack
end

#turnObject (readonly)

The last played turn number.



30
31
32
# File 'lib/connect_n_game/game.rb', line 30

def turn
  @turn
end

Instance Method Details

#current_playerObject

What player moves next?
Returns

  • An instance of a Player.



48
49
50
# File 'lib/connect_n_game/game.rb', line 48

def current_player
  players[current]
end

#game_initializeObject

Get ready to start a game



57
58
59
60
61
62
63
64
65
# File 'lib/connect_n_game/game.rb', line 57

def game_initialize
  #Set up game play data.
  @turn = 0
  @current = 1
  @rack = Rack.new(@game_size)
  @log  = []

  self
end

#last_moveObject

What was the last move?



87
88
89
# File 'lib/connect_n_game/game.rb', line 87

def last_move
  log[-1]
end

#next_moveObject

Play the next move!
Returns

  • :victory, :stalemate, :continue, or :invalid_move



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/connect_n_game/game.rb', line 70

def next_move
  channel = current_player.make_move(self, current)
  score = rack.play_channel(channel, current)
  @log << channel
  @turn += 1

  if score >= rack.order
    :victory
  elsif rack.rack_full?
    :stalemate
  else
    @current = (@current % 2) + 1
    :continue
  end
end

#previous_playerObject



52
53
54
# File 'lib/connect_n_game/game.rb', line 52

def previous_player
  players[(@current % 2) + 1]
end