repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_tray_item.rb | samples/hello/hello_tray_item.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
class HelloTrayItem
include Glimmer::UI::CustomShell
# boolean that indicates if application is visible
attr_accessor :show_application
before_body do
# application starts visible
@show_application = true
# pre-render an icon image using the Canvas Shape DSL
@image = image(16, 16) {
rectangle(0, 0, 16, 16) {
background :black
}
oval(1, 1, [:default, - 2], [:default, - 2]) {
foreground :white
}
oval(3, 3, [:default, - 6], [:default, - 6]) {
foreground :white
}
oval(5, 5, [:default, - 10], [:default, - 10]) {
foreground :white
}
oval(7, 7, [:default, - 14], [:default, - 14]) {
foreground :white
}
}
end
body {
shell(:shell_trim, :on_top) { # make it always appear on top of everything
row_layout(:vertical) {
center true
}
text 'Hello, Tray Item!'
on_shell_closed do |event|
# do not perform event that closes app when shell is closed
event.doit = false
# body_root is the root shell
body_root.hide
self.show_application = false # updates Show Application checkbox menu item indirectly
end
tray_item {
tool_tip_text 'Glimmer'
image @image # could use an image path instead
menu {
menu_item {
text 'About'
on_widget_selected do
message_box {
text 'Glimmer - About'
message 'This is a Glimmer DSL for SWT Tray Item'
}.open
end
}
menu_item(:separator)
menu_item(:check) {
text 'Show Application'
selection <=> [self, :show_application]
on_widget_selected do
# body_root is the root shell
if body_root.visible?
body_root.hide
else
body_root.show
end
end
}
menu_item(:separator)
menu_item {
text 'Exit'
on_widget_selected do
exit(0)
end
}
}
# supported tray item listeners (you can try to add actions to them when needed)
# on_widget_selected do
# end
#
# on_menu_detected do
# end
}
label(:center) {
text 'This is the application'
font height: 30
}
label {
text 'Click on the tray item (circles icon) to open its menu'
}
label {
text 'Uncheck Show Application to hide the app and recheck it to show the app'
}
}
}
end
HelloTrayItem.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_text.rb | samples/hello/hello_text.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
class HelloText
include Glimmer::UI::CustomShell
attr_accessor :default, :no_border, :center, :left, :right, :password, :telephone, :read_only, :wrap, :multi
before_body do
self.default = 'default is :border style'
self.no_border = 'no border'
self.center = 'centered'
self.left = 'left-aligned'
self.right = 'right-aligned'
self.password = 'password'
self.telephone = '555-555-5555'
self.read_only = 'Telephone area code is 555'
self.wrap = 'wraps if text content is too long like this example'
self.multi = "multi-line enables hitting enter,\nbut does not wrap by default"
end
body {
shell {
grid_layout 2, false
text 'Hello, Text!'
minimum_size 350, 100
label {
text 'text'
}
text { # includes :border style by default
layout_data :fill, :center, true, false
text <=> [self, :default]
}
label {
text 'text(:none)'
}
text(:none) { # no border
layout_data :fill, :center, true, false
text <=> [self, :no_border]
}
label {
text 'text(:center, :border)'
}
text(:center, :border) {
layout_data :fill, :center, true, false
text <=> [self, :center]
}
label {
text 'text(:left, :border)'
}
text(:left, :border) {
layout_data :fill, :center, true, false
text <=> [self, :left]
}
label {
text 'text(:right, :border)'
}
text(:right, :border) {
layout_data :fill, :center, true, false
text <=> [self, :right]
}
label {
text 'text(:password, :border)'
}
text(:password, :border) {
layout_data :fill, :center, true, false
text <=> [self, :password]
}
label {
text 'text(:read_only, :border)'
}
text(:read_only, :border) {
layout_data :fill, :center, true, false
text <= [self, :read_only]
}
label {
text 'text with event handlers'
}
text {
layout_data :fill, :center, true, false
text <=> [self, :telephone]
# this event kicks in just after the user typed and before modifying the text attribute value
on_verify_text do |verify_event|
new_text = verify_event.widget.text.clone
new_text[verify_event.start...verify_event.end] = verify_event.text
verify_event.doit = telephone?(new_text)
end
# this event kicks in just after the text widget is verified and modified
on_modify_text do |modify_event|
self.read_only = "Telephone area code is #{modify_event.widget.text.gsub(/[^0-9]/, '')[0...3]}"
end
}
label {
text 'text(:wrap, :border)'
}
text(:wrap, :border) {
layout_data(:fill, :center, true, false) {
width_hint 100
}
text <=> [self, :wrap]
}
label {
text 'text(:multi, :border)'
}
text(:multi, :border) {
layout_data :fill, :center, true, false
text <=> [self, :multi]
}
}
}
def telephone?(text)
!!text.match(/^\d{0,3}[-.\/]?\d{0,3}[-.\/]?\d{0,4}$/)
end
end
HelloText.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/clock.rb | samples/elaborate/clock.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Clock
include Glimmer::UI::CustomShell
body {
shell {
text 'Glimmer Clock'
minimum_size 400, 430
canvas {
initial_time = Time.now
background :black
animation {
every 0.01 # every hundredth of a second to ensure higher accuracy
frame { |index|
time = Time.now
oval(0, 0, 400, 400) {
background :white
}
polygon(-5, -5, 180, 0, -5, 5) {
background :black
transform {
translate 200, 200
rotate(time.sec*6 - 90)
}
}
polygon(-5, -5, 135, 0, -5, 5) {
background :dark_gray
transform {
translate 200, 200
rotate(time.min*6 - 90)
}
}
polygon(-5, -5, 90, 0, -5, 5) {
background :gray
transform {
translate 200, 200
rotate((time.hour - 12)*30 - 90)
}
}
}
}
}
}
}
end
Clock.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/contact_manager.rb | samples/elaborate/contact_manager.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative "contact_manager/contact_manager_presenter"
class ContactManager
include Glimmer::UI::CustomShell
before_body do
@contact_manager_presenter = ContactManagerPresenter.new
@contact_manager_presenter.list
end
body {
shell {
text "Contact Manager"
composite {
group {
grid_layout(2, false) {
margin_width 0
margin_height 0
}
layout_data :fill, :center, true, false
text 'Lookup Contacts'
font height: 24
label {
layout_data :right, :center, false, false
text "First &Name: "
font height: 16
}
text {
layout_data :fill, :center, true, false
text <=> [@contact_manager_presenter, :first_name]
on_key_pressed do |key_event|
@contact_manager_presenter.find if key_event.keyCode == swt(:cr)
end
}
label {
layout_data :right, :center, false, false
text "&Last Name: "
font height: 16
}
text {
layout_data :fill, :center, true, false
text <=> [@contact_manager_presenter, :last_name]
on_key_pressed do |key_event|
@contact_manager_presenter.find if key_event.keyCode == swt(:cr)
end
}
label {
layout_data :right, :center, false, false
text "&Email: "
font height: 16
}
text {
layout_data :fill, :center, true, false
text <=> [@contact_manager_presenter, :email]
on_key_pressed do |key_event|
@contact_manager_presenter.find if key_event.keyCode == swt(:cr)
end
}
composite {
row_layout {
margin_width 0
margin_height 0
}
layout_data(:right, :center, false, false) {
horizontal_span 2
}
button {
text "&Create"
on_widget_selected do
create_contact
end
on_key_pressed do |key_event|
create_contact if key_event.keyCode == swt(:cr)
end
}
button {
text "&Find"
on_widget_selected do
@contact_manager_presenter.find
end
on_key_pressed do |key_event|
@contact_manager_presenter.find if key_event.keyCode == swt(:cr)
end
}
button {
text "&List All"
on_widget_selected do
@contact_manager_presenter.list
end
on_key_pressed do |key_event|
@contact_manager_presenter.list if key_event.keyCode == swt(:cr)
end
}
}
}
@table = table(:editable, :border) { |table_proxy|
layout_data {
horizontal_alignment :fill
vertical_alignment :fill
grab_excess_horizontal_space true
grab_excess_vertical_space true
height_hint 200
}
table_column {
text "First Name"
width 80
}
table_column {
text "Last Name"
width 80
}
table_column {
text "Email"
width 200
}
menu {
menu_item {
text '&Delete'
on_widget_selected do
@contact_manager_presenter.delete
end
}
}
items <=> [@contact_manager_presenter, :results]
selection <=> [@contact_manager_presenter, :selected_contact]
on_mouse_up do |event|
table_proxy.edit_table_item(event.table_item, event.column_index)
end
}
}
}
}
def create_contact
created_contact = @contact_manager_presenter.create
new_item = @table.search do |table_item|
model = table_item.data # get model embodied by table item
created_contact == model
end.first
@table.setSelection(new_item) # set selection with Table SWT API
@table.showSelection # show selection with Table SWT API
end
end
ContactManager.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/mandelbrot_fractal.rb | samples/elaborate/mandelbrot_fractal.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require 'complex'
require 'concurrent/executor/fixed_thread_pool'
require 'concurrent/utility/processor_counter'
require 'concurrent/array'
# Mandelbrot multi-threaded implementation leveraging all processor cores.
class Mandelbrot
DEFAULT_STEP = 0.0030
Y_START = -1.0
Y_END = 1.0
X_START = -2.0
X_END = 0.5
PROGRESS_MAX = 40
class << self
attr_accessor :progress, :work_in_progress
attr_writer :processor_count
def for(max_iterations:, zoom:, background: false)
key = [max_iterations, zoom]
creation_mutex.synchronize do
unless flyweight_mandelbrots.keys.include?(key)
flyweight_mandelbrots[key] = new(max_iterations: max_iterations, zoom: zoom, background: background)
end
end
flyweight_mandelbrots[key].background = background
flyweight_mandelbrots[key]
end
def flyweight_mandelbrots
@flyweight_mandelbrots ||= {}
end
def creation_mutex
@creation_mutex ||= Mutex.new
end
def processor_count
@processor_count ||= Concurrent.processor_count
end
end
attr_accessor :max_iterations, :background
attr_reader :zoom, :points_calculated
alias points_calculated? points_calculated
# max_iterations is the maximum number of Mandelbrot calculation iterations
# zoom is how much zoom there is on the Mandelbrot points from the default view of zoom 1
# background indicates whether to do calculation in the background for caching purposes,
# thus utilizing less CPU cores to avoid disrupting user experience
def initialize(max_iterations:, zoom: 1.0, background: false)
@max_iterations = max_iterations
@zoom = zoom
end
def step
DEFAULT_STEP / zoom
end
def y_array
@y_array ||= Y_START.step(Y_END, step).to_a
end
def x_array
@x_array ||= X_START.step(X_END, step).to_a
end
def height
y_array.size
end
def width
x_array.size
end
def points
@points ||= calculate_points
end
def calculate_points
puts "Background calculation activated at zoom #{zoom}" if @background
if @points_calculated
puts "Points calculated already. Returning previously calculated points..."
return @points
end
@thread_pool = Concurrent::FixedThreadPool.new(Mandelbrot.processor_count, fallback_policy: :discard)
@points = Concurrent::Array.new(height)
Mandelbrot.work_in_progress = "Calculating Mandelbrot Points for Zoom #{zoom}x"
Mandelbrot.progress = 0
point_index = 0
point_count = width*height
height.times do |y|
@points[y] ||= Concurrent::Array.new(width)
width.times do |x|
@thread_pool.post do
@points[y][x] = calculate(x_array[x], y_array[y]).last
point_index += 1
Mandelbrot.progress += 1 if (point_index.to_f / point_count.to_f)*PROGRESS_MAX >= Mandelbrot.progress
end
end
end
@thread_pool.shutdown
@thread_pool.wait_for_termination
Mandelbrot.progress = PROGRESS_MAX
@points_calculated = true
@points
end
# Calculates a Mandelbrot point, borrowing some open-source code from:
# https://github.com/gotbadger/ruby-mandelbrot
def calculate(x,y)
base_case = [Complex(x,y), 0]
Array.new(max_iterations, base_case).inject(base_case) do |prev ,base|
z, itr = prev
c, _ = base
val = z*z + c
itr += 1 unless val.abs < 2
[val, itr]
end
end
end
class MandelbrotFractal
include Glimmer::UI::CustomShell
COMMAND = OS.mac? ? :command : :ctrl
attr_accessor :mandelbrot_shell_title
option :zoom, default: 1.0
before_body do
Display.app_name = 'Mandelbrot Fractal'
# pre-calculate mandelbrot image
@mandelbrot_image = build_mandelbrot_image
end
after_body do
observe(Mandelbrot, :work_in_progress) do
update_mandelbrot_shell_title!
end
observe(Mandelbrot, :zoom) do
update_mandelbrot_shell_title!
end
# pre-calculate zoomed mandelbrot images even before the user zooms in
puts 'Starting background calculation thread...'
@thread = Thread.new do
future_zoom = 1.5
loop do
puts "Creating mandelbrot for background calculation at zoom: #{future_zoom}"
the_mandelbrot = Mandelbrot.for(max_iterations: color_palette.size - 1, zoom: future_zoom, background: true)
pixels = the_mandelbrot.calculate_points
build_mandelbrot_image(mandelbrot_zoom: future_zoom)
@canvas.cursor = :cross unless @canvas.disposed?
future_zoom += 0.5
end
end
end
body {
shell(:no_resize) {
grid_layout
text <= [self, :mandelbrot_shell_title]
minimum_size mandelbrot.width + 29, mandelbrot.height + 77
image @mandelbrot_image
on_shell_closed do
@thread.kill # should not be dangerous in this case
puts "Mandelbrot background calculation stopped!"
end
progress_bar {
layout_data :fill, :center, true, false
minimum 0
maximum Mandelbrot::PROGRESS_MAX
selection <= [Mandelbrot, :progress]
}
@scrolled_composite = scrolled_composite {
layout_data :fill, :fill, true, true
@canvas = canvas {
image @mandelbrot_image
cursor :no
on_mouse_down do
@drag_detected = false
@canvas.cursor = :hand
end
on_drag_detected do |drag_detect_event|
@drag_detected = true
@drag_start_x = drag_detect_event.x
@drag_start_y = drag_detect_event.y
end
on_mouse_move do |mouse_event|
if @drag_detected
origin = @scrolled_composite.origin
new_x = origin.x - (mouse_event.x - @drag_start_x)
new_y = origin.y - (mouse_event.y - @drag_start_y)
@scrolled_composite.set_origin(new_x, new_y)
end
end
on_mouse_up do |mouse_event|
if !@drag_detected
origin = @scrolled_composite.origin
@location_x = mouse_event.x
@location_y = mouse_event.y
if mouse_event.button == 1
zoom_in
elsif mouse_event.button > 2
zoom_out
end
end
@canvas.cursor = can_zoom_in? ? :cross : :no
@drag_detected = false
end
}
}
menu_bar {
menu {
text '&View'
menu_item {
text 'Zoom &In'
accelerator COMMAND, '+'
on_widget_selected do
zoom_in
end
}
menu_item {
text 'Zoom &Out'
accelerator COMMAND, '-'
on_widget_selected do
zoom_out
end
}
menu_item {
text '&Reset Zoom'
accelerator COMMAND, '0'
on_widget_selected do
perform_zoom(mandelbrot_zoom: 1.0)
end
}
}
menu {
text '&Cores'
Concurrent.processor_count.times do |n|
processor_number = n + 1
menu_item(:radio) {
text "&#{processor_number}"
case processor_number
when 0..9
accelerator COMMAND, processor_number.to_s
when 10..19
accelerator COMMAND, :shift, (processor_number - 10).to_s
when 20..29
accelerator COMMAND, :alt, (processor_number - 20).to_s
end
selection true if processor_number == Concurrent.processor_count
on_widget_selected do
Mandelbrot.processor_count = processor_number
end
}
end
}
menu {
text '&Help'
menu_item {
text '&Instructions'
accelerator COMMAND, :shift, :i
on_widget_selected do
display_help_instructions
end
}
}
}
}
}
def update_mandelbrot_shell_title!
new_title = "Mandelbrot Fractal - Zoom #{zoom}x (Calculated Max: #{flyweight_mandelbrot_images.keys.max}x)"
new_title += " - #{Mandelbrot.work_in_progress}" if Mandelbrot.work_in_progress
self.mandelbrot_shell_title = new_title
end
def build_mandelbrot_image(mandelbrot_zoom: nil)
mandelbrot_zoom ||= zoom
unless flyweight_mandelbrot_images.keys.include?(mandelbrot_zoom)
the_mandelbrot = mandelbrot(mandelbrot_zoom: mandelbrot_zoom)
width = the_mandelbrot.width
height = the_mandelbrot.height
pixels = the_mandelbrot.points
Mandelbrot.work_in_progress = "Consuming Points To Build Image for Zoom #{mandelbrot_zoom}x"
Mandelbrot.progress = Mandelbrot::PROGRESS_MAX + 1
point_index = 0
point_count = width*height
# invoke as a top-level parentless keyword to avoid nesting under any widget
new_mandelbrot_image = image(width, height, top_level: true) { |x, y|
point_index += 1
Mandelbrot.progress -= 1 if (Mandelbrot::PROGRESS_MAX - (point_index.to_f / point_count.to_f)*Mandelbrot::PROGRESS_MAX) < Mandelbrot.progress
pixel_color_index = pixels[y][x]
color_palette[pixel_color_index]
}
Mandelbrot.progress = 0
flyweight_mandelbrot_images[mandelbrot_zoom] = new_mandelbrot_image
update_mandelbrot_shell_title!
end
flyweight_mandelbrot_images[mandelbrot_zoom]
end
def flyweight_mandelbrot_images
@flyweight_mandelbrot_images ||= {}
end
def mandelbrot(mandelbrot_zoom: nil)
mandelbrot_zoom ||= zoom
Mandelbrot.for(max_iterations: color_palette.size - 1, zoom: mandelbrot_zoom)
end
def color_palette
if @color_palette.nil?
@color_palette = [[0, 0, 0]] + 40.times.map { |i| [255 - i*5, 255 - i*5, 55 + i*5] }
@color_palette = @color_palette.map { |color_data| rgb(*color_data).swt_color }
end
@color_palette
end
def zoom_in
if can_zoom_in?
perform_zoom(zoom_delta: 0.5)
@canvas.cursor = can_zoom_in? ? :cross : :no
end
end
def can_zoom_in?
flyweight_mandelbrot_images.keys.include?(zoom + 0.5)
end
def zoom_out
perform_zoom(zoom_delta: -0.5)
end
def perform_zoom(zoom_delta: 0, mandelbrot_zoom: nil)
mandelbrot_zoom ||= self.zoom + zoom_delta
@canvas.cursor = :wait
last_zoom = self.zoom
self.zoom = [mandelbrot_zoom, 1.0].max
@canvas.clear_shapes(dispose_images: false)
@mandelbrot_image = build_mandelbrot_image
body_root.content {
image @mandelbrot_image
}
@canvas.content {
image @mandelbrot_image
}
@canvas.set_size @mandelbrot_image.bounds.width, @mandelbrot_image.bounds.height
@scrolled_composite.set_min_size(Point.new(@mandelbrot_image.bounds.width, @mandelbrot_image.bounds.height))
if @location_x && @location_y
# center on mouse click location
factor = (zoom / last_zoom)
@scrolled_composite.set_origin(factor*@location_x - @scrolled_composite.client_area.width/2.0, factor*@location_y - @scrolled_composite.client_area.height/2.0)
@location_x = @location_y = nil
end
update_mandelbrot_shell_title!
@canvas.cursor = :cross
end
def display_help_instructions
message_box(body_root) {
text 'Mandelbrot Fractal - Help'
message <<~MULTI_LINE_STRING
The Mandelbrot Fractal precalculates zoomed renderings in the background. Wait if you hit a zoom level that is not calculated yet.
Left-click to zoom in.
Right-click to zoom out.
Scroll or drag to pan.
Adjust cores to get a more responsive interaction.
Enjoy!
MULTI_LINE_STRING
}.open
end
end
MandelbrotFractal.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/user_profile.rb | samples/elaborate/user_profile.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
include Glimmer
# A version of this was featured in a dzone article as an intro to Glimmer syntax:
# https://dzone.com/articles/an-introduction-glimmer
shell { |shell_proxy|
text "User Profile"
composite {
grid_layout 2, false
group {
grid_layout 2, false
layout_data :fill, :fill, true, true
text "Name"
label {
text "First"
}
text {
text "Bullet"
}
label {
text "Last"
}
text {
text "Tooth"
}
}
group {
layout_data :fill, :fill, true, true
text "Gender"
radio {
text "Male"
selection true
}
radio {
text "Female"
}
}
group {
layout_data :fill, :fill, true, true
text "Role"
check {
text "Student"
selection true
}
check {
text "Employee"
selection true
}
}
group {
row_layout
layout_data :fill, :fill, true, true
text "Experience"
spinner {
selection 5
}
label {
text "years"
}
}
button {
layout_data :right, :center, true, true
text "save"
on_widget_selected do
message_box {
text 'Profile Saved!'
message 'User profile has been saved!'
}.open
end
}
button {
layout_data :left, :center, true, true
text "close"
on_widget_selected do
shell_proxy.close
end
}
}
}.open
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/stock_ticker.rb | samples/elaborate/stock_ticker.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
# This Sample is an Early Alpha (New Canvas Path DSL Feature)
class StockTicker
class Stock
class << self
attr_writer :price_min, :price_max
def price_min
@price_min ||= 1
end
def price_max
@price_max ||= 600
end
end
attr_reader :name, :prices
attr_accessor :price
def initialize(name, price)
@name = name
@price = price
@prices = [@price]
@delta_sign = 1
start_new_trend!
end
def tick!
@tick_count = @tick_count.to_i + 1
delta = @tick_count%@trend_length
if delta == 0
@delta_sign *= -1
start_new_trend!
end
prices << self.price = [[@price + @delta_sign*delta, Stock.price_min].max, Stock.price_max].min
end
def start_new_trend!
@trend_length = (rand*12).to_i + 1
end
end
include Glimmer::UI::CustomShell
before_body do
@stocks = [
Stock.new('DELL', 81),
Stock.new('AAPL', 121),
Stock.new('MSFT', 232),
Stock.new('ADBE', 459),
]
@stock_colors = [:red, :dark_green, :blue, :dark_magenta]
margin = 5
@tabs = ['Lines', 'Quadratic Bezier Curves', 'Cubic Bezier Curves', 'Points'].map {|title| {title: title, stock_paths: []}}
@stocks.each_with_index do |stock, stock_index|
observe(stock, :price) do |new_price|
begin
@tabs.each do |tab|
new_x = stock.prices.count - 1
new_y = @tabs.first[:canvas].bounds.height - new_price - 1
if new_x > 0
case tab[:title]
when 'Cubic Bezier Curves'
if new_x%3 == 0 && stock.prices[new_x] && stock.prices[new_x - 1] && stock.prices[new_x - 2]
tab[:stock_paths][stock_index].content {
cubic(new_x - 2 + margin, @tabs.first[:canvas].bounds.height - stock.prices[new_x - 2] - 1, new_x - 1 + margin, @tabs.first[:canvas].bounds.height - stock.prices[new_x - 1] - 1, new_x + margin, new_y)
}
end
when 'Quadratic Bezier Curves'
if new_x%2 == 0 && stock.prices[new_x] && stock.prices[new_x - 1]
tab[:stock_paths][stock_index].content {
quad(new_x - 1 + margin, @tabs.first[:canvas].bounds.height - stock.prices[new_x - 1] - 1, new_x + margin, new_y)
}
end
when 'Lines'
tab[:stock_paths][stock_index].content {
line(new_x + margin, new_y)
}
when 'Points'
tab[:stock_paths][stock_index].content {
point(new_x + margin, new_y)
}
end
new_x_location = new_x + 2*margin
canvas_width = tab[:canvas].bounds.width
if new_x_location > canvas_width
tab[:canvas].set_size(new_x_location, @tabs.first[:canvas].bounds.height)
tab[:canvas].cursor = :hand
tab[:scrolled_composite].set_min_size(new_x_location, @tabs.first[:canvas].bounds.height)
tab[:scrolled_composite].set_origin(tab[:scrolled_composite].origin.x + 1, tab[:scrolled_composite].origin.y) if (tab[:scrolled_composite].origin.x + tab[:scrolled_composite].client_area.width + (OS.mac? ? 0 : 20)) == canvas_width
end
else
tab[:canvas_header].content {
text(stock.name, 15, new_y - 10) {
foreground @stock_colors[stock_index]
font height: 13
}
}
end
end
rescue => e
Glimmer::Config.logger.error {e.full_message}
end
end
end
end
after_body do
@thread = Thread.new do
loop do
@stocks.each(&:tick!)
sleep(0.01)
end
end
end
body {
shell {
fill_layout {
margin_width 15
margin_height 15
}
text 'Stock Ticker'
minimum_size 650, 650
background :white
@tab_folder = tab_folder {
@tabs.each do |tab|
tab_item {
grid_layout(2, false) {
margin_width 0
margin_height 0
}
text tab[:title]
tab[:canvas_header] = canvas {
layout_data(:center, :fill, false, true)
}
tab[:scrolled_composite] = scrolled_composite {
layout_data :fill, :fill, true, true
tab[:canvas] = canvas {
background :white
@stocks.count.times do |stock_index|
tab[:stock_paths][stock_index] = path {
antialias :on
foreground @stock_colors[stock_index]
}
end
on_mouse_down do
@drag_detected = false
end
on_drag_detected do |drag_detect_event|
@drag_detected = true
@drag_start_x = drag_detect_event.x
@drag_start_y = drag_detect_event.y
end
on_mouse_move do |mouse_event|
if @drag_detected
origin = tab[:scrolled_composite].origin
new_x = origin.x - (mouse_event.x - @drag_start_x)
new_y = origin.y - (mouse_event.y - @drag_start_y)
tab[:scrolled_composite].set_origin(new_x, new_y)
end
end
on_mouse_up do |mouse_event|
@drag_detected = false
end
}
}
}
end
}
on_swt_show do
Stock.price_min = 25
Stock.price_max = @tabs.first[:canvas].bounds.height - 6
end
on_widget_disposed do
@thread.kill # safe to kill as data is in memory only
end
}
}
end
StockTicker.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/meta_sample.rb | samples/elaborate/meta_sample.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require 'fileutils'
require 'yaml'
require 'net/http'
class Sample
UNEDITABLE = ['meta_sample.rb'] + (OS.windows? ? ['calculator.rb', 'weather.rb'] : []) # Windows StyledText does not support unicode characters found in certain samples
URL_TUTORIALS = 'https://raw.githubusercontent.com/AndyObtiva/glimmer-dsl-swt/master/samples/elaborate/meta_sample/tutorials.yml'
FILE_TUTORIALS = File.expand_path(File.join('meta_sample', 'tutorials.yml'), __dir__)
TUTORIALS = YAML.load_file(FILE_TUTORIALS)
class << self
def glimmer_directory
File.expand_path('../../..', __FILE__)
end
def user_glimmer_directory
File.join(File.expand_path('~'), '.glimmer-dsl-swt')
end
def ensure_user_glimmer_directory
unless @ensured_glimmer_directory
Thread.new do
FileUtils.rm_rf(user_glimmer_directory)
FileUtils.cp_r(glimmer_directory, user_glimmer_directory)
@ensured_glimmer_directory = true
end
end
end
def tutorials
if remote_tutorials && !remote_tutorials.empty? && remote_tutorials.size >= local_tutorials.size
remote_tutorials
else
local_tutorials
end
end
def remote_tutorials
if @remote_tutorials.nil?
remote_tutorials_response = Net::HTTP.get_response(URI(URL_TUTORIALS))
raise "Error downloading remote tutorial list from #{URL_TUTORIALS} (defaulting to local list): HTTP status #{remote_tutorials_response.code} #{remote_tutorials_response.message}!" unless remote_tutorials_response.code.to_i.between?(200, 299)
remote_tutorials_yaml = remote_tutorials_response.body
@remote_tutorials = YAML.load(remote_tutorials_yaml)
end
@remote_tutorials
rescue => e
Glimmer::Config.logger.error e.full_message
nil
end
def local_tutorials
TUTORIALS
end
end
include Glimmer::DataBinding::ObservableModel
attr_accessor :sample_directory, :file, :selected
def initialize(file, sample_directory: )
self.file = file
self.sample_directory = sample_directory
end
def name
if @name.nil?
@name = File.basename(file, '.rb').split('_').map(&:capitalize).join(' ')
if @name.start_with?('Hello')
name_parts = @name.split
name_parts[0] = name_parts.first + ','
name_parts[-1] = name_parts.last + '!'
@name = name_parts.join(' ')
end
end
@name
end
def code
reset_code! if @code.nil?
@code
end
def reset_code!
@code = File.read(file)
notify_observers('code')
end
def editable
!UNEDITABLE.include?(File.basename(file))
end
alias editable? editable
def launchable
File.basename(file) != 'meta_sample.rb'
end
def teachable
!!tutorial
end
def tutorial
Sample.tutorials[name]
end
def file_relative_path
file.sub(Sample.glimmer_directory, '')
end
def user_file
File.join(Sample.user_glimmer_directory, file_relative_path)
end
def user_file_parent_directory
File.dirname(user_file)
end
def directory
file.sub(/\.rb/, '')
end
def launch(modified_code)
launch_file = user_file
begin
raise 'Unsupported through editor!' unless editable?
FileUtils.cp_r(file, user_file_parent_directory)
FileUtils.cp_r(directory, user_file_parent_directory) if File.exist?(directory)
File.write(user_file, modified_code)
rescue => e
puts 'Error writing sample modifications. Launching original sample.'
puts e.full_message
launch_file = file # load original file if failed to write changes
end
load(launch_file)
end
end
class SampleDirectory
class << self
attr_accessor :selected_sample
def sample_directories
if @sample_directories.nil?
@sample_directories = Dir.glob(File.join(File.expand_path('..', __FILE__), '*')).
select { |file| File.directory?(file) }.
map { |file| SampleDirectory.new(file) }
glimmer_gems = Gem.find_latest_files("glimmer-*-*")
sample_directories = glimmer_gems.map do |lib|
File.dirname(File.dirname(lib))
end.select do |gem|
Dir.exist?(File.join(gem, 'samples'))
end.map do |gem|
Dir.glob(File.join(gem, 'samples', '*')).select {|file_or_dir| Dir.exist?(file_or_dir)}
end.flatten.uniq.reverse
if Dir.exist?('samples')
Dir.glob(File.join('samples', '*')).to_a.reverse.each do |dir|
sample_directories << dir if Dir.exist?(dir)
end
end
sample_directories = sample_directories.uniq {|dir| File.basename(dir)}
@sample_directories = sample_directories.map { |file| SampleDirectory.new(file) }
end
@sample_directories
end
def all_samples
@all_samples ||= sample_directories.map(&:samples).reduce(:+)
end
end
include Glimmer # used for observe syntax
attr_accessor :file, :selected_sample_name
def initialize(file)
self.file = file
end
def name
File.basename(file).split('_').map(&:capitalize).join(' ')
end
def samples
if @samples.nil?
@samples = Dir.glob(File.join(file, '*')).
select { |file| File.file?(file) }.
map { |sample_file| Sample.new(sample_file, sample_directory: self) }.
sort_by(&:name)
@samples.each do |sample|
observe(sample, :selected) do |new_selected_value|
if new_selected_value
SampleDirectory.all_samples.reject {|a_sample| a_sample.name == sample.name}.each do |other_sample|
other_sample.selected = false
end
SampleDirectory.selected_sample = sample
end
end
end
end
@samples
end
def selected_sample_name_options
samples.map(&:name)
end
def selected_sample_name=(selected_name)
@selected_sample_name = selected_name
unless selected_name.nil?
(SampleDirectory.sample_directories - [self]).each { |sample_dir| sample_dir.selected_sample_name = nil }
SampleDirectory.selected_sample = samples.detect { |sample| sample.name == @selected_sample_name }
end
end
end
class MetaSampleApplication
include Glimmer::UI::CustomShell
before_body do
Sample.ensure_user_glimmer_directory
selected_sample_directory = SampleDirectory.sample_directories.first
selected_sample = selected_sample_directory.samples.first
selected_sample_directory.selected_sample_name = selected_sample.name
Display.app_name = 'Glimmer Meta-Sample'
end
body {
shell(:fill_screen) {
minimum_size 640, 384
text 'Glimmer Meta-Sample (The Sample of Samples)'
image File.expand_path('../../icons/scaffold_app.png', __dir__)
sash_form {
weights 1, 3
composite {
grid_layout(1, false) {
margin_width 0
margin_height 0
}
expand_bar {
layout_data(:fill, :fill, true, true)
font height: 25
SampleDirectory.sample_directories.each { |sample_directory|
expand_item {
layout_data(:fill, :fill, true, true)
text " #{sample_directory.name} Samples (#{sample_directory.samples.count})"
radio_group { |radio_group_proxy|
row_layout(:vertical) {
fill true
}
selection <=> [sample_directory, :selected_sample_name]
font height: 20
}
}
}
}
composite {
fill_layout
layout_data(:fill, :center, true, false) {
height_hint 96
}
button {
text 'Tutorial'
font height: 25
enabled <= [SampleDirectory, 'selected_sample.teachable']
on_widget_selected do
shell(:fill_screen) {
text "Glimmer DSL for SWT Video Tutorial - #{SampleDirectory.selected_sample.name}"
browser {
text "<iframe src='https://www.youtube.com/embed/#{SampleDirectory.selected_sample.tutorial}?autoplay=1' title='YouTube video player' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen style='width: 100%; height: 100%;'></iframe>"
}
}.open
end
}
button {
text 'Launch'
font height: 25
enabled <= [SampleDirectory, 'selected_sample.launchable']
on_widget_selected do
begin
SampleDirectory.selected_sample.launch(@code_text.text)
rescue LoadError, StandardError, SyntaxError => launch_error
error_dialog(message: launch_error.full_message).open
end
end
}
button {
text 'Reset'
font height: 25
enabled <= [SampleDirectory, 'selected_sample.editable']
on_widget_selected do
SampleDirectory.selected_sample.reset_code!
end
}
}
}
@code_text = code_text(lines: {width: 3}) {
root {
grid_layout(2, false) {
horizontal_spacing 0
margin_left 0
margin_right 0
margin_top 0
margin_bottom 0
}
}
line_numbers {
background Display.system_dark_theme? ? :black : :white
}
text <=> [SampleDirectory, 'selected_sample.code']
editable <= [SampleDirectory, 'selected_sample.editable']
left_margin 7
right_margin 7
}
}
}
}
# Method-based error_dialog custom widget
def error_dialog(message:)
return if message.nil?
dialog(body_root) { |dialog_proxy|
row_layout(:vertical) {
center true
}
text 'Error Launching'
styled_text(:border, :h_scroll, :v_scroll) {
layout_data {
width body_root.bounds.width*0.75
height body_root.bounds.height*0.75
}
text message
editable false
caret nil
}
button {
text 'Close'
on_widget_selected do
dialog_proxy.close
end
}
}
end
end
MetaSampleApplication.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris.rb | samples/elaborate/tetris.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative 'tetris/model/game'
require_relative 'tetris/view/playfield'
require_relative 'tetris/view/score_lane'
require_relative 'tetris/view/high_score_dialog'
require_relative 'tetris/view/tetris_menu_bar'
# Tetris App View Custom Shell (represents `tetris` keyword)
class Tetris
include Glimmer::UI::CustomShell
BLOCK_SIZE = 25
FONT_NAME = 'Menlo'
FONT_TITLE_HEIGHT = 32
FONT_TITLE_STYLE = :bold
BEVEL_CONSTANT = 20
option :playfield_width, default: Model::Game::PLAYFIELD_WIDTH
option :playfield_height, default: Model::Game::PLAYFIELD_HEIGHT
attr_reader :game
before_body do
@mutex = Mutex.new
@game = Model::Game.new(playfield_width, playfield_height)
@game.configure_beeper do
display.beep
end
Display.app_name = 'Glimmer Tetris'
display {
on_swt_keydown do |key_event|
case key_event.keyCode
when swt(:arrow_down), 's'.bytes.first
if OS.mac?
game.down!
else
# rate limit downs in Windows/Linux as they go too fast when key is held
@queued_downs ||= 0
@queued_downs += 1
async_exec do
game.down! if @queued_downs < 3
@queued_downs -= 1
end
end
when swt(:arrow_up)
case game.up_arrow_action
when :instant_down
game.down!(instant: true)
when :rotate_right
game.rotate!(:right)
when :rotate_left
game.rotate!(:left)
end
when swt(:arrow_left), 'a'.bytes.first
game.left!
when swt(:arrow_right), 'd'.bytes.first
game.right!
when swt(:shift), swt(:alt)
if key_event.keyLocation == swt(:right) # right key
game.rotate!(:right)
elsif key_event.keyLocation == swt(:left) # left key
game.rotate!(:left)
end
end
end
# if running in app mode, set the Mac app about dialog (ignored in platforms)
on_about do
show_about_dialog
end
on_quit do
exit(0)
end
}
end
after_body do
observe(@game, :game_over) do |game_over|
if game_over
show_high_score_dialog
else
start_moving_tetrominos_down
end
end
observe(@game, :show_high_scores) do |show_high_scores|
if show_high_scores
show_high_score_dialog
else
@high_score_dialog.close unless @high_score_dialog.nil? || @high_score_dialog.disposed? || !@high_score_dialog.visible?
end
end
@game.start!
end
body {
shell(:no_resize) {
grid_layout {
num_columns 2
make_columns_equal_width false
margin_width 0
margin_height 0
horizontal_spacing 0
}
text 'Glimmer Tetris'
minimum_size 475, 500
image tetris_icon
tetris_menu_bar(game: game)
playfield(game_playfield: game.playfield, playfield_width: playfield_width, playfield_height: playfield_height, block_size: BLOCK_SIZE)
score_lane(game: game, block_size: BLOCK_SIZE) {
layout_data(:fill, :fill, true, true)
}
}
}
def tetris_icon
icon_block_size = 64
icon_bevel_size = icon_block_size.to_f / 25.to_f
icon_bevel_pixel_size = 0.16*icon_block_size.to_f
icon_size = 8
icon_pixel_size = icon_block_size * icon_size
image(icon_pixel_size, icon_pixel_size) {
icon_size.times do |row|
icon_size.times do |column|
colored = row >= 1 && column.between?(1, 6)
color = colored ? color(([:white] + Model::Tetromino::LETTER_COLORS.values).sample) : color(:white)
x = column * icon_block_size
y = row * icon_block_size
bevel(x: x, y: y, base_color: color, size: icon_block_size)
end
end
}
end
def start_moving_tetrominos_down
Thread.new do
@mutex.synchronize do
loop do
time = Time.now
sleep @game.delay
break if @game.game_over? || body_root.disposed?
# ensure entire game tetromino down movement happens as one GUI update event with sync_exec (to avoid flicker/stutter)
sync_exec { @game.down! unless @game.paused? }
end
end
end
end
def show_high_score_dialog
return if @high_score_dialog&.visible?
@high_score_dialog = high_score_dialog(parent_shell: body_root, game: @game) if @high_score_dialog.nil? || @high_score_dialog.disposed?
@high_score_dialog.show
end
def show_about_dialog
message_box {
text 'Glimmer Tetris'
message "Glimmer Tetris\n\nGlimmer DSL for SWT Sample\n\nCopyright (c) 2007-2025 Andy Maleh"
}.open
end
end
Tetris.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/weather.rb | samples/elaborate/weather.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require 'net/http'
require 'json'
require 'facets/string/titlecase'
class Weather
include Glimmer::UI::CustomShell
DEFAULT_FONT_HEIGHT = 30
DEFAULT_FOREGROUND = :white
DEFAULT_BACKGROUND = rgb(135, 176, 235)
attr_accessor :city, :temp, :temp_min, :temp_max, :feels_like, :humidity
before_body do
@weather_mutex = Mutex.new
self.city = 'Montreal, QC, CA'
fetch_weather!
end
after_body do
Thread.new do
loop do
sleep(10)
break if body_root.disposed?
fetch_weather!
end
end
end
body {
shell(:no_resize) {
grid_layout
text 'Glimmer Weather'
minimum_size 400, (OS.linux? ? 330 : 300)
background DEFAULT_BACKGROUND
text {
layout_data(:center, :center, true, true)
text <=> [self, :city]
on_key_pressed do |event|
if event.keyCode == swt(:cr) # carriage return
Thread.new do
fetch_weather!
end
end
end
}
tab_folder {
layout_data(:center, :center, true, true) {
width_hint OS.linux? ? 300 : 270
}
['℃', '℉'].each do |temp_unit|
tab_item {
grid_layout 2, false
text temp_unit
background DEFAULT_BACKGROUND
rectangle(0, 0, [:default, -2], [:default, -2], 15, 15) {
foreground DEFAULT_FOREGROUND
}
%w[temp temp_min temp_max feels_like].each do |field_name|
temp_field(field_name, temp_unit)
end
humidity_field
}
end
}
}
}
def temp_field(field_name, temp_unit)
name_label(field_name)
label {
layout_data(:fill, :center, true, false)
text <= [self, field_name, on_read: ->(t) { "#{kelvin_to_temp_unit(t, temp_unit).to_f.round}°" }]
font height: DEFAULT_FONT_HEIGHT
background DEFAULT_BACKGROUND
foreground DEFAULT_FOREGROUND
}
end
def humidity_field
name_label('humidity')
label {
layout_data(:fill, :center, true, false)
text <= [self, 'humidity', on_read: ->(h) { "#{h.to_f.round}%" }]
font height: DEFAULT_FONT_HEIGHT
background DEFAULT_BACKGROUND
foreground DEFAULT_FOREGROUND
}
end
def name_label(field_name)
label {
layout_data :fill, :center, false, false
text field_name.titlecase
font height: DEFAULT_FONT_HEIGHT
background DEFAULT_BACKGROUND
foreground DEFAULT_FOREGROUND
}
end
def fetch_weather!
@weather_mutex.synchronize do
self.weather_data = JSON.parse(Net::HTTP.get('api.openweathermap.org', "/data/2.5/weather?q=#{city}&appid=1d16d70a9aec3570b5cbd27e6b421330"))
end
rescue => e
Glimmer::Config.logger.error "Unable to fetch weather due to error: #{e.full_message}"
end
def weather_data=(data)
@weather_data = data
main_data = data['main']
# temps come back in Kelvin
self.temp = main_data['temp']
self.temp_min = main_data['temp_min']
self.temp_max = main_data['temp_max']
self.feels_like = main_data['feels_like']
self.humidity = main_data['humidity']
end
def kelvin_to_temp_unit(kelvin, temp_unit)
temp_unit == '℃' ? kelvin_to_celsius(kelvin) : kelvin_to_fahrenheit(kelvin)
end
def kelvin_to_celsius(kelvin)
return nil if kelvin.nil?
kelvin - 273.15
end
def celsius_to_fahrenheit(celsius)
return nil if celsius.nil?
(celsius * 9 / 5 ) + 32
end
def kelvin_to_fahrenheit(kelvin)
return nil if kelvin.nil?
celsius_to_fahrenheit(kelvin_to_celsius(kelvin))
end
end
Weather.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/metronome.rb | samples/elaborate/metronome.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
class Metronome
class Beat
attr_accessor :on
def off!
self.on = false
end
def on!
self.on = true
end
end
class Rhythm
attr_reader :beat_count
attr_accessor :beats, :bpm
def initialize(beat_count)
self.beat_count = beat_count
@bpm = 120
end
def beat_count=(value)
@beat_count = value
reset_beats!
end
def reset_beats!
@beats = beat_count.times.map {Beat.new}
@beats.first.on!
end
end
include Glimmer::UI::CustomShell
import 'javax.sound.sampled'
GEM_ROOT = File.expand_path(File.join('..', '..'), __dir__)
FILE_SOUND_METRONOME_UP = File.join(GEM_ROOT, 'sounds', 'metronome-up.wav')
FILE_SOUND_METRONOME_DOWN = File.join(GEM_ROOT, 'sounds', 'metronome-down.wav')
attr_accessor :rhythm
before_body do
@rhythm = Rhythm.new(4)
end
body {
shell(:no_resize) {
row_layout(:vertical) {
center true
}
text 'Glimmer Metronome'
label {
text 'Beat Count'
font height: 30, style: :bold
}
spinner {
minimum 1
maximum 64
selection <=> [self, 'rhythm.beat_count', after_write: ->(v) {restart_metronome}]
font height: 30
}
label {
text 'BPM'
font height: 30, style: :bold
}
spinner {
minimum 30
maximum 1000
selection <=> [self, 'rhythm.bpm']
font height: 30
}
@beat_container = beat_container
on_swt_show do
start_metronome
end
on_widget_disposed do
stop_metronome
end
}
}
def beat_container
composite {
grid_layout(@rhythm.beat_count, true)
@rhythm.beat_count.times { |n|
canvas {
layout_data {
width_hint 50
height_hint 50
}
rectangle(0, 0, :default, :default, 36, 36) {
background <= [self, "rhythm.beats[#{n}].on", on_read: ->(on) { on ? :red : :yellow}]
}
}
}
}
end
def start_metronome
@thread ||= Thread.new {
@rhythm.beat_count.times.cycle { |n|
sleep(60.0/@rhythm.bpm.to_f)
@rhythm.beats.each(&:off!)
@rhythm.beats[n].on!
sound_file = n == 0 ? FILE_SOUND_METRONOME_UP : FILE_SOUND_METRONOME_DOWN
play_sound(sound_file)
}
}
if @beat_container.nil?
body_root.content {
@beat_container = beat_container
}
body_root.layout(true, true)
body_root.pack(true)
end
end
def stop_metronome
@thread&.kill # safe since no stored data is involved
@thread = nil
@beat_container&.dispose
@beat_container = nil
end
def restart_metronome
stop_metronome
start_metronome
end
# Play sound with the Java Sound library
def play_sound(sound_file)
begin
file_or_stream = java.io.File.new(sound_file)
audio_stream = AudioSystem.get_audio_input_stream(file_or_stream)
clip = AudioSystem.clip
clip.open(audio_stream)
clip.start
rescue => e
puts e.full_message
end
end
end
Metronome.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/connect4.rb | samples/elaborate/connect4.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative 'connect4/model/grid'
class Connect4
include Glimmer::UI::CustomShell
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
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(Model::Grid::WIDTH, true)
text 'Glimmer Connect 4'
background COLOR_BACKGROUND
Model::Grid::HEIGHT.times do |row_index|
Model::Grid::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
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/login.rb | samples/elaborate/login.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
class LoginPresenter
attr_accessor :user_name
attr_accessor :password
attr_accessor :status
def initialize
@user_name = ""
@password = ""
@status = "Logged Out"
end
def status=(status)
@status = status
end
def valid?
!@user_name.to_s.strip.empty? && !@password.to_s.strip.empty?
end
def logged_in?
self.status == "Logged In"
end
def logged_out?
!self.logged_in?
end
def login!
return unless valid?
self.status = "Logged In"
end
def logout!
self.user_name = ""
self.password = ""
self.status = "Logged Out"
end
end
class Login
include Glimmer::UI::CustomShell
before_body do
@presenter = LoginPresenter.new
end
body {
shell {
text "Login"
composite {
grid_layout 2, false #two columns with differing widths
label { text "Username:" } # goes in column 1
@user_name_text = text { # goes in column 2
text <=> [@presenter, :user_name]
enabled <= [@presenter, :logged_out?, computed_by: :status]
on_key_pressed do |event|
@password_text.set_focus if event.keyCode == swt(:cr)
end
}
label { text "Password:" }
@password_text = text(:password, :border) {
text <=> [@presenter, :password]
enabled <= [@presenter, :logged_out?, computed_by: :status]
on_key_pressed do |event|
@presenter.login! if event.keyCode == swt(:cr)
end
}
label { text "Status:" }
label { text <= [@presenter, :status] }
button {
text "Login"
enabled <= [@presenter, :logged_out?, computed_by: :status]
on_widget_selected do
@presenter.login!
end
on_key_pressed do |event|
if event.keyCode == swt(:cr)
@presenter.login!
end
end
}
button {
text "Logout"
enabled <= [@presenter, :logged_in?, computed_by: :status]
on_widget_selected do
@presenter.logout!
end
on_key_pressed do |event|
if event.keyCode == swt(:cr)
@presenter.logout!
@user_name_text.set_focus
end
end
}
}
}
}
end
Login.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship.rb | samples/elaborate/battleship.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require 'facets/string/titlecase'
require 'facets/string/underscore'
require_relative 'battleship/model/game'
require_relative 'battleship/view/grid'
require_relative 'battleship/view/ship_collection'
require_relative 'battleship/view/action_panel'
class Battleship
include Glimmer::UI::CustomShell
COLOR_WATER = rgb(156, 211, 219)
COLOR_SHIP = :dark_gray
before_body do
@game = Model::Game.new
end
after_body do
observe(@game, :over) do |game_over_value|
if game_over_value
game_over_message = if game_over_value == :you
"Game over!\nYou Won!"
else
"Game over!\nYou Lost!"
end
message_box {
text 'Game Over!'
message game_over_message
}.open
end
end
end
body {
shell(:no_resize) {
grid_layout(2, false) {
horizontal_spacing 15
vertical_spacing 15
}
text 'Glimmer Battleship'
@enemy_grid = grid(game: @game, player: :enemy)
@enemy_ship_collection = ship_collection(game: @game, player: :enemy)
@player_grid = grid(game: @game, player: :you)
@player_ship_collection = ship_collection(game: @game, player: :you)
action_panel(game: @game)
}
}
end
Battleship.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto.rb | samples/elaborate/quarto.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require 'yaml'
require_relative 'quarto/model/game'
require_relative 'quarto/view/board'
require_relative 'quarto/view/available_pieces_area'
require_relative 'quarto/view/selected_piece_area'
require_relative 'quarto/view/message_box_panel'
class Quarto
include Glimmer::UI::CustomShell
BOARD_DIAMETER = 430
PIECES_AREA_WIDTH = 252
AVAILABLE_PIECES_AREA_HEIGHT = 295
SELECTED_PIECE_AREA_HEIGHT = 124
CELL_DIAMETER = 68
CELL_LINE_WIDTH = 5
CELL_MARGIN = 7
SHELL_MARGIN = 15
AREA_MARGIN = 10
ROW_COUNT = 4
COLUMN_COUNT = 4
COLOR_WOOD = rgb(239, 196, 156)
COLOR_AREA = rgb(206, 188, 170)
COLOR_LIGHT_WOOD = rgb(254, 187, 120)
COLOR_DARK_WOOD = rgb(204, 108, 58)
FILE_QUARTO_CONFIG = File.join(Dir.home, '.quarto')
before_body do
load_quarto_config
@game = Model::Game.new
observe(@game, :current_move) do |new_move|
perform_current_move
end
observe(@game, :over) do |game_over_status|
if game_over_status
game_over_message = "Game Over! "
game_over_message += @game.winner_player_number.nil? ? "Draw!" : "Player #{@game.winner_player_number} wins!"
body_root.content {
@open_message_box_panel&.close
@open_message_box_panel = message_box_panel(
message: game_over_message,
background_color: COLOR_LIGHT_WOOD,
text_font: {height: 16}
) {
on_closed do
restart_game
end
}
}
end
end
end
after_body do
perform_current_move
end
body {
shell(:shell_trim, (:double_buffered unless OS.mac?)) {
text 'Glimmer Quarto'
minimum_size BOARD_DIAMETER + AREA_MARGIN + PIECES_AREA_WIDTH + SHELL_MARGIN*2 + (OS.linux? ? 52 : (OS.windows? ? 16 : 0)), BOARD_DIAMETER + 24 + SHELL_MARGIN*2 + (OS.linux? ? 96 : (OS.windows? ? 32 : 0))
maximum_size BOARD_DIAMETER + AREA_MARGIN + PIECES_AREA_WIDTH + SHELL_MARGIN*2 + (OS.linux? ? 52 : (OS.windows? ? 16 : 0)), BOARD_DIAMETER + 24 + SHELL_MARGIN*2 + (OS.linux? ? 96 : (OS.windows? ? 32 : 0))
background COLOR_WOOD
quarto_menu_bar
@board = board(game: @game, location_x: SHELL_MARGIN, location_y: SHELL_MARGIN)
@available_pieces_area = available_pieces_area(game: @game, location_x: SHELL_MARGIN + BOARD_DIAMETER + AREA_MARGIN, location_y: SHELL_MARGIN)
@selected_piece_area = selected_piece_area(game: @game, location_x: SHELL_MARGIN + BOARD_DIAMETER + AREA_MARGIN, location_y: SHELL_MARGIN + AVAILABLE_PIECES_AREA_HEIGHT + AREA_MARGIN)
}
}
def quarto_menu_bar
menu_bar {
menu {
text 'Game'
menu_item {
text 'Restart'
on_widget_selected do
restart_game
end
}
menu_item {
text 'Exit'
on_widget_selected do
exit(0)
end
}
}
menu {
text 'Help'
menu_item(:check) {
text 'Help Pop-Ups Enabled'
selection <=> [self, :help_pop_ups_enabled]
}
}
}
end
def help_pop_ups_enabled
@quarto_config[:help_pop_ups_enabled]
end
alias help_pop_ups_enabled? help_pop_ups_enabled
def help_pop_ups_enabled=(new_value)
@quarto_config[:help_pop_ups_enabled] = new_value
save_quarto_config
end
def load_quarto_config
@quarto_config = YAML.load(File.read(FILE_QUARTO_CONFIG)) rescue {}
@quarto_config[:help_pop_ups_enabled] = true if @quarto_config[:help_pop_ups_enabled].nil?
@quarto_config
end
def save_quarto_config
File.write(FILE_QUARTO_CONFIG, YAML.dump(@quarto_config))
rescue => e
puts "Unable to save quarto config file to: #{@quarto_config}"
end
def perform_current_move
verbiage = nil
case @game.current_move
when :select_piece
@available_pieces_area.pieces.each {|piece| piece.drag_source = true}
verbiage = "Player #{@game.current_player_number} must drag a piece to the Selected Piece\narea for the other player to place on the board!"
when :place_piece
@available_pieces_area.pieces.each {|piece| piece.drag_source = false}
@selected_piece_area.selected_piece.drag_source = true
verbiage = "Player #{@game.current_player_number} must drag the selected piece to the board\nin order to place it!"
end
body_root.text = "Glimmer Quarto | Player #{@game.current_player_number} #{@game.current_move.to_s.split('_').map(&:capitalize).join(' ')}"
if help_pop_ups_enabled?
async_exec do
body_root.content {
@open_message_box_panel&.close
@open_message_box_panel = message_box_panel(
message: verbiage,
background_color: COLOR_LIGHT_WOOD,
text_font: {height: 16}
)
}
body_root.redraw
end
end
end
def restart_game
@available_pieces_area.reset_pieces
@selected_piece_area.reset_selected_piece
@board.reset_cells
@game.restart
end
end
Quarto.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire.rb | samples/elaborate/klondike_solitaire.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative 'klondike_solitaire/model/game'
require_relative 'klondike_solitaire/view/action_panel'
require_relative 'klondike_solitaire/view/tableau'
require_relative 'klondike_solitaire/view/klondike_solitaire_menu_bar'
class KlondikeSolitaire
include Glimmer::UI::CustomShell
PLAYING_CARD_WIDTH = 50
PLAYING_CARD_HEIGHT = 76
PLAYING_CARD_SPACING = 5
PLAYING_CARD_FONT_HEIGHT = 16
MARGIN = 15
TABLEAU_WIDTH = 2*MARGIN + 7*(PLAYING_CARD_WIDTH + PLAYING_CARD_SPACING)
TABLEAU_HEIGHT = 420
before_body do
@game = Model::Game.new
end
body {
shell {
grid_layout {
margin_width 0
margin_height 0
margin_top 15
}
minimum_size TABLEAU_WIDTH, TABLEAU_HEIGHT
text "Glimmer Klondike Solitaire"
background :dark_green
klondike_solitaire_menu_bar(game: @game)
action_panel(game: @game) {
layout_data(:fill, :center, true, false)
}
tableau(game: @game) {
layout_data(:fill, :fill, true, true) {
width_hint TABLEAU_WIDTH
height_hint TABLEAU_HEIGHT
}
}
}
}
end
KlondikeSolitaire.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/game_of_life.rb | samples/elaborate/game_of_life.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative 'game_of_life/model/grid'
class GameOfLife
include Glimmer::UI::CustomShell
WIDTH = 20
HEIGHT = 20
CELL_WIDTH = 25
CELL_HEIGHT = 25
before_body do
@grid = GameOfLife::Model::Grid.new(WIDTH, HEIGHT)
end
body {
shell {
row_layout :vertical
text "Conway's Game of Life (Glimmer Edition)"
canvas {
layout_data {
width WIDTH*CELL_WIDTH
height HEIGHT*CELL_HEIGHT
}
(0...HEIGHT).each do |row_index|
(0...WIDTH).each do |column_index|
rectangle(column_index*CELL_WIDTH, row_index*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT) {
background <= [@grid.cell_rows[row_index][column_index], :alive, on_read: ->(a) {a ? :black : :white}]
on_mouse_down do
@grid.cell_rows[row_index][column_index].toggle_aliveness!
end
on_drag_detected do
@drag_detected = true
end
on_mouse_move do
@grid.cell_rows[row_index][column_index].live! if @drag_detected
end
on_mouse_up do
@drag_detected = false
end
}
end
end
}
composite {
row_layout(:horizontal) {
margin_width 0
}
button {
text 'Step'
enabled <= [@grid, :playing, on_read: :! ]
on_widget_selected do
@grid.step!
end
}
button {
text 'Clear'
enabled <= [@grid, :playing, on_read: :! ]
on_widget_selected do
@grid.clear!
end
}
button {
text <= [@grid, :playing, on_read: ->(p) { p ? 'Stop' : 'Play' }]
on_widget_selected do
@grid.toggle_playback!
end
}
label {
text 'Slower'
}
scale {
minimum 1
maximum 100
selection <=> [@grid, :speed]
}
label {
text 'Faster'
}
}
}
}
end
GameOfLife.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator.rb | samples/elaborate/calculator.rb | require 'glimmer-dsl-swt'
require 'bigdecimal'
require_relative 'calculator/model/presenter'
# This sample demonstrates use of MVP (Model-View-Presenter) Architectural Pattern
# to data-bind View widgets to object-oriented Models taking advantage of design patterns
# like Command Design Pattern.
class Calculator
include Glimmer::UI::CustomShell
BUTTON_FONT = {height: 14}
BUTTON_FONT_OPERATION = {height: 18}
BUTTON_FONT_BIG = {height: 28}
attr_reader :presenter
before_body do
@presenter = Model::Presenter.new
Display.setAppName('Glimmer Calculator')
display {
on_swt_keydown do |key_event|
char = key_event.character.chr rescue nil
@presenter.press(char)
end
on_about do
display_about_dialog
end
}
end
body {
shell {
grid_layout 4, true
minimum_size (OS.mac? ? 320 : (OS.windows? ? 390 : 520)), 240
text "Glimmer Calculator"
on_shell_closed do
@presenter.purge_command_history
end
# Setting styled_text to multi in order for alignment options to activate
styled_text(:multi, :wrap, :border) {
text <= [@presenter, :result]
alignment swt(:right)
right_margin 5
font height: 40
layout_data(:fill, :fill, true, true) {
horizontal_span 4
}
editable false
caret nil
}
command_button('AC')
operation_button('÷')
operation_button('×')
operation_button('−')
(7..9).each do |number|
number_button(number)
end
operation_button('+', font: BUTTON_FONT_BIG, vertical_span: 2)
(4..6).each do |number|
number_button(number)
end
(1..3).each do |number|
number_button(number)
end
command_button('=', font: BUTTON_FONT_BIG, vertical_span: 2)
number_button(0, horizontal_span: 2)
operation_button('.')
}
}
def number_button(number, options = {})
command_button(number, options)
end
def operation_button(operation, options = {})
command_button(operation, options.merge(font: BUTTON_FONT_OPERATION))
end
def command_button(command, options = {})
command = command.to_s
options[:font] ||= BUTTON_FONT
options[:horizontal_span] ||= 1
options[:vertical_span] ||= 1
button { |proxy|
text command
font options[:font]
layout_data(:fill, :fill, true, true) {
horizontal_span options[:horizontal_span]
vertical_span options[:vertical_span]
}
on_widget_selected do
@presenter.press(command)
end
}
end
def display_about_dialog
message_box(body_root) {
text 'About'
message "Glimmer - Calculator\n\nCopyright (c) 2007-2025 Andy Maleh"
}.open
end
end
Calculator.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/timer.rb | samples/elaborate/timer.rb | require 'glimmer-dsl-swt'
require 'os'
class Timer
include Glimmer::UI::CustomShell
import 'javax.sound.sampled'
FILE_SOUND_ALARM = File.expand_path(File.join('timer', 'sounds', 'alarm1.wav'), __dir__)
COMMAND_KEY = OS.mac? ? :command : :ctrl
## Add options like the following to configure CustomShell by outside consumers
#
# options :title, :background_color
# option :width, default: 320
# option :height, default: 240
attr_accessor :countdown, :min, :sec
## Use before_body block to pre-initialize variables to use in body
#
#
before_body do
Display.setAppName('Glimmer Timer')
@display = display {
on_about do
display_about_dialog
end
on_preferences do
display_about_dialog
end
}
@min = 0
@sec = 0
end
## Use after_body block to setup observers for widgets in body
#
after_body do
Thread.new do
loop do
sleep(1)
if @countdown
sync_exec do
@countdown_time = Time.new(1, 1, 1, 0, min, sec)
@countdown_time -= 1
self.min = @countdown_time.min
self.sec = @countdown_time.sec
if @countdown_time.min <= 0 && @countdown_time.sec <= 0
stop_countdown
play_countdown_done_sound
end
end
end
end
end
end
## Add widget content inside custom shell body
## Top-most widget must be a shell or another custom shell
#
body {
shell {
grid_layout # 1 column
# Replace example content below with custom shell content
minimum_size (OS.windows? ? 214 : 200), 114
text "Glimmer Timer"
timer_menu_bar
countdown_group
}
}
def timer_menu_bar
menu_bar {
menu {
text '&Action'
menu_item {
text '&Start'
accelerator COMMAND_KEY, 's'
enabled <= [self, :countdown, on_read: :!]
on_widget_selected do
start_countdown
end
}
menu_item {
text 'St&op'
enabled <= [self, :countdown]
accelerator COMMAND_KEY, 'o'
on_widget_selected do
stop_countdown
end
}
unless OS.mac?
menu_item(:separator)
menu_item {
text 'E&xit'
accelerator :alt, :f4
on_widget_selected do
exit(0)
end
}
end
}
menu {
text '&Help'
menu_item {
text '&About'
accelerator COMMAND_KEY, :shift, 'a'
on_widget_selected do
display_about_dialog
end
}
}
}
end
def countdown_group
group {
# has grid layout with 1 column by default
text 'Countdown'
font height: 20
countdown_group_field_composite
countdown_group_button_composite
}
end
def countdown_group_field_composite
composite {
row_layout {
margin_width 0
margin_height 0
}
@min_spinner = spinner {
text_limit 2
digits 0
maximum 59
selection <=> [self, :min]
enabled <= [self, :countdown, on_read: :!]
on_widget_default_selected do
start_countdown
end
}
label {
text ':'
font(height: 18) if OS.mac?
}
@sec_spinner = spinner {
text_limit 2
digits 0
maximum 59
selection <=> [self, :sec]
enabled <= [self, :countdown, on_read: :!]
on_widget_default_selected do
start_countdown
end
}
}
end
def countdown_group_button_composite
composite {
row_layout {
margin_width 0
margin_height 0
}
@start_button = button {
text '&Start'
enabled <= [self, :countdown, on_read: :!]
on_widget_selected do
start_countdown
end
on_key_pressed do |event|
start_countdown if event.keyCode == swt(:cr)
end
}
@stop_button = button {
text 'St&op'
enabled <= [self, :countdown]
on_widget_selected do
stop_countdown
end
on_key_pressed do |event|
stop_countdown if event.keyCode == swt(:cr)
end
}
}
end
def display_about_dialog
message_box(body_root) {
text 'About'
message "Glimmer Timer\n\nCopyright (c) 2007-2025 Andy Maleh"
}.open
end
def start_countdown
self.countdown = true
@stop_button.swt_widget.set_focus
end
def stop_countdown
self.countdown = false
@min_spinner.swt_widget.set_focus
end
def play_countdown_done_sound
begin
file_or_stream = java.io.File.new(FILE_SOUND_ALARM)
audio_stream = AudioSystem.get_audio_input_stream(file_or_stream)
clip = AudioSystem.clip
clip.open(audio_stream)
clip.start
rescue => e
Glimmer::Config.logger.error e.full_message
end
end
end
Timer.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake.rb | samples/elaborate/snake.rb | require 'glimmer-dsl-swt'
require_relative 'snake/presenter/grid'
class Snake
include Glimmer::UI::CustomShell
CELL_SIZE = 15
SNAKE_MOVE_DELAY = 100 # millis
before_body do
@game = Model::Game.new
@grid = Presenter::Grid.new(@game)
@game.start
@keypress_queue = []
display {
on_swt_keydown do |key_event|
if key_event.keyCode == 32
@game.toggle_pause
else
@keypress_queue << key_event.keyCode
end
end
}
end
after_body do
register_observers
end
body {
shell(:no_resize) {
grid_layout(@game.width, true) {
margin_width 0
margin_height 0
horizontal_spacing 0
vertical_spacing 0
}
# data-bind window title to game score, converting it to a title string on read from the model
text <= [@game, :score, on_read: -> (score) {"Snake (Score: #{@game.score})"}]
minimum_size @game.width * CELL_SIZE, @game.height * CELL_SIZE
@game.height.times do |row|
@game.width.times do |column|
canvas {
layout_data {
width_hint CELL_SIZE
height_hint CELL_SIZE
}
rectangle(0, 0, CELL_SIZE, CELL_SIZE) {
background <= [@grid.cells[row][column], :color] # data-bind square fill to grid cell color
}
}
end
end
}
}
def register_observers
observe(@game, :over) do |game_over|
async_exec do
if game_over
message_box {
text 'Game Over!'
message "Score: #{@game.score} | High Score: #{@game.high_score}"
}.open
@game.start
end
end
end
timer_exec(SNAKE_MOVE_DELAY, &method(:move_snake))
end
def move_snake
unless @game.paused? || @game.over?
process_queued_keypress
@game.snake.move
end
timer_exec(SNAKE_MOVE_DELAY, &method(:move_snake))
end
def process_queued_keypress
# key press queue ensures one turn per snake move to avoid a double-turn resulting in instant death (due to snake illogically going back against itself)
key = @keypress_queue.shift
if [@game.snake.head.orientation, key] == [:north, swt(:arrow_right)] ||
[@game.snake.head.orientation, key] == [:east, swt(:arrow_down)] ||
[@game.snake.head.orientation, key] == [:south, swt(:arrow_left)] ||
[@game.snake.head.orientation, key] == [:west, swt(:arrow_up)]
@game.snake.turn_right
elsif [@game.snake.head.orientation, key] == [:north, swt(:arrow_left)] ||
[@game.snake.head.orientation, key] == [:west, swt(:arrow_down)] ||
[@game.snake.head.orientation, key] == [:south, swt(:arrow_right)] ||
[@game.snake.head.orientation, key] == [:east, swt(:arrow_up)]
@game.snake.turn_left
end
end
end
Snake.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/parking.rb | samples/elaborate/parking.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative 'parking/model/parking_presenter'
class Parking
include Glimmer::UI::CustomShell
CANVAS_LENGTH = 600
FLOOR_COUNT = 4
before_body do
@parking_presenter = Model::ParkingPresenter.new(FLOOR_COUNT)
end
body {
shell(:no_resize) {
row_layout(:vertical) {
center true
}
text 'Parking'
label {
text 'Select an available spot to park'
font height: 30
}
label {
text 'Floor:'
font height: 20
}
spinner {
minimum 1
maximum FLOOR_COUNT
font height: 20
selection <=> [@parking_presenter, :selected_floor]
on_widget_selected do
@canvas.dispose_shapes
@canvas.content {
parking_floor
}
end
}
@canvas = canvas {
layout_data {
width CANVAS_LENGTH
height CANVAS_LENGTH
}
background :dark_gray
parking_floor
}
}
}
def parking_floor
parking_quad(67.5, 0, 125, 0)
parking_quad(67.5, 0, 125, 90)
parking_quad(67.5, 0, 125, 180)
parking_quad(67.5, 0, 125, 270)
end
def parking_quad(location_x, location_y, length, angle)
distance = (1.0/3)*length
parking_spot(location_x, location_y, length, angle)
parking_spot(location_x + distance, location_y, length, angle)
parking_spot(location_x + 2*distance, location_y, length, angle)
parking_spot(location_x + 3*distance, location_y, length, angle)
end
def parking_spot(location_x, location_y, length, angle)
parking_spot_letter = next_parking_spot_letter
height = length
width = (2.0/3)*length
shape(location_x, location_y) {
line_width (1.0/15)*length
foreground :white
rectangle(location_x, location_y, width, height) {
background <= [parking_spot_for(parking_spot_letter), :booked,
on_read: ->(value) {value ? :red : :dark_gray}
]
text {
x :default
y :default
string parking_spot_letter
font height: 20
}
on_mouse_up do
begin
selected_parking_floor.book!(parking_spot_letter)
message_box {
text 'Parking Booked!'
message "Floor #{@parking_presenter.selected_floor} Parking Spot #{parking_spot_letter} Is Booked!"
}.open
rescue => e
# No Op if already booked
end
end
}
line(location_x, location_y, location_x, location_y + height)
line(location_x, location_y, location_x + width, location_y)
line(location_x + width, location_y, location_x + width, location_y + height)
# Rotate around the canvas center point
transform {
translation CANVAS_LENGTH/2.0, CANVAS_LENGTH/2.0
rotation angle
translation -CANVAS_LENGTH/2.0, -CANVAS_LENGTH/2.0
}
}
end
def parking_spot_for(parking_spot_letter)
selected_parking_floor.parking_spots[parking_spot_letter]
end
def selected_parking_floor
@parking_presenter.floors[@parking_presenter.selected_floor - 1]
end
private
def next_parking_spot_letter
@parking_spot_letters = Model::ParkingSpot::LETTERS.clone if @parking_spot_letters.nil? || @parking_spot_letters.empty?
@parking_spot_letters.shift
end
end
Parking.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tic_tac_toe.rb | samples/elaborate/tic_tac_toe.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer-dsl-swt'
require_relative "tic_tac_toe/board"
class TicTacToe
include Glimmer::UI::CustomShell
before_body do
@tic_tac_toe_board = Board.new
end
after_body do
observe(@tic_tac_toe_board, :game_status) do |game_status|
display_win_message if game_status == Board::WIN
display_draw_message if game_status == Board::DRAW
end
end
body {
shell {
text "Tic-Tac-Toe"
minimum_size 176, 200
composite {
grid_layout 3, true
(1..3).each { |row|
(1..3).each { |column|
button {
layout_data :fill, :fill, true, true
text <= [@tic_tac_toe_board[row, column], :sign]
enabled <= [@tic_tac_toe_board[row, column], :empty]
font style: :bold, height: (OS.windows? ? 18 : 20)
on_widget_selected do
@tic_tac_toe_board.mark(row, column)
end
}
}
}
}
}
}
def display_win_message
display_game_over_message("Player #{@tic_tac_toe_board.winning_sign} has won!")
end
def display_draw_message
display_game_over_message("Draw!")
end
def display_game_over_message(message_text)
message_box {
text 'Game Over'
message message_text
}.open
@tic_tac_toe_board.reset!
end
end
TicTacToe.launch
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/model/ship_collection.rb | samples/elaborate/battleship/model/ship_collection.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'ship'
class Battleship
module Model
class ShipCollection
BATTLESHIPS = {
aircraft_carrier: 5,
battleship: 4,
submarine: 3,
cruiser: 3,
destroyer: 2
}
attr_reader :game, :player, :ships
attr_accessor :placed_count
def initialize(game, player)
@game = game
@player = player
@ships = BATTLESHIPS.reduce({}) do |hash, pair|
name, width = pair
ship = Ship.new(self, name, width)
Glimmer::DataBinding::Observer.proc do |cell_value|
self.placed_count = ships.values.map(&:top_left_cell).compact.size
end.observe(ship, :top_left_cell)
hash.merge(name => ship)
end
end
def reset!
ships.values.each(&:reset!)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/model/cell.rb | samples/elaborate/battleship/model/cell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Battleship
module Model
class Cell
attr_reader :grid, :row_index, :column_index
attr_accessor :hit, :ship, :ship_index
alias hit? hit
def initialize(grid, row_index, column_index)
@grid = grid
@row_index = row_index
@column_index = column_index
end
def reset!
self.hit = nil
self.ship = nil
self.ship_index = nil
end
# Places ship horizontally so that its top left cell is self,
# automatically figuring out the rest of the cells
def place_ship!(ship)
begin
old_ship_top_left_cell = ship.top_left_cell
old_ship_orientation = ship.orientation
ship.top_left_cell = self
if old_ship_top_left_cell
ship.cells(old_ship_orientation).each(&:reset!)
ship.length.times do |index|
if ship.orientation == :horizontal
old_cell = grid.cell_rows[old_ship_top_left_cell.row_index][old_ship_top_left_cell.column_index + index]
else
old_cell = grid.cell_rows[old_ship_top_left_cell.row_index + index][old_ship_top_left_cell.column_index]
end
old_cell.reset!
end
end
ship.length.times do |index|
if ship.orientation == :horizontal
cell = grid.cell_rows[row_index][column_index + index]
else
cell = grid.cell_rows[row_index + index][column_index]
end
cell.ship = ship
cell.ship_index = index
end
rescue => e
Glimmer::Config.logger.debug(e.full_message)
end
end
def hit=(value)
@hit = value
ship&.sunk = true if ship&.all_cells_hit?
grid.game.over = grid.game.opposite_player(grid.player) if grid.game.started? && grid.game.ship_collections[grid.player].ships.values.map(&:sunk).all?
end
def to_s
"#{(Grid::ROW_ALPHABETS[row_index])}#{(column_index + 1)}"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/model/game.rb | samples/elaborate/battleship/model/game.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'grid'
require_relative 'ship'
class Battleship
module Model
class Game
BATTLESHIPS = {
aircraft_carrier: 5,
battleship: 4,
submarine: 3,
cruiser: 3,
destroyer: 2
}
PLAYERS = [:enemy, :you]
attr_reader :grids, :ship_collections
attr_accessor :started, :current_player, :over
alias started? started
alias over? over
def initialize
@grids = PLAYERS.reduce({}) { |hash, player| hash.merge(player => Grid.new(self, player)) }
@ship_collections = PLAYERS.reduce({}) { |hash, player| hash.merge(player => ShipCollection.new(self, player)) }
@started = false
@current_player = :enemy
@enemy_moves = []
end
def battle!
self.started = true
place_enemy_ships!
enemy_attack!
end
def reset!
self.started = false
self.over = false
self.current_player = :enemy
@grids.values.each(&:reset!)
@ship_collections.values.each(&:reset!)
@enemy_moves = []
end
def attack!(row_index, column_index)
return unless started?
cell = opposite_grid.cell_rows[row_index][column_index]
return unless cell.hit.nil?
cell.hit = !!cell.ship
switch_player!
enemy_attack! if current_player == :enemy
end
# Enemy attack artificial intelligence
def enemy_attack!
begin
cell = nil
if @enemy_moves.any? && @enemy_moves.last.hit? && !@enemy_moves.last.ship.sunk?
if @enemy_moves[-2].nil? || !@enemy_moves[-2].hit?
orientation = Ship::ORIENTATIONS[(rand * 2).to_i]
else
orientation = @enemy_moves.last.row_index == @enemy_moves[-2].row_index ? :horizontal : :vertical
end
offset = 1 * ((rand * 2).to_i == 1 ? 1 : -1)
if orientation == :horizontal
offset *= -1 if [-1, Grid::WIDTH].include?(@enemy_moves.last.column_index + offset)
cell = opposite_grid.cell_rows[@enemy_moves.last.row_index][@enemy_moves.last.column_index + offset]
else
offset *= -1 if [-1, Grid::HEIGHT].include?(@enemy_moves.last.row_index + offset)
cell = opposite_grid.cell_rows[@enemy_moves.last.row_index + offset][@enemy_moves.last.column_index]
end
cell = nil if cell.hit?
end
if cell.nil?
random_row_index = (rand * Grid::HEIGHT).to_i
random_column_index = (rand * Grid::WIDTH).to_i
cell = opposite_grid.cell_rows[random_row_index][random_column_index]
end
end until cell.hit.nil?
attack!(cell.row_index, cell.column_index)
@enemy_moves << cell
end
def opposite_grid
grids[opposite_player]
end
def opposite_player(player = nil)
player ||= current_player
PLAYERS[(PLAYERS.index(player) + 1) % PLAYERS.size]
end
def switch_player!
self.current_player = opposite_player
end
def over=(value)
@over = value
self.started = false
end
private
def place_enemy_ships!
ship_collection = @ship_collections[:enemy]
ship_collection.ships.values.each do |ship|
until ship.top_left_cell
random_row_index = (rand * Grid::HEIGHT).to_i
random_column_index = (rand * Grid::WIDTH).to_i
enemy_grid = @grids[:enemy]
top_left_cell = enemy_grid.cell_rows[random_row_index][random_column_index]
top_left_cell.place_ship!(ship)
begin
ship.toggle_orientation! if (rand * 2).to_i == 1
rescue => e
Glimmer::Config.logger.debug(e.full_message)
end
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/model/grid.rb | samples/elaborate/battleship/model/grid.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class Battleship
module Model
class Grid
HEIGHT = 10
WIDTH = 10
ROW_ALPHABETS = %w[A B C D E F G H I J]
attr_reader :game, :player, :cell_rows
def initialize(game, player)
@game = game
@player = player
build
end
def reset!
@cell_rows.flatten.each(&:reset!)
end
private
def build
@cell_rows = HEIGHT.times.map do |row_index|
WIDTH.times.map do |column_index|
Cell.new(self, row_index, column_index)
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/model/ship.rb | samples/elaborate/battleship/model/ship.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class Battleship
module Model
class Ship
ORIENTATIONS = [:horizontal, :vertical]
attr_reader :ship_collection, :name, :length
attr_accessor :orientation, :top_left_cell, :sunk
alias sunk? sunk
def initialize(ship_collection, name, length)
@ship_collection = ship_collection
@name = name
@length = length
@orientation = :horizontal
end
def to_s
"#{name.titlecase} (#{length} cells)"
end
def top_left_cell=(a_cell)
if a_cell
raise "Top left cell #{a_cell} already occupied by ship #{a_cell.ship.name}" if a_cell.ship && a_cell.ship != self
raise "Top left cell #{a_cell} cannot fit ship #{name}" if a_cell.column_index + length > Grid::WIDTH
grid = ship_collection.game.grids[ship_collection.player]
1.upto(length - 1).each do |index|
if orientation == :horizontal
other_cell = grid.cell_rows[a_cell.row_index][a_cell.column_index + index]
else
other_cell = grid.cell_rows[a_cell.row_index + index][a_cell.column_index]
end
raise "Cell #{other_cell} already occupied by ship #{other_cell.ship.name}" if other_cell.ship && other_cell.ship != self
end
end
@top_left_cell = a_cell
end
def orientation=(value)
if top_left_cell
if value == :horizontal
if top_left_cell.column_index + length > Grid::WIDTH
raise "Top left cell #{top_left_cell} cannot fit ship #{name}"
end
else
if top_left_cell.row_index + length > Grid::HEIGHT
raise "Top left cell #{top_left_cell} cannot fit ship #{name}"
end
end
if cells(value)[1..-1].map(&:ship).reject {|s| s == self}.any?
raise 'Orientation #{value} cells occupied by another ship'
end
if value != @orientation
cells.each(&:reset!)
@orientation = value
cells.each_with_index do |cell, index|
cell.ship = self
cell.ship_index = index
end
end
end
end
def cells(for_orientation = nil)
for_orientation ||= orientation
if top_left_cell
length.times.map do |index|
if for_orientation == :horizontal
top_left_cell.grid.cell_rows[top_left_cell.row_index][top_left_cell.column_index + index]
else
top_left_cell.grid.cell_rows[top_left_cell.row_index + index][top_left_cell.column_index]
end
end
end
end
def all_cells_hit?
cells&.map(&:hit)&.all? {|h| h == true}
end
def reset!
self.sunk = nil
self.top_left_cell = nil
self.orientation = :horizontal
end
def toggle_orientation!
self.orientation = ORIENTATIONS[(ORIENTATIONS.index(orientation) + 1) % ORIENTATIONS.length]
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/view/ship_collection.rb | samples/elaborate/battleship/view/ship_collection.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative '../model/game'
require_relative '../model/ship_collection'
require_relative 'ship'
class Battleship
module View
class ShipCollection
include Glimmer::UI::CustomWidget
options :game, :player
body {
composite {
row_layout(:vertical) {
fill true
margin_width 0
margin_height 0
}
Model::ShipCollection::BATTLESHIPS.each do |ship_name, ship_length|
ship(game: game, player: player, ship_name: ship_name, ship_length: ship_length)
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/view/cell.rb | samples/elaborate/battleship/view/cell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Battleship
module View
class Cell
include Glimmer::UI::CustomWidget
class << self
attr_accessor :dragging
alias dragging? dragging
end
COLOR_WATER = rgb(156, 211, 219)
COLOR_SHIP = :gray
COLOR_PLACED = :white
COLOR_EMPTY = :black
COLOR_NO_HIT = :white
COLOR_HIT = :red
options :game, :player, :row_index, :column_index, :ship
option :type, default: :grid # other type is :ship
body {
canvas {
if type == :grid
if player == :you
background <= [model, :ship, on_read: ->(s) {s ? COLOR_SHIP : COLOR_WATER}]
else
background COLOR_WATER
end
else
background <= [ship, :sunk, on_read: ->(s) {s ? COLOR_HIT : COLOR_PLACED}]
background <= [ship, :top_left_cell, on_read: ->(c) {c ? COLOR_PLACED : COLOR_SHIP}]
end
rectangle(0, 0, [:max, -1], [:max, -1])
oval(:default, :default, 10, 10) {
if model.nil?
foreground COLOR_EMPTY
else
foreground <= [model, :hit, on_read: ->(h) {h == nil ? COLOR_EMPTY : (h ? COLOR_HIT : COLOR_NO_HIT)}]
end
}
oval(:default, :default, 5, 5) {
if model.nil?
background COLOR_EMPTY
else
background <= [model, :hit, on_read: ->(h) {h == nil ? COLOR_EMPTY : (h ? COLOR_HIT : COLOR_NO_HIT)}]
end
}
on_mouse_move do |event|
if game.started?
if type == :grid
if player == :enemy
body_root.cursor = :cross
else
body_root.cursor = :arrow
end
else
body_root.cursor = :arrow
end
end
end
if player == :enemy
on_mouse_up do
game.attack!(row_index, column_index)
end
end
if player == :you
on_drag_detected do |event|
unless game.started? || game.over?
Cell.dragging = true
body_root.cursor = :hand if type == :grid
end
end
on_drag_set_data do |event|
the_ship = ship || model&.ship
if the_ship && !game.started? && !game.over? && !(type == :ship && the_ship.top_left_cell)
event.data = the_ship.name.to_s
else
event.doit = false
Cell.dragging = false
end
end
on_mouse_up do
unless game.started? || game.over?
Cell.dragging = false
change_cursor
end
end
if type == :grid
on_mouse_move do |event|
unless game.started? || game.over?
change_cursor
end
end
on_mouse_hover do |event|
unless game.started? || game.over?
change_cursor
end
end
on_mouse_up do |event|
unless game.started? || game.over?
begin
model.ship&.toggle_orientation!
rescue => e
Glimmer::Config.logger.debug e.full_message
end
change_cursor
end
end
on_drop do |event|
unless game.started? || game.over?
ship_name = event.data
place_ship(ship_name.to_s.to_sym) if ship_name
Cell.dragging = false
change_cursor
end
end
end
end
}
}
def model
game.grids[player].cell_rows[row_index][column_index] if type == :grid
end
def place_ship(ship_name)
ship = game.ship_collections[player].ships[ship_name]
model.place_ship!(ship)
end
def change_cursor
if type == :grid && model.ship && !Cell.dragging?
body_root.cursor = model.ship.orientation == :horizontal ? :sizens : :sizewe
elsif !Cell.dragging?
body_root.cursor = :arrow
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/view/grid.rb | samples/elaborate/battleship/view/grid.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative '../model/grid'
require_relative 'cell'
class Battleship
module View
class Grid
include Glimmer::UI::CustomWidget
options :game, :player
body {
composite {
grid_layout(Model::Grid::WIDTH + 1, true) {
margin_width 0
margin_height 0
horizontal_spacing 0
vertical_spacing 0
}
label(:center) {
layout_data(:fill, :center, true, false) {
horizontal_span (Model::Grid::WIDTH + 1)
}
text player.to_s.capitalize
font height: OS.windows? ? 18 : 20, style: :bold
}
label # filler
Model::Grid::WIDTH.times do |column_index|
label {
text (column_index + 1).to_s
font height: OS.windows? ? 14 : 16
}
end
Model::Grid::HEIGHT.times do |row_index|
label {
text Model::Grid::ROW_ALPHABETS[row_index]
font height: OS.windows? ? 14 : 16
}
Model::Grid::WIDTH.times do |column_index|
cell(game: game, player: player, row_index: row_index, column_index: column_index) {
layout_data {
width_hint 25
height_hint 25
}
}
end
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/view/ship.rb | samples/elaborate/battleship/view/ship.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class Battleship
module View
class Ship
include Glimmer::UI::CustomWidget
options :game, :player, :ship_name, :ship_length
body {
composite {
row_layout(:vertical) {
fill true
margin_width 0
margin_height 0
}
label {
text ship_name.to_s.titlecase
font height: OS.windows? ? 14 : 16
}
composite {
grid_layout(ship_length, true) {
margin_width 0
margin_height 0
horizontal_spacing 0
vertical_spacing 0
}
ship_length.times do |column_index|
cell(game: game, player: player, type: :ship, column_index: column_index, ship: game.ship_collections[player].ships[ship_name]) {
layout_data {
width_hint 25
height_hint 25
}
}
end
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/battleship/view/action_panel.rb | samples/elaborate/battleship/view/action_panel.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Battleship
module View
class ActionPanel
include Glimmer::UI::CustomWidget
options :game
body {
composite {
row_layout(:horizontal) {
margin_width 0
margin_height 0
}
layout_data(:center, :center, true, false)
@battle_button = button {
text 'Battle!'
enabled <= [game.ship_collections[:you], :placed_count, on_read: ->(c) {c == 5}]
on_widget_selected do
game.battle!
@battle_button.enabled = false
end
}
button {
text 'Restart'
on_widget_selected do
game.reset!
end
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/game.rb | samples/elaborate/klondike_solitaire/model/game.rb | require_relative 'playing_card'
require_relative 'dealt_pile'
require_relative 'dealing_pile'
require_relative 'column_pile'
require_relative 'foundation_pile'
class KlondikeSolitaire
module Model
class Game
COLUMN_PILE_COUNT = 7
attr_reader :deck, :dealing_pile, :dealt_pile, :column_piles, :foundation_piles
def initialize
@deck = new_deck
@dealt_pile = DealtPile.new(self)
@dealing_pile = DealingPile.new(self)
@column_piles = COLUMN_PILE_COUNT.times.map {|n| ColumnPile.new(self, n + 1)}
@foundation_piles = PlayingCard::SUITS.map {|suit| FoundationPile.new(self, suit)}
end
def restart!
@deck = new_deck
@dealt_pile.reset!
@dealing_pile.reset!
@column_piles.each(&:reset!)
@foundation_piles.each(&:reset!)
end
private
def new_deck
PlayingCard.deck.shuffle
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/playing_card.rb | samples/elaborate/klondike_solitaire/model/playing_card.rb | class KlondikeSolitaire
module Model
class PlayingCard
SUITS = [:spades, :hearts, :clubs, :diamonds]
BLACK_SUITS = [:spades, :clubs]
RED_SUITS = [:hearts, :diamonds]
RANK_COUNT = 13
class << self
def deck
suit_decks.flatten
end
def suit_decks
SUITS.map do |suit|
suit_deck(suit)
end
end
def suit_deck(suit)
1.upto(RANK_COUNT).map do |rank|
new(rank, suit)
end
end
def rank_text(rank)
case rank
when 1
'A'
when 11
'J'
when 12
'Q'
when 13
'K'
else
rank
end
end
def suit_text(suit)
case suit
when :spades
"♠"
when :hearts
"♥"
when :clubs
"♣"
when :diamonds
"♦"
end
end
end
attr_reader :rank, :suit
attr_accessor :hidden
alias hidden? hidden
def initialize(rank, suit, hidden = false)
@rank = rank
@suit = suit
@hidden = hidden
end
def color
if BLACK_SUITS.include?(suit)
:black
elsif RED_SUITS.include?(suit)
:red
end
end
def to_s
"Playing Card #{rank}#{suit.to_s[0].upcase}"
end
def suit_text
self.class.suit_text(suit)
end
def rank_text
self.class.rank_text(rank)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/dealt_pile.rb | samples/elaborate/klondike_solitaire/model/dealt_pile.rb | class KlondikeSolitaire
module Model
class DealtPile
def initialize(game)
@game = game
end
def reset!
playing_cards.clear
end
def push!(playing_card)
playing_cards.push(playing_card)
end
def remove!(card)
playing_cards.delete(card)
end
def playing_cards
@playing_cards ||= []
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/column_pile.rb | samples/elaborate/klondike_solitaire/model/column_pile.rb | class KlondikeSolitaire
module Model
class ColumnPile
include Glimmer::DataBinding::ObservableModel
attr_reader :count
def initialize(game, count)
@game = game
@count = count
reset!
end
def reset!
playing_cards.clear
populate!(count.times.map { @game.deck.pop })
end
# this method does not validate
def populate!(new_playing_cards)
new_playing_cards.each_with_index do |playing_card, index|
playing_card.hidden = true if index < (new_playing_cards.size - 1)
playing_cards.push(playing_card)
end
end
# this method validates that playing card fits at the bottom of the column (opposite color and one number smaller)
# throws an error if it does not fit
def add!(new_playing_card)
bottom_card = playing_cards.last
if (playing_cards.empty? && new_playing_card.rank == 13) ||
(new_playing_card.color != bottom_card.color && new_playing_card.rank == (bottom_card.rank - 1))
playing_cards.push(new_playing_card)
else
raise "Cannot add #{new_playing_card} to #{self}"
end
end
def remove!(card)
remove_cards_starting_at(playing_cards.index(card)).tap do |result|
playing_cards.last&.hidden = false
end
end
def remove_cards_starting_at(index)
removed_cards = playing_cards[index...playing_cards.size]
playing_cards[index...playing_cards.size] = []
removed_cards
end
def playing_cards
@playing_cards ||= []
end
def to_s
"Column Pile #{count} (#{playing_cards.map {|card| "#{card.rank}#{card.suit.to_s[0].upcase}"}.join(" | ")})"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/foundation_pile.rb | samples/elaborate/klondike_solitaire/model/foundation_pile.rb | class KlondikeSolitaire
module Model
class FoundationPile
attr_reader :suit
def initialize(game, suit)
@game = game
@suit = suit
reset!
end
def reset!
playing_cards.clear
end
# adds a card
# validates if it is a card that belongs to the suit
def add!(playing_card)
if playing_card.suit == suit &&
(
(playing_cards.empty? && playing_card.rank == 1) ||
playing_card.rank == (playing_cards.last.rank + 1)
)
playing_cards.push(playing_card)
else
raise "Cannot add #{playing_card} to #{self}"
end
end
def playing_cards
@playing_cards ||= []
end
def to_s
"Foundation Pile #{suit} (#{playing_cards.map {|card| "#{card.rank}#{card.suit.to_s[0].upcase}"}.join(" | ")})"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/model/dealing_pile.rb | samples/elaborate/klondike_solitaire/model/dealing_pile.rb | class KlondikeSolitaire
module Model
class DealingPile
DEALING_INITIAL_COUNT = 24
def initialize(game)
@game = game
reset!
end
def reset!
playing_cards.clear
DEALING_INITIAL_COUNT.times { playing_cards << @game.deck.pop }
end
def deal!
playing_card = playing_cards.shift
if playing_card.nil?
@game.dealt_pile.playing_cards.each do |a_playing_card|
playing_cards << a_playing_card
end
@game.dealt_pile.playing_cards.clear
else
@game.dealt_pile.push!(playing_card)
end
end
def playing_cards
@playing_cards ||= []
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/action_panel.rb | samples/elaborate/klondike_solitaire/view/action_panel.rb | class KlondikeSolitaire
module View
class ActionPanel
include Glimmer::UI::CustomWidget
option :game
body {
composite {
grid_layout(1, false) {
margin_width 0
margin_height 0
}
background :dark_green
button {
layout_data :center, :center, true, false
text 'Restart Game'
on_widget_selected do
game.restart!
end
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/playing_card.rb | samples/elaborate/klondike_solitaire/view/playing_card.rb | class KlondikeSolitaire
module View
class PlayingCard
include Glimmer::UI::CustomShape
options :card_x, :card_y, :model, :parent_pile
before_body do
self.card_x ||= 0
self.card_y ||= 0
end
body {
rectangle(card_x, card_y, PLAYING_CARD_WIDTH - 1, PLAYING_CARD_HEIGHT - 1, 15, 15) {
background model.hidden ? :red : :white
# border
rectangle(0, 0, PLAYING_CARD_WIDTH - 1, PLAYING_CARD_HEIGHT - 1, 15, 15) {
foreground :black
}
unless model.hidden?
text {
string model ? "#{model.rank_text}#{model.suit_text}" : ""
font height: PLAYING_CARD_FONT_HEIGHT
x 5
y 5
foreground model ? model.color : :transparent
}
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/empty_playing_card.rb | samples/elaborate/klondike_solitaire/view/empty_playing_card.rb | require_relative '../model/playing_card'
class KlondikeSolitaire
module View
class EmptyPlayingCard
include Glimmer::UI::CustomShape
options :card_x, :card_y, :suit
before_body do
self.card_x ||= 0
self.card_y ||= 0
end
body {
rectangle(card_x, card_y, PLAYING_CARD_WIDTH - 1, PLAYING_CARD_HEIGHT - 1, 15, 15) {
foreground :gray
if suit
text {
string Model::PlayingCard.suit_text(suit)
font height: 20
x :default
y :default
is_transparent true
foreground Model::PlayingCard::BLACK_SUITS.include?(suit) ? :black : :red
}
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/klondike_solitaire_menu_bar.rb | samples/elaborate/klondike_solitaire/view/klondike_solitaire_menu_bar.rb | class KlondikeSolitaire
module View
class KlondikeSolitaireMenuBar
include Glimmer::UI::CustomWidget
option :game
before_body do
@display = display {
on_about do
display_about_dialog
end
on_preferences do
display_about_dialog
end
}
end
body {
menu_bar {
menu {
text '&Game'
menu_item {
text '&Restart'
accelerator (OS.mac? ? :command : :ctrl), :r
on_widget_selected do
game.restart!
end
}
menu_item {
text 'E&xit'
accelerator :alt, :f4
on_widget_selected do
exit(0)
end
}
}
menu {
text '&Help'
menu_item {
text '&About...'
on_widget_selected do
display_about_dialog
end
}
}
}
}
def display_about_dialog
message_box(body_root) {
text 'About'
message "Glimmer Klondike Solitaire\nGlimmer DSL for SWT Elaborate Sample"
}.open
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/dealt_pile.rb | samples/elaborate/klondike_solitaire/view/dealt_pile.rb | require_relative '../model/dealt_pile'
require_relative 'empty_playing_card'
require_relative 'playing_card'
class KlondikeSolitaire
module View
class DealtPile
include Glimmer::UI::CustomShape
options :pile_x, :pile_y, :model
after_body do
observe(model, 'playing_cards.empty?') do |empty_value|
if empty_value
body_root.shapes.to_a.dup.each { |shape| shape.dispose(redraw: false) }
body_root.content {
empty_playing_card
}
else
before_last_shape = body_root.shapes[-2] && body_root.shapes[-2].get_data('custom_shape').respond_to?(:model) && body_root.shapes[-2].get_data('custom_shape').model
if model.playing_cards.last == before_last_shape # happens when dragging card out
body_root.shapes.last.dispose
else
body_root.content {
playing_card(model: model.playing_cards.last, parent_pile: self) {
drag_source true
}
}
end
end
end
end
body {
shape(pile_x, pile_y) {
empty_playing_card
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/column_pile.rb | samples/elaborate/klondike_solitaire/view/column_pile.rb | require_relative '../model/column_pile'
require_relative 'playing_card'
class KlondikeSolitaire
module View
class ColumnPile
include Glimmer::UI::CustomShape
options :pile_x, :pile_y, :model
after_body {
observe(model, 'playing_cards.last.hidden') do
build_column_pile(model.playing_cards)
end
build_column_pile(model.playing_cards)
}
body {
shape(pile_x, pile_y) {
on_drop do |drop_event|
begin
card_shape = drop_event.dragged_shape.get_data('custom_shape')
card = card_shape.model
model.add!(card)
card_parent_pile = card_shape.parent_pile
card_source_model = card_parent_pile.model
cards = card_source_model.remove!(card)
cards[1..-1].each { |card| model.add!(card) } if cards.is_a?(Array) # if it is a column pile
rescue => e
Glimmer::Config.logger.debug { "Error encountered on drop of a card to a column pile: #{e.full_message}" }
drop_event.doit = false
end
end
}
}
def build_column_pile(playing_cards)
body_root.shapes.to_a.dup.each { |shape| shape.dispose(redraw: false) }
current_parent = body_root
playing_cards.each_with_index do |card, i|
current_parent.content {
current_parent = playing_card(card_x: 0, card_y: 20, model: card, parent_pile: self) {
drag_source true unless card.hidden?
}.body_root
}
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/foundation_pile.rb | samples/elaborate/klondike_solitaire/view/foundation_pile.rb | require_relative '../model/playing_card'
require_relative '../model/foundation_pile'
class KlondikeSolitaire
module View
class FoundationPile
include Glimmer::UI::CustomShape
options :pile_x, :pile_y, :game, :suit
attr_accessor :model
before_body do
self.model = game.foundation_piles[Model::PlayingCard::SUITS.index(suit)]
end
after_body do
observe(model, 'playing_cards.last') do |last_card|
if last_card
body_root.content {
playing_card(model: last_card)
}
else
body_root.clear_shapes
body_root.content {
empty_playing_card(suit: suit)
}
end
end
end
body {
shape(pile_x, pile_y) {
empty_playing_card(suit: suit)
on_drop do |drop_event|
begin
card_shape = drop_event.dragged_shape.get_data('custom_shape')
card = card_shape.model
card_parent_pile = card_shape.parent_pile
card_source_model = card_parent_pile.model
raise 'Cannot accept multiple cards' if card_source_model.playing_cards.index(card) != (card_source_model.playing_cards.size - 1)
model.add!(card)
card_source_model.remove!(card)
rescue => e
Glimmer::Config.logger.debug { "Error encountered on drop of a card to a foundation pile: #{e.full_message}" }
drop_event.doit = false
end
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/tableau.rb | samples/elaborate/klondike_solitaire/view/tableau.rb | require_relative 'dealing_pile'
require_relative 'dealt_pile'
require_relative 'column_pile'
require_relative 'foundation_pile'
require_relative '../model/game'
class KlondikeSolitaire
module View
class Tableau
include Glimmer::UI::CustomWidget
option :game
body {
canvas {
background :dark_green
# row 1
@foundation_piles = Model::PlayingCard::SUITS.each_with_index.map do |suit, i|
foundation_pile(pile_x: MARGIN + i*(PLAYING_CARD_WIDTH + PLAYING_CARD_SPACING), pile_y: 0, game: game, suit: suit)
end
@dealt_pile = dealt_pile(pile_x: MARGIN + 5*(PLAYING_CARD_WIDTH + PLAYING_CARD_SPACING), pile_y: 0, model: game.dealt_pile)
@dealing_pile = dealing_pile(pile_x: MARGIN + 6*(PLAYING_CARD_WIDTH + PLAYING_CARD_SPACING), pile_y: 0, model: game.dealing_pile)
# row 2
@column_piles = 7.times.map do |n|
column_pile(pile_x: MARGIN + n*(PLAYING_CARD_WIDTH + PLAYING_CARD_SPACING), pile_y: PLAYING_CARD_HEIGHT + PLAYING_CARD_SPACING, model: game.column_piles[n])
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/dealing_pile.rb | samples/elaborate/klondike_solitaire/view/dealing_pile.rb | require_relative '../model/dealing_pile'
require_relative 'empty_playing_card'
require_relative 'hidden_playing_card'
class KlondikeSolitaire
module View
class DealingPile
include Glimmer::UI::CustomShape
options :pile_x, :pile_y, :model
after_body {
observe(model, 'playing_cards.empty?') do |empty_value|
body_root.shapes.to_a.each { |shape| shape.dispose(redraw: false) }
if empty_value
body_root.content {
empty_playing_card
}
else
body_root.content {
hidden_playing_card
}
end
end
}
body {
shape(pile_x, pile_y) {
hidden_playing_card
on_mouse_up do |event|
model.deal!
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/klondike_solitaire/view/hidden_playing_card.rb | samples/elaborate/klondike_solitaire/view/hidden_playing_card.rb | class KlondikeSolitaire
module View
class HiddenPlayingCard
include Glimmer::UI::CustomShape
options :card_x, :card_y
before_body do
self.card_x ||= 0
self.card_y ||= 0
end
body {
rectangle(card_x, card_y, PLAYING_CARD_WIDTH - 1, PLAYING_CARD_HEIGHT - 1, 15, 15) {
background :red
# border
rectangle(0, 0, PLAYING_CARD_WIDTH - 1, PLAYING_CARD_HEIGHT - 1, 15, 15) {
foreground :black
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/model/game.rb | samples/elaborate/tetris/model/game.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'fileutils'
require 'json'
require 'glimmer/data_binding/observer'
require 'glimmer/config'
require_relative 'block'
require_relative 'tetromino'
require_relative 'past_game'
class Tetris
module Model
class Game
PLAYFIELD_WIDTH = 10
PLAYFIELD_HEIGHT = 20
PREVIEW_PLAYFIELD_WIDTH = 4
PREVIEW_PLAYFIELD_HEIGHT = 2
SCORE_MULTIPLIER = {1 => 40, 2 => 100, 3 => 300, 4 => 1200}
UP_ARROW_ACTIONS = %i[instant_down rotate_right rotate_left]
SPEEDS = %i[snail sloth turtle rabbit gorilla bear horse gazelle cheetah falcon]
SPEED_INITIAL_DELAYS = SPEEDS.each_with_index.inject({}) {|hash, speed_index_pair| hash.merge(speed_index_pair.first => 1.1 - speed_index_pair.last*(0.1)) }
attr_reader :playfield_width, :playfield_height
attr_accessor :game_over, :paused, :preview_tetromino, :lines, :score, :level, :high_scores, :beeping, :added_high_score, :show_high_scores, :up_arrow_action, :show_preview_tetromino, :initial_delay
alias game_over? game_over
alias paused? paused
alias beeping? beeping
alias added_high_score? added_high_score
alias show_preview_tetromino? show_preview_tetromino
def initialize(playfield_width = PLAYFIELD_WIDTH, playfield_height = PLAYFIELD_HEIGHT)
@initial_delay = SPEED_INITIAL_DELAYS[:snail]
@playfield_width = playfield_width
@playfield_height = playfield_height
@high_scores = []
@show_high_scores = false
@beeping = true
@up_arrow_action = :rotate_left
@show_preview_tetromino = true
load_high_scores!
end
def configure_beeper(&beeper)
@beeper = beeper
end
def game_in_progress?
!game_over? && !paused?
end
def start!
self.show_high_scores = false
self.paused = false
self.level = 1
self.score = 0
self.lines = 0
reset_playfield
reset_preview_playfield
reset_tetrominoes
preview_next_tetromino!
consider_adding_tetromino
self.game_over = false
end
alias restart! start!
def game_over!
add_high_score!
beep
self.game_over = true
end
def clear_high_scores!
high_scores.clear
end
def add_high_score!
self.added_high_score = true
high_scores.prepend(PastGame.new("Player #{high_scores.count + 1}", score, lines, level))
end
def save_high_scores!
high_score_file_content = @high_scores.map {|past_game| past_game.to_a.join("\t") }.join("\n")
FileUtils.mkdir_p(tetris_dir)
File.write(tetris_high_score_file, high_score_file_content)
rescue => e
# Fail safely by keeping high scores in memory if unable to access disk
Glimmer::Config.logger.error {"Failed to save high scores in: #{tetris_high_score_file}\n#{e.full_message}"}
end
def load_high_scores!
if File.exist?(tetris_high_score_file)
self.high_scores = File.read(tetris_high_score_file).split("\n").map {|line| PastGame.new(*line.split("\t")) }
end
rescue => e
# Fail safely by keeping high scores in memory if unable to access disk
Glimmer::Config.logger.error {"Failed to load high scores from: #{tetris_high_score_file}\n#{e.full_message}"}
end
def tetris_dir
@tetris_dir ||= File.join(File.expand_path('~'), '.glimmer-tetris')
end
def tetris_high_score_file
File.join(tetris_dir, "high_scores.txt")
end
def down!(instant: false)
return unless game_in_progress?
current_tetromino.down!(instant: instant)
game_over! if current_tetromino.row <= 0 && current_tetromino.stopped?
end
def right!
return unless game_in_progress?
current_tetromino.right!
end
def left!
return unless game_in_progress?
current_tetromino.left!
end
def rotate!(direction)
return unless game_in_progress?
current_tetromino.rotate!(direction)
end
def current_tetromino
tetrominoes.last
end
def tetrominoes
@tetrominoes ||= reset_tetrominoes
end
# Returns blocks in the playfield
def playfield
@playfield ||= @original_playfield = @playfield_height.times.map {
@playfield_width.times.map {
Block.new
}
}
end
# Executes a hypothetical scenario without truly changing playfield permanently
def hypothetical(&block)
@playfield = hypothetical_playfield
block.call
@playfield = @original_playfield
end
# Returns whether currently executing a hypothetical scenario
def hypothetical?
@playfield != @original_playfield
end
def hypothetical_playfield
@playfield_height.times.map { |row|
@playfield_width.times.map { |column|
playfield[row][column].clone
}
}
end
def preview_playfield
@preview_playfield ||= PREVIEW_PLAYFIELD_HEIGHT.times.map {|row|
PREVIEW_PLAYFIELD_WIDTH.times.map {|column|
Block.new
}
}
end
def preview_next_tetromino!
self.preview_tetromino = Tetromino.new(self)
end
def calculate_score!(eliminated_lines)
new_score = SCORE_MULTIPLIER[eliminated_lines] * (level + 1)
self.score += new_score
end
def level_up!
self.level += 1 if lines >= self.level*10
end
def delay
[@initial_delay - (level.to_i * 0.1), 0.001].max
end
def beep
@beeper&.call if beeping
end
SPEED_INITIAL_DELAYS.each do |speed, speed_initial_day|
define_method("speed_#{speed}=") do |is_true|
self.initial_delay = speed_initial_day if is_true
end
define_method("speed_#{speed}") do
self.initial_delay == speed_initial_day
end
end
UP_ARROW_ACTIONS.each do |up_arrow_action_symbol|
define_method("#{up_arrow_action_symbol}_on_up=") do |is_true|
self.up_arrow_action = up_arrow_action_symbol if is_true
end
define_method("#{up_arrow_action_symbol}_on_up") do
self.up_arrow_action == up_arrow_action_symbol
end
end
def reset_tetrominoes
@tetrominoes = []
end
def reset_playfield
playfield.each do |row|
row.each do |block|
block.clear
end
end
end
def reset_preview_playfield
preview_playfield.each do |row|
row.each do |block|
block.clear
end
end
end
def consider_adding_tetromino
if tetrominoes.empty? || current_tetromino.stopped?
preview_tetromino.launch!
preview_next_tetromino!
end
end
def consider_eliminating_lines
eliminated_lines = 0
playfield.each_with_index do |row, playfield_row|
if row.all? {|block| !block.clear?}
eliminated_lines += 1
shift_blocks_down_above_row(playfield_row)
end
end
if eliminated_lines > 0
beep
self.lines += eliminated_lines
level_up!
calculate_score!(eliminated_lines)
end
end
def playfield_remaining_heights(tetromino = nil)
@playfield_width.times.map do |playfield_column|
bottom_most_block = tetromino.bottom_most_block_for_column(playfield_column)
(playfield.each_with_index.detect do |row, playfield_row|
!row[playfield_column].clear? &&
(
tetromino.nil? ||
bottom_most_block.nil? ||
(playfield_row > tetromino.row + bottom_most_block[:row_index])
)
end || [nil, @playfield_height])[1]
end.to_a
end
private
def shift_blocks_down_above_row(row)
row.downto(0) do |playfield_row|
playfield[playfield_row].each_with_index do |block, playfield_column|
previous_row = playfield[playfield_row - 1]
previous_block = previous_row[playfield_column]
block.color = previous_block.color unless block.color == previous_block.color
end
end
playfield[0].each(&:clear)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/model/past_game.rb | samples/elaborate/tetris/model/past_game.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Tetris
module Model
class PastGame
attr_accessor :name, :score, :lines, :level
def initialize(name, score, lines, level)
@name = name
@score = score.to_i
@lines = lines.to_i
@level = level.to_i
end
def to_a
[@name, @score, @lines, @level]
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/model/tetromino.rb | samples/elaborate/tetris/model/tetromino.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'block'
require 'matrix'
class Tetris
module Model
class Tetromino
ORIENTATIONS = [:north, :east, :south, :west]
LETTER_COLORS = {
I: :cyan,
J: :blue,
L: :dark_yellow,
O: :yellow,
S: :green,
T: :magenta,
Z: :red,
}
attr_reader :game, :letter, :preview
alias preview? preview
attr_accessor :orientation, :blocks, :row, :column
def initialize(game)
@game = game
@letter = LETTER_COLORS.keys.sample
@orientation = :north
@blocks = default_blocks
@preview = true
new_row = 0
new_column = (Model::Game::PREVIEW_PLAYFIELD_WIDTH - width)/2
update_playfield(new_row, new_column)
end
def playfield
@preview ? game.preview_playfield : game.playfield
end
def launch!
remove_from_playfield
@preview = false
new_row = 1 - height
new_column = (game.playfield_width - width)/2
update_playfield(new_row, new_column)
game.tetrominoes << self
end
def update_playfield(new_row = nil, new_column = nil)
remove_from_playfield
if !new_row.nil? && !new_column.nil?
@row = new_row
@column = new_column
add_to_playfield
end
end
def add_to_playfield
update_playfield_block do |playfield_row, playfield_column, row_index, column_index|
playfield[playfield_row][playfield_column].color = blocks[row_index][column_index].color if playfield_row >= 0 && playfield[playfield_row][playfield_column]&.clear? && !blocks[row_index][column_index].clear? && playfield[playfield_row][playfield_column].color != blocks[row_index][column_index].color
end
end
def remove_from_playfield
return if @row.nil? || @column.nil?
update_playfield_block do |playfield_row, playfield_column, row_index, column_index|
playfield[playfield_row][playfield_column].clear if playfield_row >= 0 && !blocks[row_index][column_index].clear? && playfield[playfield_row][playfield_column]&.color == color
end
end
def stopped?
return true if @stopped || @preview
playfield_remaining_heights = game.playfield_remaining_heights(self)
result = bottom_most_blocks.any? do |bottom_most_block|
playfield_column = @column + bottom_most_block[:column_index]
playfield_remaining_heights[playfield_column] &&
@row + bottom_most_block[:row_index] >= playfield_remaining_heights[playfield_column] - 1
end
if result && !game.hypothetical?
@stopped = result
game.consider_eliminating_lines
@game.consider_adding_tetromino
end
result
end
# Returns bottom-most blocks of a tetromino, which could be from multiple rows depending on shape (e.g. T)
def bottom_most_blocks
width.times.map do |column_index|
row_blocks_with_row_index = @blocks.each_with_index.to_a.reverse.detect do |row_blocks, row_index|
!row_blocks[column_index].clear?
end
bottom_most_block = row_blocks_with_row_index[0][column_index]
bottom_most_block_row = row_blocks_with_row_index[1]
{
block: bottom_most_block,
row_index: bottom_most_block_row,
column_index: column_index
}
end
end
def bottom_most_block_for_column(column)
bottom_most_blocks.detect {|bottom_most_block| (@column + bottom_most_block[:column_index]) == column}
end
def right_blocked?
(@column == game.playfield_width - width) ||
right_most_blocks.any? { |right_most_block|
(@row + right_most_block[:row_index]) >= 0 &&
playfield[@row + right_most_block[:row_index]][@column + right_most_block[:column_index] + 1].occupied?
}
end
# Returns right-most blocks of a tetromino, which could be from multiple columns depending on shape (e.g. T)
def right_most_blocks
@blocks.each_with_index.map do |row_blocks, row_index|
column_block_with_column_index = row_blocks.each_with_index.to_a.reverse.detect do |column_block, column_index|
!column_block.clear?
end
if column_block_with_column_index
right_most_block = column_block_with_column_index[0]
{
block: right_most_block,
row_index: row_index,
column_index: column_block_with_column_index[1]
}
end
end.compact
end
def left_blocked?
(@column == 0) ||
left_most_blocks.any? { |left_most_block|
(@row + left_most_block[:row_index]) >= 0 &&
playfield[@row + left_most_block[:row_index]][@column + left_most_block[:column_index] - 1].occupied?
}
end
# Returns right-most blocks of a tetromino, which could be from multiple columns depending on shape (e.g. T)
def left_most_blocks
@blocks.each_with_index.map do |row_blocks, row_index|
column_block_with_column_index = row_blocks.each_with_index.to_a.detect do |column_block, column_index|
!column_block.clear?
end
if column_block_with_column_index
left_most_block = column_block_with_column_index[0]
{
block: left_most_block,
row_index: row_index,
column_index: column_block_with_column_index[1]
}
end
end.compact
end
def width
@blocks[0].size
end
def height
@blocks.size
end
def down!(instant: false)
launch! if preview?
unless stopped?
block_count = 1
if instant
remaining_height, bottom_touching_block = remaining_height_and_bottom_touching_block
block_count = remaining_height - @row
end
new_row = @row + block_count
update_playfield(new_row, @column)
end
end
def left!
unless left_blocked?
new_column = @column - 1
update_playfield(@row, new_column)
end
end
def right!
unless right_blocked?
new_column = @column + 1
update_playfield(@row, new_column)
end
end
# Rotate in specified direcation, which can be :right (clockwise) or :left (counterclockwise)
def rotate!(direction)
return if stopped?
can_rotate = nil
new_blocks = nil
game.hypothetical do
hypothetical_rotated_tetromino = hypothetical_tetromino
new_blocks = hypothetical_rotated_tetromino.rotate_blocks(direction)
can_rotate = !hypothetical_rotated_tetromino.stopped? && !hypothetical_rotated_tetromino.right_blocked? && !hypothetical_rotated_tetromino.left_blocked?
end
if can_rotate
remove_from_playfield
self.orientation = ORIENTATIONS[ORIENTATIONS.rotate(direction == :right ? -1 : 1).index(@orientation)]
self.blocks = new_blocks
update_playfield(@row, @column)
end
rescue => e
puts e.full_message
end
def rotate_blocks(direction)
new_blocks = Matrix[*@blocks].transpose.to_a
if direction == :right
new_blocks = new_blocks.map(&:reverse)
else
new_blocks = new_blocks.reverse
end
Matrix[*new_blocks].to_a
end
def hypothetical_tetromino
clone.tap do |hypo_clone|
remove_from_playfield
hypo_clone.blocks = @blocks.map do |row_blocks|
row_blocks.map do |column_block|
column_block.clone
end
end
end
end
def remaining_height_and_bottom_touching_block
playfield_remaining_heights = game.playfield_remaining_heights(self)
bottom_most_blocks.map do |bottom_most_block|
playfield_column = @column + bottom_most_block[:column_index]
[playfield_remaining_heights[playfield_column] - (bottom_most_block[:row_index] + 1), bottom_most_block]
end.min_by(&:first)
end
def default_blocks
case @letter
when :I
[
[block, block, block, block]
]
when :J
[
[block, block, block],
[empty, empty, block],
]
when :L
[
[block, block, block],
[block, empty, empty],
]
when :O
[
[block, block],
[block, block],
]
when :S
[
[empty, block, block],
[block, block, empty],
]
when :T
[
[block, block, block],
[empty, block, empty],
]
when :Z
[
[block, block, empty],
[empty, block, block],
]
end
end
def color
LETTER_COLORS[@letter]
end
def include_block?(block)
@blocks.flatten.include?(block)
end
private
def block
Block.new(color)
end
def empty
Block.new
end
def update_playfield_block(&updater)
@row.upto(@row + height - 1) do |playfield_row|
@column.upto(@column + width - 1) do |playfield_column|
row_index = playfield_row - @row
column_index = playfield_column - @column
updater.call(playfield_row, playfield_column, row_index, column_index)
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/model/block.rb | samples/elaborate/tetris/model/block.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Tetris
module Model
class Block
COLOR_CLEAR = :white
attr_accessor :color
# Initializes with color. Default color (gray) signifies an empty block
def initialize(color = COLOR_CLEAR)
@color = color
end
# Clears block color. `quietly` option indicates if it should not notify observers by setting value quietly via variable not attribute writer.
def clear
self.color = COLOR_CLEAR unless self.color == COLOR_CLEAR
end
def clear?
self.color == COLOR_CLEAR
end
def occupied?
!clear?
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/playfield.rb | samples/elaborate/tetris/view/playfield.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'block'
class Tetris
module View
class Playfield
include Glimmer::UI::CustomWidget
options :game_playfield, :playfield_width, :playfield_height, :block_size
body {
composite((:double_buffered unless OS.mac?)) {
grid_layout {
num_columns playfield_width
make_columns_equal_width true
margin_width block_size
margin_height block_size
horizontal_spacing 0
vertical_spacing 0
}
playfield_height.times { |row|
playfield_width.times { |column|
block(game_playfield: game_playfield, block_size: block_size, row: row, column: column) {
layout_data {
width_hint block_size
height_hint block_size
}
}
}
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/tetris_menu_bar.rb | samples/elaborate/tetris/view/tetris_menu_bar.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Tetris
module View
class TetrisMenuBar
include Glimmer::UI::CustomWidget
COMMAND_KEY = OS.mac? ? :command : :ctrl
options :game
body {
menu_bar {
menu {
text '&Game'
menu_item {
text '&Start'
enabled <= [game, :game_over]
accelerator COMMAND_KEY, :s
on_widget_selected {
game.start!
}
}
menu_item(:check) {
text '&Pause'
accelerator COMMAND_KEY, :p
enabled <= [game, :game_over, on_read: ->(value) { !value && !game.show_high_scores }]
enabled <= [game, :show_high_scores, on_read: ->(value) { !value && !game.game_over }]
selection <=> [game, :paused]
}
menu_item {
text '&Restart'
accelerator COMMAND_KEY, :r
on_widget_selected {
game.restart!
}
}
menu_item(:separator)
menu_item {
text '&Exit'
accelerator COMMAND_KEY, :x
on_widget_selected {
parent_proxy.close
}
}
} # end of menu
menu {
text '&View'
menu_item(:check) {
text 'Show Next Block Preview'
accelerator COMMAND_KEY, :shift, :p
selection <=> [game, :show_preview_tetromino]
}
menu_item(:separator)
menu {
text '&High Scores'
menu_item(:check) {
text '&Show'
accelerator COMMAND_KEY, :shift, :h
selection <=> [game, :show_high_scores]
}
menu_item {
text '&Clear'
accelerator COMMAND_KEY, :shift, :c
on_widget_selected {
game.clear_high_scores!
}
}
}
} # end of menu
menu {
text '&Speed'
Model::Game::SPEEDS.each do |speed|
menu_item(:radio) {
text speed.to_s.capitalize
selection <=> [game, "speed_#{speed}", computed_by: :initial_delay]
}
end
}
menu {
text '&Options'
menu_item(:check) {
text '&Beeping'
accelerator COMMAND_KEY, :b
selection <=> [game, :beeping]
}
menu {
text 'Up Arrow'
menu_item(:radio) {
text '&Instant Down'
accelerator COMMAND_KEY, :shift, :i
selection <=> [game, :instant_down_on_up, computed_by: :up_arrow_action]
}
menu_item(:radio) {
text 'Rotate &Right'
accelerator COMMAND_KEY, :shift, :r
selection <=> [game, :rotate_right_on_up, computed_by: :up_arrow_action]
}
menu_item(:radio) {
text 'Rotate &Left'
accelerator COMMAND_KEY, :shift, :l
selection <=> [game, :rotate_left_on_up, computed_by: :up_arrow_action]
}
}
} # end of menu
menu {
text '&Help'
menu_item {
text '&About'
accelerator COMMAND_KEY, :shift, :a
on_widget_selected {
parent_custom_shell&.show_about_dialog
}
}
} # end of menu
}
}
def parent_custom_shell
# grab custom shell widget wrapping parent widget proxy (i.e. Tetris) and invoke method on it
the_parent_custom_shell = parent_proxy&.get_data('custom_shell')
the_parent_custom_shell if the_parent_custom_shell&.visible?
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/high_score_dialog.rb | samples/elaborate/tetris/view/high_score_dialog.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'tetris_menu_bar'
class Tetris
module View
class HighScoreDialog
include Glimmer::UI::CustomShell
options :parent_shell, :game
after_body do
@game_over_observer = observe(game, :game_over) do |game_over|
close if !game_over
end
end
body {
dialog(parent_shell) {
row_layout {
type :vertical
center true
}
text 'Glimmer Tetris'
tetris_menu_bar(game: game)
label(:center) {
text <= [game, :game_over, on_read: ->(game_over) { game_over ? 'Game Over!' : 'High Scores' }]
font name: FONT_NAME, height: FONT_TITLE_HEIGHT, style: FONT_TITLE_STYLE
}
@high_score_table = table {
layout_data {
height 100
}
table_column {
text 'Name'
}
table_column {
text 'Score'
}
table_column {
text 'Lines'
}
table_column {
text 'Level'
}
items <=> [game, :high_scores, read_only_sort: true]
}
composite {
row_layout :horizontal
@play_close_button = button {
text <= [game, :game_over, on_read: ->(game_over) { game_over ? 'Play Again?' : 'Close'}]
focus true # initial focus
on_widget_selected {
async_exec { close }
game.paused = @game_paused
game.restart! if game.game_over?
}
}
}
on_swt_show {
@game_paused = game.paused?
game.paused = true
if game.game_over? && game.added_high_score?
game.added_high_score = false
game.save_high_scores!
@high_score_table.edit_table_item(
@high_score_table.items.first, # row item
0, # column
write_on_cancel: true,
after_write: -> {
game.save_high_scores!
@play_close_button.set_focus
},
)
end
}
on_shell_closed {
# guard is needed because there is an observer in Tetris closing on
# game.show_high_scores change, which gets set below
unless @closing
@closing = true
@high_score_table.cancel_edit!
game.paused = @game_paused
game.show_high_scores = false
else
@closing = false
end
}
on_widget_disposed {
@game_over_observer.deregister
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/score_lane.rb | samples/elaborate/tetris/view/score_lane.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'block'
require_relative 'playfield'
class Tetris
module View
class ScoreLane
include Glimmer::UI::CustomWidget
options :block_size, :game
before_body do
@font_name = FONT_NAME
@font_height = FONT_TITLE_HEIGHT
end
body {
composite {
row_layout {
type :vertical
center true
fill true
margin_width 0
margin_right block_size
margin_height block_size
}
label(:center) {
text 'Next'
font name: @font_name, height: @font_height, style: FONT_TITLE_STYLE
visible <= [game, :show_preview_tetromino]
}
playfield(game_playfield: game.preview_playfield, playfield_width: Model::Game::PREVIEW_PLAYFIELD_WIDTH, playfield_height: Model::Game::PREVIEW_PLAYFIELD_HEIGHT, block_size: block_size) {
visible <= [game, :show_preview_tetromino]
}
label(:center) {
text 'Score'
font name: @font_name, height: @font_height, style: FONT_TITLE_STYLE
}
label(:center) {
text <= [game, :score]
font height: @font_height
}
label # spacer
label(:center) {
text 'Lines'
font name: @font_name, height: @font_height, style: FONT_TITLE_STYLE
}
label(:center) {
text <= [game, :lines]
font height: @font_height
}
label # spacer
label(:center) {
text 'Level'
font name: @font_name, height: @font_height, style: FONT_TITLE_STYLE
}
label(:center) {
text <= [game, :level]
font height: @font_height
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/bevel.rb | samples/elaborate/tetris/view/bevel.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Creates a class-based custom shape representing the `bevel` keyword by convention
class Tetris
module View
class Bevel
include Glimmer::UI::CustomShape
options :base_color, :size, :bevel_pixel_size
option :x, default: 0
option :y, default: 0
before_body do
self.bevel_pixel_size = 0.16*size.to_f if bevel_pixel_size.nil?
end
body {
rectangle(x, y, size, size) {
background <= [self, :base_color]
polygon(0, 0, size, 0, size - bevel_pixel_size, bevel_pixel_size, bevel_pixel_size, bevel_pixel_size) {
background <= [self, :base_color, on_read: ->(color_value) {
unless color_value.nil?
color = color(color_value)
rgb(color.red + 4*BEVEL_CONSTANT, color.green + 4*BEVEL_CONSTANT, color.blue + 4*BEVEL_CONSTANT)
end
}]
}
polygon(size, 0, size - bevel_pixel_size, bevel_pixel_size, size - bevel_pixel_size, size - bevel_pixel_size, size, size) {
background <= [self, :base_color, on_read: ->(color_value) {
unless color_value.nil?
color = color(color_value)
rgb(color.red - BEVEL_CONSTANT, color.green - BEVEL_CONSTANT, color.blue - BEVEL_CONSTANT)
end
}]
}
polygon(size, size, 0, size, bevel_pixel_size, size - bevel_pixel_size, size - bevel_pixel_size, size - bevel_pixel_size) {
background <= [self, :base_color, on_read: ->(color_value) {
unless color_value.nil?
color = color(color_value)
rgb(color.red - 2*BEVEL_CONSTANT, color.green - 2*BEVEL_CONSTANT, color.blue - 2*BEVEL_CONSTANT)
end
}]
}
polygon(0, 0, 0, size, bevel_pixel_size, size - bevel_pixel_size, bevel_pixel_size, bevel_pixel_size) {
background <= [self, :base_color, on_read: ->(color_value) {
unless color_value.nil?
color = color(color_value)
rgb(color.red - BEVEL_CONSTANT, color.green - BEVEL_CONSTANT, color.blue - BEVEL_CONSTANT)
end
}]
}
rectangle(0, 0, size, size) {
foreground <= [self, :base_color, on_read: ->(color_value) {
# use gray instead of white for the border
color_value == Model::Block::COLOR_CLEAR ? :gray : color_value
}]
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tetris/view/block.rb | samples/elaborate/tetris/view/block.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'bevel'
class Tetris
module View
class Block
include Glimmer::UI::CustomWidget
options :game_playfield, :block_size, :row, :column
body {
canvas { |canvas_proxy|
bevel(size: block_size) {
base_color <= [game_playfield[row][column], :color]
}
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/presenter/cell.rb | samples/elaborate/snake/presenter/cell.rb | class Snake
module Presenter
class Cell
COLOR_CLEAR = :white
COLOR_SNAKE = :green
COLOR_APPLE = :red
attr_reader :row, :column, :grid
attr_accessor :color
def initialize(grid: ,row: ,column: )
@row = row
@column = column
@grid = grid
end
def clear
self.color = COLOR_CLEAR unless color == COLOR_CLEAR
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 150]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/presenter/grid.rb | samples/elaborate/snake/presenter/grid.rb | require 'glimmer'
require_relative '../model/game'
require_relative 'cell'
class Snake
module Presenter
class Grid
include Glimmer
attr_reader :game, :cells
def initialize(game = Model::Game.new)
@game = game
@cells = @game.height.times.map do |row|
@game.width.times.map do |column|
Cell.new(grid: self, row: row, column: column)
end
end
observe(@game.snake, :vertebrae) do |new_vertebrae|
occupied_snake_positions = @game.snake.vertebrae.map {|v| [v.row, v.column]}
@cells.each_with_index do |row_cells, row|
row_cells.each_with_index do |cell, column|
if [@game.apple.row, @game.apple.column] == [row, column]
cell.color = Cell::COLOR_APPLE
elsif occupied_snake_positions.include?([row, column])
cell.color = Cell::COLOR_SNAKE
else
cell.clear
end
end
end
end
end
def clear
@cells.each do |row_cells|
row_cells.each do |cell|
cell.clear
end
end
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 75]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/model/game.rb | samples/elaborate/snake/model/game.rb | require 'fileutils'
require_relative 'snake'
require_relative 'apple'
class Snake
module Model
class Game
WIDTH_DEFAULT = 20
HEIGHT_DEFAULT = 20
FILE_HIGH_SCORE = File.expand_path(File.join(Dir.home, '.glimmer-snake'))
attr_reader :width, :height
attr_accessor :snake, :apple, :over, :score, :high_score, :paused
alias over? over
alias paused? paused
def initialize(width = WIDTH_DEFAULT, height = HEIGHT_DEFAULT)
@width = width
@height = height
@snake = Snake.new(self)
@apple = Apple.new(self)
FileUtils.touch(FILE_HIGH_SCORE)
@high_score = File.read(FILE_HIGH_SCORE).to_i rescue 0
end
def score=(new_score)
@score = new_score
self.high_score = @score if @score > @high_score
end
def high_score=(new_high_score)
@high_score = new_high_score
File.write(FILE_HIGH_SCORE, @high_score.to_s)
rescue => e
puts e.full_message
end
def start
self.over = false
self.score = 0
self.snake.generate
self.apple.generate
end
def pause
self.paused = true
end
def resume
self.paused = false
end
def toggle_pause
unless paused?
pause
else
resume
end
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 75]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/model/apple.rb | samples/elaborate/snake/model/apple.rb | class Snake
module Model
class Apple
attr_reader :game
attr_accessor :row, :column
def initialize(game)
@game = game
end
# generates a new location from scratch or via dependency injection of what cell is (for testing purposes)
def generate(initial_row: nil, initial_column: nil)
if initial_row && initial_column
self.row, self.column = initial_row, initial_column
else
self.row, self.column = @game.height.times.zip(@game.width.times).reject do |row, column|
@game.snake.vertebrae.map {|v| [v.row, v.column]}.include?([row, column])
end.sample
end
end
def remove
self.row = nil
self.column = nil
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 120]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/model/vertebra.rb | samples/elaborate/snake/model/vertebra.rb | class Snake
module Model
class Vertebra
ORIENTATIONS = %i[north east south west]
# orientation is needed for snake occuppied cells (but not apple cells)
attr_reader :snake
attr_accessor :row, :column, :orientation
def initialize(snake: , row: , column: , orientation: )
@row = row || rand(snake.game.height)
@column = column || rand(snake.game.width)
@orientation = orientation || ORIENTATIONS.sample
@snake = snake
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 150]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/snake/model/snake.rb | samples/elaborate/snake/model/snake.rb | require_relative 'vertebra'
class Snake
module Model
class Snake
SCORE_EAT_APPLE = 50
RIGHT_TURN_MAP = {
north: :east,
east: :south,
south: :west,
west: :north
}
LEFT_TURN_MAP = RIGHT_TURN_MAP.invert
attr_accessor :collided
alias collided? collided
attr_reader :game
# vertebrae and joins are ordered from tail to head
attr_accessor :vertebrae
def initialize(game)
@game = game
end
# generates a new snake location and orientation from scratch or via dependency injection of what head_cell and orientation are (for testing purposes)
def generate(initial_row: nil, initial_column: nil, initial_orientation: nil)
self.collided = false
initial_vertebra = Vertebra.new(snake: self, row: initial_row, column: initial_column, orientation: initial_orientation)
self.vertebrae = [initial_vertebra]
end
def length
@vertebrae.length
end
def head
@vertebrae.last
end
def tail
@vertebrae.first
end
def remove
self.vertebrae.clear
self.joins.clear
end
def move
@old_tail = tail.dup
@new_head = head.dup
case @new_head.orientation
when :east
@new_head.column = (@new_head.column + 1) % @game.width
when :west
@new_head.column = (@new_head.column - 1) % @game.width
when :south
@new_head.row = (@new_head.row + 1) % @game.height
when :north
@new_head.row = (@new_head.row - 1) % @game.height
end
if @vertebrae.map {|v| [v.row, v.column]}.include?([@new_head.row, @new_head.column])
self.collided = true
@game.over = true
else
@vertebrae.append(@new_head)
@vertebrae.delete(tail)
if head.row == @game.apple.row && head.column == @game.apple.column
grow
@game.apple.generate
end
end
end
def turn_right
head.orientation = RIGHT_TURN_MAP[head.orientation]
end
def turn_left
head.orientation = LEFT_TURN_MAP[head.orientation]
end
def grow
@game.score += SCORE_EAT_APPLE
@vertebrae.prepend(@old_tail)
end
# inspect is overridden to prevent printing very long stack traces
def inspect
"#{super[0, 150]}... >"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command.rb | samples/elaborate/calculator/model/command.rb | class Calculator
module Model
class Command
class << self
attr_accessor :number1, :number2, :operation
# Keyword string representing calculator command (e.g. '+' for Add command)
# Subclasses must call to define a single keyword
def keyword(keyword_text)
Command.keyword_to_command_class_mapping[keyword_text] = self
end
# Keyword string array representing calculator command (e.g. ('0'..'9').to_a)
# Subclasses must call to define multiple keywords
def keywords(*keyword_text_array)
keyword_text_array.flatten.each do |keyword_text|
keyword(keyword_text)
end
end
def keyword_to_command_class_mapping
@keyword_to_command_class_mapping ||= {}
end
def command_history
@command_history ||= []
end
def purge_command_history
Command.command_history.clear
self.number1 = nil
self.number2 = nil
self.operation = nil
end
def for(button)
command_class = keyword_to_command_class_mapping[button]
command_class&.new(button)&.tap do |command|
command.execute
command_history << command
end
end
end
attr_reader :button
attr_accessor :result
def initialize(button)
@button = button
end
def number1
Command.number1
end
def number1=(value)
Command.number1 = value.to_f
end
def number2
Command.number2
end
def number2=(value)
Command.number2 = value.to_f
end
def operation
Command.operation
end
def operation=(op)
Command.operation = op
end
def last_result
last_command&.result
end
def last_command
command_history.last
end
def command_history
Command.command_history
end
def execute
raise 'Not implemented! Please override in a subclass.'
end
end
end
end
# Dir[File.join(File.dirname(__FILE__), 'command', '**', '*.rb')].each {|f| require(f)} # disabled for Opal compatibility
require_relative 'command/all_clear'
require_relative 'command/equals'
require_relative 'command/number'
require_relative 'command/operation'
require_relative 'command/point'
require_relative 'command/operation/add'
require_relative 'command/operation/divide'
require_relative 'command/operation/multiply'
require_relative 'command/operation/subtract'
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/presenter.rb | samples/elaborate/calculator/model/presenter.rb | require_relative 'command'
class Calculator
module Model
class Presenter
FORMATTER = {
nil => '0',
'NaN' => 'Not a number'
}
attr_accessor :result
def initialize
self.result = '0'
end
def press(button)
command = Command.for(button)
if command
new_result = command.result
self.result = FORMATTER[new_result] || new_result
end
end
def purge_command_history
Command.purge_command_history
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/equals.rb | samples/elaborate/calculator/model/command/equals.rb | class Calculator
module Model
class Command
class Equals < Command
keywords '=', "\r"
def execute
if number1 && number2 && operation
self.result = operation.calculate.to_s
self.number1 = self.result
else
self.result = last_result || '0'
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/all_clear.rb | samples/elaborate/calculator/model/command/all_clear.rb | class Calculator
module Model
class Command
class AllClear < Command
keywords 'AC', 'c', 'C', 8.chr, 27.chr, 127.chr
def execute
self.result = '0'
self.number1 = nil
self.number2 = nil
self.operation = nil
command_history.clear
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/command_history.rb | samples/elaborate/calculator/model/command/command_history.rb | ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false | |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/point.rb | samples/elaborate/calculator/model/command/point.rb | class Calculator
module Model
class Command
class Point < Command
keyword '.'
def execute
self.result = last_result.nil? || !last_command.is_a?(Number) ? '0.' : "#{last_result}."
if operation.nil? || last_command.is_a?(Equals)
self.number1 = self.result
self.number2 = nil
self.operation = nil
else
self.number2 = self.result
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/number.rb | samples/elaborate/calculator/model/command/number.rb | class Calculator
module Model
class Command
class Number < Command
keywords ('0'..'9').to_a
def execute
self.result = last_result.nil? || (!last_command.is_a?(Number) && !last_command.is_a?(Point)) ? button : last_result + button
if operation.nil? || last_command.is_a?(Equals)
self.number1 = self.result
self.number2 = nil
self.operation = nil
else
self.number2 = self.result
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/operation.rb | samples/elaborate/calculator/model/command/operation.rb | class Calculator
module Model
class Command
class Operation < Command
def execute
if number1 && number2 && operation && !last_command.is_a?(Equals)
self.result = operation.calculate.to_s
self.number1 = self.result
else
self.result = last_result || '0'
self.operation = self
end
end
def calculate
calculation_result = BigDecimal.new(number1.to_s).send(operation_method, BigDecimal.new(number2.to_s)).to_f
calculation_result.to_s.match(/\.0+$/) ? calculation_result.to_i : calculation_result
end
# Subclasses must implement to indicate operation method on number (e.g. :+ for addition)
def operation_method
raise 'Not implemented!'
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/operation/add.rb | samples/elaborate/calculator/model/command/operation/add.rb | class Calculator
module Model
class Command
class Operation < Command
class Add < Operation
keyword '+'
def operation_method
:+
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/operation/subtract.rb | samples/elaborate/calculator/model/command/operation/subtract.rb | class Calculator
module Model
class Command
class Operation < Command
class Subtract < Operation
keywords '−', '-'
def operation_method
:-
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/operation/multiply.rb | samples/elaborate/calculator/model/command/operation/multiply.rb | class Calculator
module Model
class Command
class Operation < Command
class Multiply < Operation
keywords '×', '*'
def operation_method
:*
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/calculator/model/command/operation/divide.rb | samples/elaborate/calculator/model/command/operation/divide.rb | class Calculator
module Model
class Command
class Operation < Command
class Divide < Operation
keywords '÷', '/'
def operation_method
:/
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/model/piece.rb | samples/elaborate/quarto/model/piece.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Quarto
module Model
class Piece
class << self
def all_pieces
[
Cube.new(pitted: false, height: :tall, color: :light),
Cylinder.new(pitted: false, height: :tall, color: :light),
Cube.new(pitted: true, height: :short, color: :light),
Cube.new(pitted: false, height: :short, color: :light),
Cube.new(pitted: false, height: :tall, color: :dark),
Cylinder.new(pitted: true, height: :short, color: :dark),
Cylinder.new(pitted: false, height: :short, color: :dark),
Cylinder.new(pitted: true, height: :tall, color: :dark),
Cylinder.new(pitted: false, height: :tall, color: :dark),
Cube.new(pitted: true, height: :short, color: :dark),
Cube.new(pitted: false, height: :short, color: :dark),
Cube.new(pitted: true, height: :tall, color: :dark),
].freeze
end
end
attr_reader :pitted, :height, :color
alias pitted? pitted
def initialize(pitted: , height: , color: )
@pitted = pitted
@height = height
@color = color
end
def light?
@color == :light
end
def dark?
@color == :dark
end
def tall?
@height == :tall
end
def short?
@height == :short
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/model/game.rb | samples/elaborate/quarto/model/game.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'piece'
require_relative 'piece/cube'
require_relative 'piece/cylinder'
class Quarto
module Model
class Game
MOVES = [:select_piece, :place_piece]
PLAYER_NUMBERS = [1, 2]
ROW_COUNT = 4
COLUMN_COUNT = 4
attr_accessor :board, :available_pieces, :selected_piece, :current_move, :current_player_number, :over, :winner_player_number
alias over? over
def initialize
start
end
def start
self.over = false
self.board = ROW_COUNT.times.map {COLUMN_COUNT.times.map {nil}}
self.available_pieces = Piece.all_pieces.dup
self.selected_piece = nil
self.current_player_number = 1
self.current_move = MOVES.first
self.winner_player_number = nil
end
alias restart start
def select_piece(piece)
self.selected_piece = piece
next_player
next_move
end
def place_piece(piece, row:, column:)
if @board[row][column].nil?
@board[row][column] = piece
if win?
self.winner_player_number = current_player_number # must set before updating observed over attribute
self.over = true
elsif draw?
self.winner_player_number = nil # must set before updating observed over attribute
self.over = true
else
next_move
end
end
end
def next_move
last_move = current_move
last_move_index = MOVES.index(last_move)
self.current_move = MOVES[(last_move_index + 1)%MOVES.size]
end
def next_player
last_player_number = current_player_number
last_player_number_index = PLAYER_NUMBERS.index(current_player_number)
self.current_player_number = PLAYER_NUMBERS[(last_player_number_index + 1)%PLAYER_NUMBERS.size]
end
def draw?
!win? && board.flatten.compact.count == 12
end
def win?
row_win? || column_win? || diagonal_win?
end
def row_win?
ROW_COUNT.times.any? { |row| equivalent_pieces?(@board[row]) }
end
def column_win?
COLUMN_COUNT.times.any? do |column|
equivalent_pieces?(ROW_COUNT.times.map {|row| @board[row][column]})
end
end
def diagonal_win?
diagonal1_win? || diagonal2_win?
end
def diagonal1_win?
equivalent_pieces?(ROW_COUNT.times.map { |n| @board[n][n] })
end
def diagonal2_win?
equivalent_pieces?(ROW_COUNT.times.map { |n| @board[ROW_COUNT - 1 - n][n] })
end
def equivalent_pieces?(the_pieces)
return false if the_pieces.any?(&:nil?)
the_pieces.map(&:class).uniq.size == 1 ||
the_pieces.map(&:pitted).uniq.size == 1 ||
the_pieces.map(&:height).uniq.size == 1 ||
the_pieces.map(&:color).uniq.size == 1
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/model/piece/cube.rb | samples/elaborate/quarto/model/piece/cube.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative '../piece'
class Quarto
module Model
class Piece
class Cube < Piece
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/model/piece/cylinder.rb | samples/elaborate/quarto/model/piece/cylinder.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative '../piece'
class Quarto
module Model
class Piece
class Cylinder < Piece
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/piece.rb | samples/elaborate/quarto/view/piece.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cylinder'
require_relative 'cube'
class Quarto
module View
class Piece
include Glimmer::UI::CustomShape
SIZE_SHORT = 28
SIZE_TALL = 48
BASIC_SHAPE_WIDTH = 48
BASIC_SHAPE_HEIGHT = 28
LINE_THICKNESS = 2
options :game, :model, :location_x, :location_y
before_body do
@background_color = model.light? ? COLOR_LIGHT_WOOD : COLOR_DARK_WOOD
@size = model.short? ? SIZE_SHORT : SIZE_TALL
@shape_location_x = 0
@shape_location_y = model.short? ? 20 : 0
end
body {
shape(location_x, location_y) {
if model.is_a?(Model::Piece::Cylinder)
cylinder(location_x: @shape_location_x, location_y: @shape_location_y, cylinder_height: @size, oval_width: BASIC_SHAPE_WIDTH, oval_height: BASIC_SHAPE_HEIGHT, pitted: model.pitted?, background_color: @background_color, line_thickness: LINE_THICKNESS)
else
cube(location_x: @shape_location_x, location_y: @shape_location_y, cube_height: @size, rectangle_width: BASIC_SHAPE_WIDTH, rectangle_height: BASIC_SHAPE_HEIGHT, pitted: model.pitted?, background_color: @background_color, line_thickness: LINE_THICKNESS)
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/cube.rb | samples/elaborate/quarto/view/cube.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Quarto
module View
class Cube
include Glimmer::UI::CustomShape
DEFAULT_SIZE = 28
options :location_x, :location_y, :rectangle_width, :rectangle_height, :cube_height, :pitted, :background_color, :line_thickness
alias pitted? pitted
before_body do
self.location_x ||= 0
self.location_y ||= 0
self.rectangle_width ||= rectangle_height || cube_height || DEFAULT_SIZE
self.rectangle_height ||= rectangle_width || cube_height || DEFAULT_SIZE
self.cube_height ||= rectangle_width || rectangle_height || DEFAULT_SIZE
self.line_thickness ||= 1
end
body {
shape(location_x, location_y) {
polygon(0, cube_height + rectangle_height / 2.0, rectangle_width / 2.0, cube_height, rectangle_width, cube_height + rectangle_height / 2.0, rectangle_width / 2.0, cube_height + rectangle_height) {
background background_color
}
polygon(0, cube_height + rectangle_height / 2.0, rectangle_width / 2.0, cube_height, rectangle_width, cube_height + rectangle_height / 2.0, rectangle_width / 2.0, cube_height + rectangle_height) {
line_width line_thickness
}
rectangle(0, rectangle_height / 2.0, rectangle_width, cube_height) {
background background_color
}
polyline(0, rectangle_height / 2.0 + cube_height, 0, rectangle_height / 2.0, rectangle_width, rectangle_height / 2.0, rectangle_width, rectangle_height / 2.0 + cube_height) {
line_width line_thickness
}
polygon(0, rectangle_height / 2.0, rectangle_width / 2.0, 0, rectangle_width, rectangle_height / 2.0, rectangle_width / 2.0, rectangle_height) {
background background_color
}
polygon(0, rectangle_height / 2.0, rectangle_width / 2.0, 0, rectangle_width, rectangle_height / 2.0, rectangle_width / 2.0, rectangle_height) {
line_width line_thickness
}
line(rectangle_width / 2.0, cube_height + rectangle_height, rectangle_width / 2.0, rectangle_height) {
line_width line_thickness
}
if pitted?
oval(rectangle_width / 4.0, rectangle_height / 4.0, rectangle_width / 2.0, rectangle_height / 2.0) {
background :black
}
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/message_box_panel.rb | samples/elaborate/quarto/view/message_box_panel.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Quarto
module View
class MessageBoxPanel
include Glimmer::UI::CustomShape
FONT_HEIGHT_DEFAULT = 12
BUTTON_TEXT_DEFAULT = 'OK'
option :message
option :location_x, default: :default
option :location_y, default: :default
option :size_width
option :size_height
option :background_color, default: :white
option :foreground_color, default: :black
option :border_line_width, default: 1
option :text_font, default: {height: FONT_HEIGHT_DEFAULT}
option :text_color, default: :black
attr_reader :closed
alias closed? closed
def can_handle_observation_request?(observation_request)
observation_request == 'on_closed' || super
end
def handle_observation_request(observation_request, &block)
if observation_request == 'on_closed'
@on_closed_handlers ||= []
@on_closed_handlers << block
else
super
end
end
before_body do
@font_height = text_font[:height] || FONT_HEIGHT_DEFAULT
self.size_width ||= [:default, @font_height*4.0]
self.size_height ||= [:default, @font_height*4.0]
@text_offset = -1.2*@font_height
display {
on_swt_keyup do |key_event|
close if key_event.keyCode == swt(:cr)
end
}
end
body {
rectangle(location_x, location_y, size_width, size_height, round: true) {
background background_color
text(message, :default, [:default, @text_offset]) {
foreground :black
font text_font
}
rectangle(0, 0, :max, :max, round: true) { # border drawn around max dimensions of parent
foreground foreground_color
line_width border_line_width
}
rectangle(:default, [:default, @font_height + (@font_height/2.0)], @font_height*5.5, @font_height*2.0, @font_height, @font_height, round: true) {
background background_color
text(BUTTON_TEXT_DEFAULT) {
foreground text_color
font text_font
}
on_mouse_up do
close
end
}
rectangle(:default, [:default, @font_height + (@font_height/2.0)], @font_height*5.5, @font_height*2.0, @font_height, @font_height, round: true) { # border
foreground foreground_color
line_width border_line_width
}
}
}
def close
unless @closed
@closed = true
@on_closed_handlers&.each {|handler| handler.call}
@on_closed_handlers&.clear
body_root.dispose
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/cell.rb | samples/elaborate/quarto/view/cell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Quarto
module View
class Cell
include Glimmer::UI::CustomShape
options :game, :row, :column
attr_reader :placed_piece
before_body do
@board_x_offset = (BOARD_DIAMETER - COLUMN_COUNT * (CELL_DIAMETER + CELL_LINE_WIDTH + CELL_MARGIN) + CELL_LINE_WIDTH + CELL_MARGIN) / 2.0
@board_y_offset = (BOARD_DIAMETER - ROW_COUNT * (CELL_DIAMETER + CELL_LINE_WIDTH + CELL_MARGIN) + CELL_LINE_WIDTH + CELL_MARGIN) / 2.0
end
body {
oval(@board_x_offset + column * (CELL_DIAMETER + CELL_LINE_WIDTH + CELL_MARGIN),
@board_y_offset + row * (CELL_DIAMETER + CELL_LINE_WIDTH + CELL_MARGIN),
CELL_DIAMETER,
CELL_DIAMETER) {
background :black
line_width CELL_LINE_WIDTH
transform board_rotation_transform
oval { # this draws an outline around max dimensions by default (when no x,y,w,h specified)
foreground COLOR_WOOD
line_width CELL_LINE_WIDTH
transform board_rotation_transform
}
on_drop do |drop_event|
dragged_piece = drop_event.dragged_shape
if dragged_piece.parent.get_data('custom_shape').is_a?(SelectedPieceArea)
model = dragged_piece.get_data('custom_shape').model
dragged_piece.dispose
new_x, new_y = body_root.transform_point(body_root.absolute_x, body_root.absolute_y)
parent_proxy.content {
piece(game: game, model: model, location_x: new_x, location_y: new_y) {
transform {
translate -38, -14
}
}
}
game.place_piece(model, row: row, column: column)
else
drop_event.doit = false
end
end
}
}
def board_rotation_transform
@board_rotation_transform ||= transform {
# main rotation is done by moving shape to be centered in origin, rotating, and then moving shape back
translate (SHELL_MARGIN + BOARD_DIAMETER)/2.0, (SHELL_MARGIN + BOARD_DIAMETER)/2.0
rotate 45
translate -(SHELL_MARGIN + BOARD_DIAMETER)/2.0, -(SHELL_MARGIN + BOARD_DIAMETER)/2.0
# extra translation to improve location of rotated cells
translate 7, -4
}
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/cylinder.rb | samples/elaborate/quarto/view/cylinder.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Quarto
module View
class Cylinder
include Glimmer::UI::CustomShape
DEFAULT_SIZE = 28
options :location_x, :location_y, :oval_width, :oval_height, :cylinder_height, :pitted, :background_color, :line_thickness
alias pitted? pitted
before_body do
self.location_x ||= 0
self.location_y ||= 0
self.oval_width ||= oval_height || cylinder_height || DEFAULT_SIZE
self.oval_height ||= oval_width || cylinder_height || DEFAULT_SIZE
self.cylinder_height ||= oval_width || oval_height || DEFAULT_SIZE
self.line_thickness ||= 1
end
body {
shape(location_x, location_y) {
oval(0, cylinder_height, oval_width, oval_height) {
background background_color
oval { # draws with foreground :black and has max size within parent by default
line_width line_thickness
}
}
rectangle(0, oval_height / 2.0, oval_width, cylinder_height) {
background background_color
}
polyline(0, oval_height / 2.0 + cylinder_height, 0, oval_height / 2.0, oval_width, oval_height / 2.0, oval_width, oval_height / 2.0 + cylinder_height) {
line_width line_thickness
}
oval(0, 0, oval_width, oval_height) {
background background_color
oval { # draws with foreground :black and has max size within parent by default
line_width line_thickness
}
}
if pitted?
oval(oval_width / 4.0, oval_height / 4.0, oval_width / 2.0, oval_height / 2.0) {
background :black
}
end
}
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/board.rb | samples/elaborate/quarto/view/board.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class Quarto
module View
class Board
include Glimmer::UI::CustomShape
option :game
option :location_x, default: 0
option :location_y, default: 0
after_body do
reset_cells
end
body {
rectangle(location_x, location_y, BOARD_DIAMETER, BOARD_DIAMETER, round: true) {
background :black
text("Glimmer\nQuarto", BOARD_DIAMETER - 69, BOARD_DIAMETER - 43) {
foreground COLOR_WOOD
}
@cell_container = oval(0, 0, :max, :max) {
foreground COLOR_WOOD
line_width CELL_LINE_WIDTH
}
}
}
def reset_cells
@cell_container.shapes.dup.each(&:dispose)
@cell_container.content {
@cells = ROW_COUNT.times.map do |row|
COLUMN_COUNT.times.map do |column|
cell(game: game, row: row, column: column)
end
end.flatten
}
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/selected_piece_area.rb | samples/elaborate/quarto/view/selected_piece_area.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# require_relative 'piece'
class Quarto
module View
class SelectedPieceArea
include Glimmer::UI::CustomShape
options :game
option :location_x, default: 0
option :location_y, default: 0
attr_reader :selected_piece
body {
rectangle(location_x, location_y, PIECES_AREA_WIDTH, SELECTED_PIECE_AREA_HEIGHT) {
background COLOR_WOOD
rectangle(0, 0, :max, :max, round: true) { # border
foreground :black
line_width 2
}
text('Selected Piece', 15, 10) {
font height: 18, style: :bold
}
on_drop do |drop_event|
dragged_piece = drop_event.dragged_shape
if dragged_piece.parent.get_data('custom_shape').is_a?(AvailablePiecesArea)
model = dragged_piece.get_data('custom_shape').model
dragged_piece.dispose
body_root.content {
@selected_piece = piece(game: game, model: model, location_x: 15, location_y: 15 + 25)
}
game.select_piece(model)
else
drop_event.doit = false
end
end
}
}
def reset_selected_piece
@selected_piece&.dispose
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/quarto/view/available_pieces_area.rb | samples/elaborate/quarto/view/available_pieces_area.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'piece'
class Quarto
module View
class AvailablePiecesArea
include Glimmer::UI::CustomShape
options :game
option :location_x, default: 0
option :location_y, default: 0
attr_reader :pieces
after_body do
reset_pieces
end
body {
rectangle(location_x, location_y, PIECES_AREA_WIDTH, AVAILABLE_PIECES_AREA_HEIGHT) {
background COLOR_WOOD
rectangle(0, 0, :max, :max, round: true) { # border
foreground :black
line_width 2
}
text('Available Pieces', 15, 10) {
font height: 18, style: :bold
}
}
}
def reset_pieces
@pieces&.dup&.each { |piece| piece.dispose(redraw: false) }
body_root.content {
x_offset = 15
y_offset = 10 + 18 + 10
x_spacing = 10
y_spacing = 35
row_count = 3
column_count = 4
@pieces = row_count.times.map do |row|
column_count.times.map do |column|
piece(game: game, model: game.available_pieces[row*column_count + column], location_x: x_offset + column*(View::Piece::BASIC_SHAPE_WIDTH + x_spacing), location_y: y_offset + row*(View::Piece::SIZE_TALL + y_spacing))
end
end.flatten
}
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/connect4/model/slot.rb | samples/elaborate/connect4/model/slot.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Connect4
module Model
class Slot
attr_reader :grid
# value 0 means empty, 1 means player 1 coin, and 2 means player 2 coin
attr_accessor :value
def initialize(grid)
@value = 0
@grid = grid
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/connect4/model/grid.rb | samples/elaborate/connect4/model/grid.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'slot'
class Connect4
module Model
class Grid
WIDTH = 7
HEIGHT = 6
attr_reader :slot_rows
attr_accessor :current_player, :game_over
def initialize
build_slots
start!
end
def start!
self.game_over = false
self.current_player = 1
reset_slots
end
alias restart! start!
def insert!(column_index)
found_row_index = bottom_most_free_row_index(column_index)
raise "Illegal move at #{column_index}" if found_row_index == -1
@slot_rows[found_row_index][column_index].value = @current_player
self.current_player = @current_player%2 + 1
evaluate_game_over
end
# returns bottom most free row index
# returns -1 if none
def bottom_most_free_row_index(column_index)
found_row_index = @slot_rows.size - 1
found_row_index -= 1 until found_row_index == -1 || @slot_rows[found_row_index][column_index].value == 0
found_row_index
end
private
def build_slots
@slot_rows = HEIGHT.times.map do |row_index|
WIDTH.times.map do |column_index|
Slot.new(self)
end
end
end
def reset_slots
@slot_rows.flatten.each {|s| s.value = 0}
end
def evaluate_game_over
evaluate_horizontal_win
evaluate_vertical_win
evaluate_sw_ne_diagonal_win
evaluate_se_nw_diagonal_win
self.game_over ||= true if @slot_rows.flatten.map(&:value).all? {|v| v > 0}
end
def evaluate_horizontal_win
connections = nil
last_slot_value = nil
HEIGHT.times do |row_index|
connections = nil
last_slot_value = nil
WIDTH.times do |column_index|
slot = @slot_rows[row_index][column_index]
if slot.value.to_i > 0 && slot.value == last_slot_value
connections += 1
else
last_slot_value = slot.value
connections = 1
end
break if connections == 4
end
break if connections == 4
end
self.game_over = last_slot_value if connections == 4
end
def evaluate_vertical_win
connections = nil
last_slot_value = nil
WIDTH.times do |column_index|
connections = nil
last_slot_value = nil
HEIGHT.times do |row_index|
slot = @slot_rows[row_index][column_index]
if slot.value.to_i > 0 && slot.value == last_slot_value
connections += 1
else
last_slot_value = slot.value
connections = 1
end
break if connections == 4
end
break if connections == 4
end
self.game_over = last_slot_value if connections == 4
end
def evaluate_sw_ne_diagonal_win
sw_ne_coordinates = [
[[3, 0], [2, 1], [1, 2], [0, 3]],
[[4, 0], [3, 1], [2, 2], [1, 3], [0, 4]],
[[5, 0], [4, 1], [3, 2], [2, 3], [1, 4], [0, 5]],
[[5, 1], [4, 2], [3, 3], [2, 4], [1, 5], [0, 6]],
[[5, 2], [4, 3], [3, 4], [2, 5], [1, 6]],
[[5, 3], [4, 4], [3, 5], [2, 6]],
]
evaluate_diagonal_win(sw_ne_coordinates)
end
def evaluate_se_nw_diagonal_win
sw_ne_coordinates = [
[[0, 3], [1, 4], [2, 5], [3, 6]],
[[0, 2], [1, 3], [2, 4], [3, 5], [4, 6]],
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]],
[[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5]],
[[1, 0], [2, 1], [3, 2], [4, 3], [5, 4]],
[[2, 0], [3, 1], [4, 2], [5, 3]],
]
evaluate_diagonal_win(sw_ne_coordinates)
end
def evaluate_diagonal_win(diagonal_coordinates)
connections = nil
last_slot_value = nil
diagonal_coordinates.each do |group|
connections = nil
last_slot_value = nil
group.each do |row_index, column_index|
slot = @slot_rows[row_index][column_index]
if slot.value.to_i > 0 && slot.value == last_slot_value
connections += 1
else
last_slot_value = slot.value
connections = 1
end
break if connections == 4
end
break if connections == 4
end
self.game_over = last_slot_value if connections == 4
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tic_tac_toe/cell.rb | samples/elaborate/tic_tac_toe/cell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class TicTacToe
class Cell
EMPTY = ""
attr_accessor :sign, :empty
def initialize
reset!
end
def mark(sign)
self.sign = sign
end
def reset!
self.sign = EMPTY
end
def sign=(sign_symbol)
@sign = sign_symbol
self.empty = sign == EMPTY
end
def marked
!empty
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/tic_tac_toe/board.rb | samples/elaborate/tic_tac_toe/board.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class TicTacToe
class Board
DRAW = :draw
IN_PROGRESS = :in_progress
WIN = :win
attr :winning_sign
attr_accessor :game_status
def initialize
@sign_state_machine = {nil => "X", "X" => "O", "O" => "X"}
build_grid
@winning_sign = Cell::EMPTY
@game_status = IN_PROGRESS
end
#row and column numbers are 1-based
def mark(row, column)
self[row, column].mark(current_sign)
game_over? #updates winning sign
end
def current_sign
@current_sign = @sign_state_machine[@current_sign]
end
def [](row, column)
@grid[row-1][column-1]
end
def game_over?
win? or draw?
end
def win?
win = (row_win? or column_win? or diagonal_win?)
self.game_status=WIN if win
win
end
def reset!
(1..3).each do |row|
(1..3).each do |column|
self[row, column].reset!
end
end
@winning_sign = Cell::EMPTY
@current_sign = nil
self.game_status=IN_PROGRESS
end
private
def build_grid
@grid = []
3.times do |row_index| #0-based
@grid << []
3.times { @grid[row_index] << Cell.new }
end
end
def row_win?
(1..3).each do |row|
if row_has_same_sign(row)
@winning_sign = self[row, 1].sign
return true
end
end
false
end
def column_win?
(1..3).each do |column|
if column_has_same_sign(column)
@winning_sign = self[1, column].sign
return true
end
end
false
end
#needs refactoring if we ever decide to make the board size dynamic
def diagonal_win?
if (self[1, 1].sign == self[2, 2].sign) and (self[2, 2].sign == self[3, 3].sign) and self[1, 1].marked
@winning_sign = self[1, 1].sign
return true
end
if (self[3, 1].sign == self[2, 2].sign) and (self[2, 2].sign == self[1, 3].sign) and self[3, 1].marked
@winning_sign = self[3, 1].sign
return true
end
false
end
def draw?
@board_full = true
3.times do |x|
3.times do |y|
@board_full = false if self[x, y].empty
end
end
self.game_status = DRAW if @board_full
@board_full
end
def row_has_same_sign(number)
row_sign = self[number, 1].sign
[2, 3].each do |column|
return false unless row_sign == (self[number, column].sign)
end
true if self[number, 1].marked
end
def column_has_same_sign(number)
column_sign = self[1, number].sign
[2, 3].each do |row|
return false unless column_sign == (self[row, number].sign)
end
true if self[1, number].marked
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/contact_manager/contact_manager_presenter.rb | samples/elaborate/contact_manager/contact_manager_presenter.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative "contact_repository"
class ContactManager
class ContactManagerPresenter
attr_accessor :results, :selected_contact
@@contact_attributes = [:first_name, :last_name, :email]
@@contact_attributes.each {|attribute_name| attr_accessor attribute_name}
def initialize(contact_repository = nil)
@contact_repository = contact_repository || ContactRepository.new
@results = []
end
def list
@applied_filter = {}
filter
end
def find
@applied_filter = fields
filter
end
def filter
self.results = @contact_repository.find(@applied_filter)
end
def fields
filters = {}
@@contact_attributes.each do |attribute_name|
filters[attribute_name] = self.send(attribute_name) if self.send(attribute_name)
end
filters
end
def clear_fields
@@contact_attributes.each do |attribute_name|
self.send("#{attribute_name}=", '')
end
end
def create
created_contact = @contact_repository.create(fields)
filter
clear_fields
created_contact
end
def delete
deleted_contact = @contact_repository.delete(@selected_contact)
filter
self.selected_contact = nil
deleted_contact
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/contact_manager/contact_repository.rb | samples/elaborate/contact_manager/contact_repository.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative "contact"
class ContactManager
class ContactRepository
NAMES_FIRST = %w[
Liam
Noah
William
James
Oliver
Benjamin
Elijah
Lucas
Mason
Logan
Alexander
Ethan
Jacob
Michael
Daniel
Henry
Jackson
Sebastian
Aiden
Matthew
Samuel
David
Joseph
Carter
Owen
Wyatt
John
Jack
Luke
Jayden
Dylan
Grayson
Levi
Isaac
Gabriel
Julian
Mateo
Anthony
Jaxon
Lincoln
Joshua
Christopher
Andrew
Theodore
Caleb
Ryan
Asher
Nathan
Thomas
Leo
Isaiah
Charles
Josiah
Hudson
Christian
Hunter
Connor
Eli
Ezra
Aaron
Landon
Adrian
Jonathan
Nolan
Jeremiah
Easton
Elias
Colton
Cameron
Carson
Robert
Angel
Maverick
Nicholas
Dominic
Jaxson
Greyson
Adam
Ian
Austin
Santiago
Jordan
Cooper
Brayden
Roman
Evan
Ezekiel
Xaviar
Jose
Jace
Jameson
Leonardo
Axel
Everett
Kayden
Miles
Sawyer
Jason
Emma
Olivia
]
NAMES_LAST = %w[
Smith
Johnson
Williams
Brown
Jones
Miller
Davis
Wilson
Anderson
Taylor
]
def initialize(contacts = nil)
@contacts = contacts || 100.times.map do |n|
random_first_name_index = (rand*NAMES_FIRST.size).to_i
random_last_name_index = (rand*NAMES_LAST.size).to_i
first_name = NAMES_FIRST[random_first_name_index]
last_name = NAMES_LAST[random_last_name_index]
email = "#{first_name}@#{last_name}.com".downcase
Contact.new(
first_name: first_name,
last_name: last_name,
email: email
)
end
end
def find(attribute_filter_map)
@contacts.find_all do |contact|
match = true
attribute_filter_map.keys.each do |attribute_name|
contact_value = contact.send(attribute_name).downcase
filter_value = attribute_filter_map[attribute_name].downcase
match = false unless contact_value.match(filter_value)
end
match
end
end
def create(attributes)
created_contact = Contact.new(attributes)
@contacts << created_contact
created_contact
end
def delete(contact)
@contacts.delete(contact)
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/contact_manager/contact.rb | samples/elaborate/contact_manager/contact.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class ContactManager
class Contact
attr_accessor :first_name, :last_name, :email
def initialize(attribute_map)
@first_name = attribute_map[:first_name]
@last_name = attribute_map[:last_name]
@email = attribute_map[:email]
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/game_of_life/model/cell.rb | samples/elaborate/game_of_life/model/cell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class GameOfLife
module Model
class Cell
attr_reader :grid, :row_index, :column_index
attr_accessor :alive
alias alive? alive
def initialize(grid, row_index, column_index, alive=false)
@grid = grid
@row_index = row_index
@column_index = column_index
@alive = alive
end
def live!
self.alive = true
end
def die!
self.alive = false
end
def toggle_aliveness!
return if grid.playing?
dead ? live! : die!
end
def dead?
!alive?
end
alias dead dead?
# step into the next generation
def step!
self.alive = (alive? && alive_neighbor_count.between?(2, 3)) || (dead? && alive_neighbor_count == 3)
end
def alive_neighbor_count
[row_index - 1, 0].max.upto([row_index + 1, grid.row_count - 1].min).map do |current_row_index|
[column_index - 1, 0].max.upto([column_index + 1, grid.column_count - 1].min).map do |current_column_index|
if current_row_index == row_index && current_column_index == column_index
0
else
grid.previous_cell_rows[current_row_index][current_column_index].alive? ? 1 : 0
end
end
end.flatten.reduce(:+)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/game_of_life/model/grid.rb | samples/elaborate/game_of_life/model/grid.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'cell'
class GameOfLife
module Model
class Grid
include Glimmer # included only to utilize sync_exec/async_exec
DEFAULT_ROW_COUNT = 100
DEFAULT_COLUMN_COUNT = 100
attr_reader :row_count, :column_count
attr_accessor :cell_rows, :previous_cell_rows, :playing, :speed
alias playing? playing
def initialize(row_count=DEFAULT_ROW_COUNT, column_count=DEFAULT_COLUMN_COUNT)
@row_count = row_count
@column_count = column_count
@speed = 10.0
build_cells
end
def clear!
cell_rows.each do |row|
row.each do |cell|
cell.die!
end
end
end
# steps into the next generation of cells given their current neighbors
def step!
self.previous_cell_rows = cell_rows.map do |row|
row.map do |cell|
cell.clone
end
end
cell_rows.each do |row|
row.each do |cell|
cell.step!
end
end
end
def toggle_playback!
if playing?
stop!
else
play!
end
end
def play!
self.playing = true
Thread.new do
while @playing
sync_exec { step! }
sleep(1.0/@speed)
end
end
end
def stop!
self.playing = false
end
private
def build_cells
@cell_rows = @row_count.times.map do |row_index|
@column_count.times.map do |column_index|
Cell.new(self, row_index, column_index)
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/parking/model/parking_floor.rb | samples/elaborate/parking/model/parking_floor.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'parking_spot'
class Parking
module Model
class ParkingFloor
attr_reader :number, :parking_spots
def initialize(floor_number)
@number = floor_number
@parking_spots = ParkingSpot::LETTERS.reduce({}) do |hash, letter|
hash.merge(letter => ParkingSpot.new(self, letter))
end
end
def book!(parking_spot_letter)
parking_spots[parking_spot_letter].book!
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/parking/model/parking_spot.rb | samples/elaborate/parking/model/parking_spot.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class Parking
module Model
class ParkingSpot
LETTERS = %W[A B C D E F G H I J K L M N O P]
attr_reader :parking_floor, :letter
attr_accessor :booked
alias booked? booked
def initialize(parking_floor, letter)
@parking_floor = parking_floor
@letter = letter
end
def book!
raise "Floor #{parking_floor.number} Parking Spot #{letter} Is Already Booked!" if booked?
self.booked = true
end
def free!
self.booked = false
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/elaborate/parking/model/parking_presenter.rb | samples/elaborate/parking/model/parking_presenter.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require_relative 'parking_floor'
class Parking
module Model
class ParkingPresenter
attr_reader :floor_count
attr_accessor :floors, :selected_floor
def initialize(floor_count)
self.floors = 1.upto(floor_count).map do |floor_number|
ParkingFloor.new(floor_number)
end
self.selected_floor = 1
end
def book(parking_spot_letter)
self.floors[selected_floor - 1].book(parking_spot_letter)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.