Skip to content

Instantly share code, notes, and snippets.

@jorgemanrubia
Created November 3, 2024 20:59
Show Gist options
  • Save jorgemanrubia/00dab5745ab8b0bde7f5a5799e690a5b to your computer and use it in GitHub Desktop.
Save jorgemanrubia/00dab5745ab8b0bde7f5a5799e690a5b to your computer and use it in GitHub Desktop.
Sudoku in Ruby by ChatGPT
require 'ruby2d'
# Define constants
GRID_SIZE = 9
CELL_SIZE = 60
WINDOW_SIZE = CELL_SIZE * GRID_SIZE
FONT_SIZE = 20
# Create Window
set title: "Ruby Sudoku", width: WINDOW_SIZE, height: WINDOW_SIZE
# Initial Sudoku Board (0 means empty)
board = Array.new(GRID_SIZE) { Array.new(GRID_SIZE, 0) }
selected_cell = [0, 0]
# Helper to draw the grid
def draw_grid
(0..GRID_SIZE).each do |i|
thickness = (i % 3 == 0) ? 4 : 1
Line.new(x1: i * CELL_SIZE, y1: 0, x2: i * CELL_SIZE, y2: WINDOW_SIZE, width: thickness, color: 'black')
Line.new(x1: 0, y1: i * CELL_SIZE, x2: WINDOW_SIZE, y2: i * CELL_SIZE, width: thickness, color: 'black')
end
end
# Draw numbers on the grid
def draw_numbers(board)
board.each_with_index do |row, y|
row.each_with_index do |num, x|
next if num == 0
Text.new(num.to_s, x: x * CELL_SIZE + 20, y: y * CELL_SIZE + 20, size: FONT_SIZE, color: 'blue')
end
end
end
# Highlight selected cell
def highlight_cell(x, y)
Square.new(x: x * CELL_SIZE, y: y * CELL_SIZE, size: CELL_SIZE, color: 'yellow', opacity: 0.3)
end
# Main draw loop
update do
clear
draw_grid
highlight_cell(*selected_cell)
draw_numbers(board)
end
# Handle mouse click to select cell
on :mouse_down do |event|
if event.button == :left
selected_cell = [event.x / CELL_SIZE, event.y / CELL_SIZE]
end
end
# Handle keyboard input to place numbers
on :key_down do |event|
if ('1'..'9').include?(event.key)
x, y = selected_cell
board[y][x] = event.key.to_i
elsif event.key == 'backspace'
x, y = selected_cell
board[y][x] = 0
end
end
show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment