Class: Rb2048::Game

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(init_elements = nil, size = 4, level = 2) ⇒ Game

Returns a new instance of Game.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rb2048/game.rb', line 17

def initialize(init_elements = nil, size=4, level=2)
  @logger = LoggerMan
  
  @level = level
  @size = size 

  @render = ::Rb2048::GameRender.new
  @window = @render.window

  @frame_data_channel = Queue.new
  @refresh_rate = 60
  @frame_delta = 1.0 / @refresh_rate

  @io_data_channel = Queue.new
  
  init_game(init_elements)      
end

Class Method Details

.quit_gameObject



12
13
14
15
# File 'lib/rb2048/game.rb', line 12

def self.quit_game
  Curses.close_screen
  printf "Goodbye :P \n"
end

Instance Method Details

#actionObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rb2048/game.rb', line 56

def action
  while (command = @io_data_channel.shift)
    if command == :QUIT
      self.class.quit_game
      exit 0
    elsif command == :RESTART
      self.init_game
    else
      @backend.__send__("#{command.to_s.downcase}_merge")
      frame_data = @backend.tun_result
      @frame_data_channel << frame_data
    end
  end

end

#init_game(init_elements = nil) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/rb2048/game.rb', line 40

def init_game(init_elements=nil)
  @backend = ::Rb2048::GameBoard.new(@size,@level)
  @backend.create_elements(init_elements)

  @logger.log("INIT", "start")
  @frame_data_channel << @backend.tun_result
end

#key_listenerObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/rb2048/game.rb', line 72

def key_listener()
  while true
    command = nil

    k = @window.getch
    if k ==  Curses::KEY_UP || k ==  "w"
      command =  :UP
    elsif k ==  Curses::KEY_DOWN || k ==  "s"
      command =  :DOWN
    elsif k ==  Curses::KEY_LEFT || k ==  "a"
      command =  :LEFT
    elsif k ==  Curses::KEY_RIGHT || k ==  "d"
      command =  :RIGHT
    elsif k ==  "q"
      command = :QUIT
    elsif k == "r"
      command = :RESTART
    else
    end

    @io_data_channel << command if command
    sleep 0.08
  end
end

#main_loopObject



48
49
50
51
52
53
54
# File 'lib/rb2048/game.rb', line 48

def main_loop
  key_listener_thr = Thread.new { self.key_listener }
  action_thr = Thread.new { self.action }
  render_thr = Thread.new { self.render }

  [key_listener_thr,action_thr, render_thr].map(&:join)
end

#renderObject



97
98
99
100
101
102
103
# File 'lib/rb2048/game.rb', line 97

def render
  while (frame_data = @frame_data_channel.shift)
    break if frame_data == :done
    @render.draw(frame_data) if frame_data
    sleep 0.16
  end
end

#runObject



35
36
37
38
# File 'lib/rb2048/game.rb', line 35

def run
  init_game
  main_loop
end