#!/usr/bin/ruby -w
# Encoding: UTF-8
# frozen_string_literal: true
# =========================================================================== #
# This has been inspired by the game called tetris.
# =========================================================================== #
# require 'gtk_paradise/example/advanced/moving_block_example.rb'
# =========================================================================== #
require 'gtk_paradise/require_gtk3'

TITLE = 'Moving blocks example'

alias e puts

Gtk.extend(::Gtk::BaseModule)
Gtk.initialize_default_css_provider

r = Gtk.run
r.increase_font_size
fixed = Gtk::Fixed.new
fixed.set_size_request(440, 440)

# =========================================================================== #
# === N_ITERATIONS
# =========================================================================== #
N_ITERATIONS = 15

@vbox = Gtk.vbox
@vbox.bblack3
@vbox.css_class('BG_blue')
@vbox.show_all
@vbox.set_size_request(50, 50)
@vbox.background_color(:royalblue)

@vbox2 = Gtk.vbox
@vbox2.bblack3
@vbox2.css_class('BG_green')
@vbox2.show_all
@vbox2.set_size_request(50, 50)
@vbox2.background_color(:green)

frame = Gtk.frame(' Moving Block Example ')
frame.set_font(:hack_25)
frame.make_bold
frame.add(fixed)
frame.set_border_width(20)
position = 20+rand(15)
fixed.put(@vbox, 10, position)
fixed.put(@vbox2, 80, position)

counter = 0

# This is the logic that will re-position the blocks.
GLib::Timeout.add(500) {
  counter += 1
  if counter < N_ITERATIONS
    position += 15
    position = 400 if position > 400
    e "Position is now at: #{position}"
    # ======================================================================= #
    # Here is the relocation-specific tidbit, via .move():
    # ======================================================================= #
    fixed.move(@vbox, 10, position)
    fixed.move(@vbox2, 80, position)
    true # Keep it on!
  else
    false # Else stop it when the counter ran too high.
  end
}

r.add(frame)
r.modify_background(:normal, :white)
r.signal_connect(:key_press_event) {|widget, event|
  if event.is_key?(:down)
    # The user pressed the down-key here.
    position += 15
    position = 400 if position > 400
    e "Position is now at: #{position}"
    fixed.move(@vbox, 10, position)
  # else
  end
}
r.set_title(TITLE)
r.top_left_then_run