Class: RubyArmor::Play

Inherits:
Fidgit::GuiState
  • Object
show all
Defined in:
lib/ruby_armor/states/play.rb

Constant Summary collapse

MAX_TURN_DELAY =
1
MIN_TURN_DELAY =
0
TURN_DELAY_STEP =
0.1
MAX_TURNS =
100
SHORTCUT_COLOR =
Color.rgb(175, 255, 100)
FILE_SYNC_DELAY =

2 polls per second.

0.5
ENEMY_TYPES =
[
    RubyWarrior::Units::Wizard,
    RubyWarrior::Units::ThickSludge,
    RubyWarrior::Units::Sludge,
    RubyWarrior::Units::Archer,
]
WARRIOR_TYPES =
[
    RubyWarrior::Units::Warrior,
    RubyWarrior::Units::Golem,
]
FRIEND_TYPES =
[
    RubyWarrior::Units::Captive,
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(game, config) ⇒ Play

Returns a new instance of Play.



41
42
43
44
# File 'lib/ruby_armor/states/play.rb', line 41

def initialize(game, config)
  @game, @config = game, config
  super()
end

Instance Attribute Details

#turnObject

Returns the value of attribute turn.



31
32
33
# File 'lib/ruby_armor/states/play.rb', line 31

def turn
  @turn
end

Instance Method Details

#create_file_tab_windowsObject



291
292
293
294
295
296
297
298
299
# File 'lib/ruby_armor/states/play.rb', line 291

def create_file_tab_windows
  @file_tab_windows = {}
  @file_contents = {}
  ["README", "player.rb"].each do |file|
    @file_tab_windows[file] = Fidgit::ScrollWindow.new width: 380, height: 250 do
      @file_contents[file] = text_area width: 368, editable: false
    end
  end
end

#create_file_tabsObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/ruby_armor/states/play.rb', line 230

def create_file_tabs
  # Tabs to contain README and player code to the left.
  vertical padding: 0, spacing: 0 do
    @file_tabs_group = group do
      @file_tab_buttons = horizontal padding: 0, spacing: 4 do
        %w[README player.rb].each do |name|
          radio_button(name.to_s, name, border_thickness: 0, tip: "View #{File.join profile.player_path, name}")
        end

        horizontal padding_left: 50, padding: 0 do
          button "copy", tip: "Copy displayed file to clipboard", font_height: 12, border_thickness: 0, padding: 4 do
            Clipboard.copy @file_contents[@file_tabs_group.value].stripped_text
          end

          # Default editor for Windows.
          ENV['EDITOR'] = "notepad" if Gem.win_platform? and ENV['EDITOR'].nil?

          tip = ENV['EDITOR'] ? "Edit file in #{ENV['EDITOR']} (set EDITOR environment variable to use a different editor)" : "ENV['EDITOR'] not set"
          button "edit", tip: tip, enabled: ENV['EDITOR'], font_height: 12, border_thickness: 0, padding: 4 do
            command = %<#{ENV['EDITOR']} "#{File.join(level.player_path, @file_tabs_group.value)}">
            $stdout.puts "SYSTEM: #{command}"
            Thread.new { system command }
          end
        end
      end

      subscribe :changed do |_, value|
        current = @file_tab_buttons.find {|elem| elem.value == value }
        @file_tab_buttons.each {|t| t.enabled = (t != current) }
        current.color, current.background_color = current.background_color, current.color

        @file_tab_contents.clear
        @file_tab_contents.add @file_tab_windows[value]
      end
    end

    # Contents of those tabs.
    @file_tab_contents = vertical padding: 0, width: 380, height: $window.height * 0.5

    create_file_tab_windows
    @file_tabs_group.value = "README"
  end
end

#create_log_tab_windowsObject



281
282
283
284
285
286
287
288
289
# File 'lib/ruby_armor/states/play.rb', line 281

def create_log_tab_windows
  @log_tab_windows = {}
  @log_contents = {}
  ["current turn", "full log"].each do |log|
    @log_tab_windows[log] = Fidgit::ScrollWindow.new width: 380, height: 250 do
      @log_contents[log] = text_area width: 368, editable: false
    end
  end
end

#create_log_tabsObject



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/ruby_armor/states/play.rb', line 196

def create_log_tabs
  vertical padding: 0, spacing: 0 do
    @log_tabs_group = group do
      @log_tab_buttons = horizontal padding: 0, spacing: 4 do
        ["current turn", "full log"].each do |name|
          radio_button(name.capitalize, name, border_thickness: 0, tip: "View #{name}")
        end

        horizontal padding_left: 50, padding: 0 do
          button "copy", tip: "Copy displayed log to clipboard", font_height: 12, border_thickness: 0, padding: 4 do
            Clipboard.copy @log_contents[@log_tabs_group.value].stripped_text
          end
        end
      end

      subscribe :changed do |_, value|
        current = @log_tab_buttons.find {|elem| elem.value == value }
        @log_tab_buttons.each {|t| t.enabled = (t != current) }
        current.color, current.background_color = current.background_color, current.color

        @log_tab_contents.clear
        @log_tab_contents.add @log_tab_windows[value]
      end
    end

    # Contents of those tabs.
    @log_tab_contents = vertical padding: 0, width: 380, height: $window.height * 0.5

    create_log_tab_windows
    @log_tabs_group.value = "current turn"
  end
end

#create_sync_timerObject

Continually poll the player code file to see when it is edited.



380
381
382
383
384
385
386
# File 'lib/ruby_armor/states/play.rb', line 380

def create_sync_timer
  stop_timer :refresh_code

  every(FILE_SYNC_DELAY * 1000, :name => :refresh_code) do
    sync_player_file
  end
end

#create_ui_bar(packer) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/ruby_armor/states/play.rb', line 104

def create_ui_bar(packer)
  vertical parent: packer, padding: 0, height: 260, width: 100, spacing: 6 do
    # Labels at top-right.
    @tower_label = label "", tip: "Each tower has a different difficulty level"
    @level_label = label "Level:"
    @turn_label = label "Turn:", tip: "Current turn; starvation at #{MAX_TURNS} to avoid endless games"
    @health_label = label "Health:", tip: "The warrior's remaining health; death occurs at 0"

    # Buttons underneath them.
    button_options = {
        :width => 70,
        :justify => :center,
        shortcut: :auto,
        shortcut_color: SHORTCUT_COLOR,
        border_thickness: 0,
    }
    @start_button = button "Start", button_options.merge(tip: "Start running player.rb in this level") do
      start_level
    end

    @reset_button = button "Reset", button_options.merge(tip: "Restart the level") do
      profile.level_number = 0 if profile.epic?
      prepare_level
    end

    @hint_button = button "Hint", button_options.merge(tip: "Get hint on how best to approach the level") do
      message replace_syntax(level.tip)
    end

    @continue_button = button "Continue", button_options.merge(tip: "Climb up the stairs to the next level") do
      save_player_code

      # Move to next level.
      if @game.next_level.exists?
        @game.prepare_next_level
      else
        @game.prepare_epic_mode
      end

      prepare_level
    end

    horizontal padding: 0, spacing: 21 do
      options = { padding: 4, border_thickness: 0, shortcut: :auto, shortcut_color: SHORTCUT_COLOR }
      @turn_slower_button = button "-", options.merge(tip: "Make turns run slower") do
        @config.turn_delay = [@config.turn_delay + TURN_DELAY_STEP, MAX_TURN_DELAY].min if @config.turn_delay < MAX_TURN_DELAY
        update_turn_delay
      end

      @turn_duration_label = label "", align: :center

      @turn_faster_button = button "+", options.merge(tip: "Make turns run faster") do
        @config.turn_delay = [@config.turn_delay - TURN_DELAY_STEP, MIN_TURN_DELAY].max if @config.turn_delay > MIN_TURN_DELAY
        update_turn_delay
      end

      update_turn_delay
    end

    # Review old level code.
    @review_button = button "Review", button_options.merge(tip: "Review code used for each level",
                            enabled: false, border_thickness: 0, shortcut: :v) do
      ReviewCode.new(profile).show
    end
  end
end

#drawObject



590
591
592
# File 'lib/ruby_armor/states/play.rb', line 590

def draw
  super
end

#effective_turnObject



406
407
408
# File 'lib/ruby_armor/states/play.rb', line 406

def effective_turn
  @turn_slider.enabled? ? @turn_slider.value : @turn
end

#floorObject



457
# File 'lib/ruby_armor/states/play.rb', line 457

def floor; level.floor; end

#generate_readmeObject



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/ruby_armor/states/play.rb', line 363

def generate_readme
  readme = <<END
#{level.description}

Tip: #{level.tip}

Warrior Abilities:
END
  level.warrior.abilities.each do |name, ability|
    readme << "  warrior.#{name}\n"
    readme << "    #{ability.description}\n\n"
  end

  @file_contents["README"].text = replace_syntax readme
end

#handle_exception(exception) ⇒ Object



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/ruby_armor/states/play.rb', line 553

def handle_exception(exception)
  return if @exception and exception.message == @exception.message

  self.puts "\n#{profile.warrior_name} was eaten by a #{exception.class}!\n"
  self.puts exception.message
  self.puts
  self.puts exception.backtrace.join("\n")

  # TODO: Make this work without it raising exceptions in Fidgit :(
  #exception.message =~ /:(\d+):/
  #exception_line = $1.to_i - 1
  #code_lines = @file_contents["player.rb"].text.split "\n"
  #code_lines[exception_line] = "<c=ff0000>{code_lines[exception_line]}</c>"
  #@file_contents["player.rb"].text = code_lines.join "\n"

  @start_button.enabled = false

  @exception = exception
end

#levelObject



456
# File 'lib/ruby_armor/states/play.rb', line 456

def level; @level; end

#level_endedObject

Not necessarily complete; just finished.



544
545
546
547
548
549
550
551
# File 'lib/ruby_armor/states/play.rb', line 544

def level_ended
  return if profile.epic?

  @hint_button.enabled = true
  @turn_slider.enabled = true
  @turn_slider.instance_variable_set :@range, 0..turn
  @turn_slider.value = turn
end

#out_of_time?Boolean

Returns:

  • (Boolean)


573
574
575
# File 'lib/ruby_armor/states/play.rb', line 573

def out_of_time?
  turn >= MAX_TURNS
end

#play_turnObject



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/ruby_armor/states/play.rb', line 473

def play_turn
  self.puts "- turn #{(turn + 1).to_s.rjust(3)} -"

  begin
    actions = record_log do
      floor.units.each(&:prepare_turn)
      floor.units.each(&:perform_turn)
    end

    self.print actions
  rescue => ex
    handle_exception ex
    return
  end

  self.turn += 1

  @health[turn] = level.warrior.health # Record health for later playback.

  level.time_bonus -= 1 if level.time_bonus > 0

  refresh_labels

  if level.passed?
    stop_timer :refresh_code # Don't sync after successful completion, unless reset.
    @reset_button.enabled = false if profile.epic? # Continue will save performance; reset won't.
    @continue_button.enabled = true

    if profile.next_level.exists?
      self.puts "Success! You have found the stairs."
      level.tally_points

      if profile.epic?
        # Start the next level immediately.
        self.puts "\n#{"-" * 25}\n"

        # Rush onto the next level immediately!
        profile.level_number += 1
        prepare_level
        start_level
      end
    else
      self.puts "CONGRATULATIONS! You have climbed to the top of the tower and rescued the fair maiden Ruby."
      level.tally_points

      if profile.epic?
        self.puts @game.final_report if @game.final_report
        profile.save
      end
    end

    level_ended

  elsif level.failed?
    level_ended
    self.puts "Sorry, you failed level #{level.number}. Change your script and try again."

  elsif out_of_time?
    level_ended
    self.puts "Sorry, you starved to death on level #{level.number}. Change your script and try again."

  end

  # Add the full turn's text into the main log at once, to save on re-calculations.
  @log_contents["full log"].text += @log_contents["current turn"].text
  @log_tab_windows["full log"].offset_y = Float::INFINITY

  self.puts
end

#prepare_levelObject



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/ruby_armor/states/play.rb', line 301

def prepare_level
  @recorded_log = nil # Not initially logging.

  @log_contents["full log"].text = "" #unless profile.epic? # TODO: Might need to avoid this, since it could get REALLY long.
  @continue_button.enabled = false
  @hint_button.enabled = false
  @reset_button.enabled = false
  @start_button.enabled = true

  @exception = nil

  if profile.current_level.number.zero?
    if profile.epic?
      @game.prepare_epic_mode
      profile.level_number += 1
      profile.current_epic_score = 0
      profile.current_epic_grades = {}
    else
      @game.prepare_next_level 
    end
  end

  create_sync_timer

  @level = profile.current_level # Need to store this because it gets forgotten by the profile/game :(
  @playing = false
  level.load_level

  @dungeon_view.floor = floor

  # List of log entries, unit drawings and health made in each turn.
  @turn_logs = Hash.new {|h, k| h[k] = "" }
  @health = [level.warrior.health]

  @review_button.enabled = ReviewCode.saved_levels? profile # Can't review code unless some has been saved.

  self.turn = 0

  generate_readme

  # Initial log entry.
  self.puts "- turn   0 -"
  self.print "#{profile.warrior_name} climbs up to level #{level.number}\n"
  @log_contents["full log"].text += @log_contents["current turn"].text

  @dungeon_view.tile_set = %w[beginner intermediate].index(profile.tower.name) || 2 # We don't know what the last tower will be called.

  # Reset the time-line slider.
  @turn_slider.enabled = false
  @turn_slider.value = 0

  refresh_labels

  # Load the player's own code, which might explode!
  begin
    level.load_player
  rescue SyntaxError, StandardError => ex
    handle_exception ex
    return
  end
end


581
582
583
584
585
586
587
588
# File 'lib/ruby_armor/states/play.rb', line 581

def print(message)
  if recording_log?
    @recorded_log << message
  else
    @turn_logs[turn] << message
    @log_contents["current turn"].text = replace_log @turn_logs[turn]
  end
end

#profileObject



455
# File 'lib/ruby_armor/states/play.rb', line 455

def profile; @game.profile; end

#puts(message = "") ⇒ Object



577
578
579
# File 'lib/ruby_armor/states/play.rb', line 577

def puts(message = "")
  print "#{message}\n"
end

#record_logObject



460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/ruby_armor/states/play.rb', line 460

def record_log
  raise "block required" unless block_given?
  @recorded_log = ""
  record = ""
  begin
    yield
  ensure
    record = @recorded_log
    @recorded_log = nil
  end
  record
end

#recording_log?Boolean

Returns:

  • (Boolean)


459
# File 'lib/ruby_armor/states/play.rb', line 459

def recording_log?; not @recorded_log.nil?; end

#refresh_labelsObject



410
411
412
413
414
415
416
# File 'lib/ruby_armor/states/play.rb', line 410

def refresh_labels
  @tower_label.text =  profile.tower.name.capitalize
  @level_label.text =  "Level:  #{profile.epic? ? "E" : " "}#{level.number}"
  @level_label.tip = profile.epic? ? "Playing in EPIC mode" : "Playing in normal mode"
  @turn_label.text =   "Turn:   #{effective_turn.to_s.rjust(2)}"
  @health_label.text = "Health: #{@health[effective_turn].to_s.rjust(2)}"
end

#replace_log(string) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/ruby_armor/states/play.rb', line 439

def replace_log(string)
  @enemy_pattern ||= /([asw])/i #Archer, sludge, thick sludge, wizard.
  @friend_pattern ||= /([C])/
  @warrior_pattern ||= /([@G])/ # Player and golem

  # Used in log.
  string.gsub(/\|.*\|/i) {|c|
             c = c.gsub @enemy_pattern, '<c=ff0000>\1</c>'
             c.gsub! @friend_pattern, '<c=00dd00>\1</c>'
             c.gsub! @warrior_pattern, '<c=aaaaff>\1</c>'
             c.gsub '|', '<c=777777>|</c>'
         }
        .gsub(/^(#{profile.warrior_name}.*)/, '<c=aaaaff>\1</c>')   # Player doing stuff.
        .gsub(/(\-{3,})/, '<c=777777>\1</c>')                  # Walls.
end

#replace_syntax(string) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/ruby_armor/states/play.rb', line 426

def replace_syntax(string)
  # Used in readme.
  string.gsub!(/warrior\.[^! \n]+./) do |s|
    if s[-1, 1] == '!'
      "<c=eeee00>#{s}</c>" # Commands.
    else
      "<c=00ff00>#{s}</c>" # Queries.
    end
  end

  replace_log string
end

#save_player_codeObject



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/ruby_armor/states/play.rb', line 171

def save_player_code
  # Save the code used to complete the level for posterity.
  File.open File.join(profile.player_path, "ruby_armor/player_#{profile.epic? ? "EPIC" : level.number.to_s.rjust(3, '0')}.rb"), "w" do |file|
    file.puts @loaded_code

    file.puts
    file.puts
    file.puts "#" * 40
    file.puts "=begin"
    file.puts
    file.puts record_log { level.tally_points }
    file.puts

    if profile.epic? and @game.final_report
      file.puts @game.final_report
    else
      file.puts "Completed in #{turn} turns."
    end

    file.puts
    file.puts "=end"
    file.puts "#" * 40
  end
end

#setupObject



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
# File 'lib/ruby_armor/states/play.rb', line 46

def setup
  super

  RubyWarrior::UI.proxy = self


  on_input(:escape) { pop_game_state }

  on_input(:right_arrow) do
    if !focus and @turn_slider.enabled? and @turn_slider.value < turn
      @turn_slider.value += 1
    end
  end
  on_input(:left_arrow) do
    if !focus and @turn_slider.enabled? and @turn_slider.value > 0
      @turn_slider.value -= 1
    end
  end

  vertical spacing: 10, padding: 10 do
    horizontal padding: 0, height: 260, width: 780, spacing: 10 do |packer|
      # Space for the game graphics.
      @dungeon_view = DungeonView.new packer, @config.warrior_class

      create_ui_bar packer
    end

    @turn_slider = slider width: 774, range: 0..MAX_TURNS, value: 0, enabled: false, tip: "Turn" do |_, turn|
      @log_contents["current turn"].text = replace_log @turn_logs[turn]
      @dungeon_view.turn = turn
      refresh_labels
    end

    # Text areas at the bottom.
    horizontal padding: 0, spacing: 10 do
      create_file_tabs
      create_log_tabs
    end
  end

  # Return to normal mode if extra levels have been added.
  if profile.epic?
    if profile.level_after_epic?
      # TODO: do something with log.
      log = record_log do
        @game.go_back_to_normal_mode
      end
    else
      # TODO: do something with log.
      log = record_log do
        @game.play_epic_mode
      end
    end
  end

  prepare_level
end

#start_levelObject



418
419
420
421
422
423
424
# File 'lib/ruby_armor/states/play.rb', line 418

def start_level
  @reset_button.enabled = true
  @start_button.enabled = false
  @playing = true
  self.turn = 0
  refresh_labels
end

#sync_player_fileObject



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/ruby_armor/states/play.rb', line 388

def sync_player_file
  begin
    player_file = File.join level.player_path, "player.rb"
    player_code = File.read player_file
    stripped_code = player_code.strip
    @loaded_code ||= ""
    unless @loaded_code == stripped_code
      $stdout.puts "Detected change in player.rb"

      @file_contents["player.rb"].text = stripped_code
      @loaded_code = stripped_code
      prepare_level
    end
  rescue Errno::ENOENT
    # This can happen if the file is busy.
  end
end

#unit_health_changed(unit, amount) ⇒ Object



594
595
596
# File 'lib/ruby_armor/states/play.rb', line 594

def unit_health_changed(unit, amount)
  @dungeon_view.unit_health_changed unit, amount
end

#updateObject



598
599
600
601
602
603
604
# File 'lib/ruby_armor/states/play.rb', line 598

def update
  super

  if @playing and Time.now >= @take_next_turn_at and not (level.passed? || level.failed? || out_of_time? || @exception)
    play_turn
  end
end

#update_turn_delayObject



274
275
276
277
278
279
# File 'lib/ruby_armor/states/play.rb', line 274

def update_turn_delay
  @turn_duration_label.text = "%2d" % [(MAX_TURN_DELAY / TURN_DELAY_STEP) + 1 - (@config.turn_delay / TURN_DELAY_STEP)]
  @turn_slower_button.enabled = @config.turn_delay < MAX_TURN_DELAY
  @turn_faster_button.enabled = @config.turn_delay > MIN_TURN_DELAY
  @turn_duration_label.tip = "Speed of turns (high is faster; currently turns take #{(@config.turn_delay * 1000).to_i}ms)"
end