class GameCodebreaker::Game
Constants
- JUST_A_MAGIC_NUMBER
Attributes
code[R]
game_over[R]
hint[R]
hints[R]
history[R]
length[R]
level[R]
level_name[R]
turns[R]
win[R]
Public Class Methods
new( code: "", length: 4, level: (Options.level)[:level], turns: 0, history: [], hint: (Options.level)[:hint], hinted: 0, win: false, game_over: false, hints: [], level_name: 'low' )
click to toggle source
# File lib/game_codebreaker/game.rb, line 10 def initialize( code: "", length: 4, level: (Options.level)[:level], turns: 0, history: [], hint: (Options.level)[:hint], hinted: 0, win: false, game_over: false, hints: [], level_name: 'low' ) @code, @length = code, length @level, @turns = level, turns @history, @hint = history, hint @hinted, @win, = hinted, win @hints, @game_over = hints, game_over @level_name = level_name generate_code if @code == "" raise ArgumentError, 'Length code must be equal to variable with name \'length\'' if @code.size != @length end
Public Instance Methods
check_game( string )
click to toggle source
# File lib/game_codebreaker/game.rb, line 45 def check_game( string ) @game_over = true if @turns == @level (@win = true; @game_over = true) if string.count("+") == @length end
game_over?()
click to toggle source
# File lib/game_codebreaker/game.rb, line 50 def game_over? @game_over end
get_hint()
click to toggle source
# File lib/game_codebreaker/game.rb, line 33 def get_hint ( @hints << "there is no hints anymore"; @hints.uniq!; return ) if @hint == 0 pozition = nil; old_pozitions = [] @hints.each do |str| str.split(//).each_with_index { |word, index| old_pozitions << index unless word.to_i == 0 } end ( @length*JUST_A_MAGIC_NUMBER ).times { pozition = rand( @length ); break unless old_pozitions.include?( pozition ) } result = "" @length.times { |i| pozition == i ? result << @code.to_s[i] : result << "-" } @hint -= 1; @hints << result end
respond( string )
click to toggle source
# File lib/game_codebreaker/game.rb, line 23 def respond( string ) return if game_over? skynet = Array.new(@code.split(//)) human = string.split(//) list = [@code, human.join("")] result = process( skynet, human ) @turns += 1; @history << ( list << result ) check_game( result ) end
win?()
click to toggle source
# File lib/game_codebreaker/game.rb, line 54 def win? @win end
Private Instance Methods
generate_code()
click to toggle source
# File lib/game_codebreaker/game.rb, line 60 def generate_code @length.times{ @code << rand(1..6).to_s } end
process( skynet, human )
click to toggle source
# File lib/game_codebreaker/game.rb, line 64 def process( skynet, human ) result = "" @length.times do |i| if skynet[i] == human[i] result += "+" skynet[i], human[i] = nil, nil end end skynet.compact!; human.compact!; human.each { |val| result += "-" if skynet.include?( val ) } result end