xxxxxxxxxx
// variables
let diceValue; // Stores the current rolled number (1-6)
let dotColor; // Stores the random color for the dots
let diceRotation; // Stores a small random rotation
// Predefined dot positions for each dice number (indexed from 1 to 6)
const dotPositions = [
[], // Index 0 (unused, since dice starts at 1)
[[0, 0]], // Dice face 1 (center dot)
[[-40, -40], [40, 40]], // Dice face 2 (diagonal dots)
[[-40, -40], [0, 0], [40, 40]], // Dice face 3 (diagonal + center dot)
[[-40, -40], [40, -40], [-40, 40], [40, 40]], // Dice face 4 (four corners)
[[-40, -40], [40, -40], [0, 0], [-40, 40], [40, 40]], // Dice face 5 (four corners + center)
[[-40, -40], [40, -40], [-40, 0], [40, 0], [-40, 40], [40, 40]] // Dice face 6 (three pairs of dots)
];
function setup() {
createCanvas(400, 400);
angleMode(DEGREES);
rollDice(); // Roll the dice once when the program starts
}
function draw() {
background(220); // background to light gray
translate(width / 2, height / 2); // to the origin to the center of the canvas
rotate(diceRotation); // a small random rotation to the dice
drawDice(); // Draw the dice shape and its dots
drawFace(); // Draw a facial expression based on the dice value
}
// Function to roll the dice and assign random properties
function rollDice() {
diceValue = int(random(1, 7)); // Generate a random integer between 1 and 6
dotColor = color(random(255), random(255), random(255)); // Assign a random dot color
diceRotation = random(-15, 15); // Give the dice a slight tilt
}
// Function to draw the dice and its dots
function drawDice() {
fill(255); // dice color to white
stroke(0); // black stroke
strokeWeight(4); // thickness
rectMode(CENTER); // Center the rectangle at (0,0)
rect(0, 0, 150, 150, 20); // the dice (150x150 px with rounded corners)
fill(dotColor); // Use the randomized dot color
for (let pos of dotPositions[diceValue]) { // Loop through dot positions for the current diceValue
ellipse(pos[0], pos[1], 20, 20); // Draw a dot at each position
}
}
// Function to draw a face expression based on the dice value
function drawFace() {
let eyeSize = 15; // Set eye size
let mouthY = 30; // Vertical position of the mouth
fill(0);
ellipse(-30, -20, eyeSize, eyeSize); // left eye
ellipse(30, -20, eyeSize, eyeSize); // right eye
strokeWeight(3);
noFill(); // No fill for the mouth, just an outline
// the mouth expression based on the dice roll
if (diceValue <= 2) {
arc(0, mouthY, 40, 20, 180, 0); // Sad face (downward curve)
} else if (diceValue <= 4) {
line(-15, mouthY, 15, mouthY); // Neutral face (straight mouth)
} else {
arc(0, mouthY, 40, 20, 0, 180); // Happy face (upward curve)
}
}