Class: GameCodebreaker::Memory

Inherits:
Object
  • Object
show all
Defined in:
lib/game_codebreaker/memory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Memory

Returns a new instance of Memory.



8
9
10
11
# File 'lib/game_codebreaker/memory.rb', line 8

def initialize( path )
  @path = path
  File.exists?( path ) ? @users = load.users : @users = []
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



6
7
8
# File 'lib/game_codebreaker/memory.rb', line 6

def path
  @path
end

#usersObject

Returns the value of attribute users.



6
7
8
# File 'lib/game_codebreaker/memory.rb', line 6

def users
  @users
end

Instance Method Details

#add_games(object) ⇒ Object



13
14
15
16
# File 'lib/game_codebreaker/memory.rb', line 13

def add_games( object )
  @users.each { |user| @user = user if user.hash == object.hash }
  object.games.each { |game| @user.games << game } 
end

#exists?(object) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
# File 'lib/game_codebreaker/memory.rb', line 18

def exists?( object )
  @users.each { |user| return true if user.hash == object.hash }
  false
end

#get_user(object) ⇒ Object



23
24
25
26
# File 'lib/game_codebreaker/memory.rb', line 23

def get_user( object )
  @users.each { |user| @user = user if user.hash == object.hash }
  @user
end

#info(user) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/game_codebreaker/memory.rb', line 28

def info( user )
  a = []
  a << name = user.name
  a << surname = user.surname
  a << age = user.age
  a << total_game = user.games.size
  array_win = user.games.select { |game| game.win == true }
  a << total_win = array_win.size
  a << total_losses = ( user.games.select { |game| game.win == false } ).size
  average_turns = 0 and array_win.each { |game| average_turns += game.turns }
  total_win != 0 ? a << average_turns /= total_win : a << 0
  average_level = 0 and user.games.select { |game| average_level += game.level }
  a << average_level /= total_game
end

#loadObject



48
49
50
# File 'lib/game_codebreaker/memory.rb', line 48

def load
  return Marshal.load File.open(@path,'r').read if File.exists?( @path )
end

#save(user) ⇒ Object



43
44
45
46
# File 'lib/game_codebreaker/memory.rb', line 43

def save( user )
  exists?( user ) ? ( add_games(user); user = get_user(user) ) : @users << user
  File.open(@path,'w') { |f| f.write Marshal.dump self }
end