xxxxxxxxxx
113
//visualiser for https://www.codingame.com/ide/puzzle/sum-of-spirals-diagonals
var spiralsize;
var rainbow;
var rainbowsize; // hhhhhhhhhhhhh
function setup() {
var cnv = createCanvas(400, 400);
cnv.parent('sketch-holder'); // This will place your canvas inside the div with id 'sketch-holder'
noStroke();
colorMode(HSB, 360, 100, 100);
textAlign(CENTER);
rectMode(CENTER);
spiralsize=createSlider(1, 30, 15, 1).parent('spiralsize')
spiralsize.input(function() {
draw();
select('#spiralsize-value').html(spiralsize.value());
});
rainbowsize=createSlider(100, 900, 300, 1).parent('rainbowsize')
rainbowsize.input(function() {
draw();
select('#rainbowsize-value').html(rainbowsize.value());
});
rainbow = select('#rainbow').parent('rainbow-check').changed(draw)
// initialize values next to sliders
select('#spiralsize-value').html(spiralsize.value());
select('#rainbowsize-value').html(rainbowsize.value());
}
function spiralIn(N) {
const overlayColor = color('rgba(232,228,229,0.41)')
const tileColor = color('rgb(0,255,127)')
const tile_radius = width/N; //based off width only
const tile_offset = 1 + tile_radius/2;
delta = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1],
];
M = tile_radius;
textSize(M/2)
x = -tile_offset;
y = tile_offset;
dir = 0;
j=1;
var total = 0;
let totalRectangles = N*N;
for (var n = N; n > 1; n -= 2) {
for (const k of [0,1,1,2]) {
for (var i = 0; i < n-k; i++) {
x = (x + delta[dir][0] * M);
y = (y + delta[dir][1] * M);
// Calculate the hue value based on the current loop iteration
var hue = map(j, 0, totalRectangles, 0, rainbowsize.value());
fill(hue, 100, 100);
rect(x, y, M);
// diagonal overlay
if (((i == (n-k-1)) && k!=2) || (i==0 && k == 0)) {
fill(overlayColor);
rect(x, y, M);
total+=j;
}
fill('rgb(0,0,0)');
text(j,x,y);
j++;
}
dir = (dir + 1) % 4;
}
}
if (N % 2 > 0) {
x = x + delta[dir][0] * M;
y = y + delta[dir][1] * M;
fill(overlayColor);
rect(x, y, M);
total+=j;
fill('rgb(0,0,0)');
text(j, x, y+5)
}
var totalSpan = select('#total');
totalSpan.html(`Sum of Diagonals: ${total}`);
}
rainbow_theta = 0;
rainbow_change_speed = 0.005;
function draw() {
background(220);
spiralIn(spiralsize.value());
if (rainbow.checked()){
rainbowsize.value((0.1+abs(sin(rainbow_theta/2)))*900)
rainbow_theta += rainbow_change_speed;
}
}