Andy Maleh
Posted on August 4, 2021
Glimmer DSL for SWT 4.20.13.14 shipped with a Connect 4 elaborate sample. It is implemented as a 2-player game that is very similar to Tic Tac Toe in implementation except that it relies on a hybrid canvas widget/shape approach to lay out the slots.
I'll let the GUI code speak for itself.
# From: https://github.com/AndyObtiva/glimmer-dsl-swt/blob/master/docs/reference/GLIMMER_SAMPLES.md#connect-4
require 'glimmer-dsl-swt'
require_relative 'connect4/model/grid'
class Connect4
include Glimmer::UI::CustomShell
WIDTH = 7
HEIGHT = 6
COLOR_BACKGROUND = rgb(63, 104, 212)
COLOR_EMPTY_SLOT = :white
COLOR_COIN1 = rgb(236, 223, 56)
COLOR_COIN2 = rgb(176, 11, 23)
attr_accessor :current_player_color
before_body do
@grid = Model::Grid.new(WIDTH, HEIGHT)
select_player_color
end
after_body do
observe(@grid, :current_player) do
select_player_color
end
observe(@grid, :game_over) do |game_over_value|
if game_over_value
game_over_message = case game_over_value
when true
"Game over!\nDraw!"
when 1
"Game over!\nPlayer 1 (yellow) wins!"
when 2
"Game over!\nPlayer 2 (red) wins!"
end
message_box {
text 'Game Over!'
message game_over_message
}.open
@grid.restart!
end
end
end
body {
shell(:no_resize) {
grid_layout(7, true)
text 'Glimmer Connect 4'
background COLOR_BACKGROUND
HEIGHT.times do |row_index|
WIDTH.times do |column_index|
canvas {
layout_data {
width_hint 50
height_hint 50
}
background :transparent
the_oval = oval(0, 0, 50, 50) {
background <= [@grid.slot_rows[row_index][column_index], :value, on_read: ->(v) { v == 0 ? COLOR_EMPTY_SLOT : (v == 1 ? COLOR_COIN1 : COLOR_COIN2)}]
}
if row_index == 0
entered = false
on_mouse_enter do
entered = true
the_oval.background = current_player_color if @grid.slot_rows[row_index][column_index].value == 0
end
on_mouse_exit do
entered = false
the_oval.background = COLOR_EMPTY_SLOT if @grid.slot_rows[row_index][column_index].value == 0
end
on_mouse_up do
@grid.insert!(column_index)
the_oval.background = current_player_color if entered && @grid.slot_rows[row_index][column_index].value == 0
end
end
}
end
end
}
}
def select_player_color
self.current_player_color = @grid.current_player == 1 ? COLOR_COIN1 : COLOR_COIN2
end
end
Connect4.launch
About to drop by pointing to top slot
Happy Glimmering!
💖 💪 🙅 🚩
Andy Maleh
Posted on August 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
ruby Glimmer DSL for SWT Table Cell Data-Binding of Background/Foreground/Font/Image
September 2, 2022