xxxxxxxxxx
128
const gridSize = 5;
let n;
let loopMax = 200;
let grid = [];
let T_slider, loopMax_slider;
let T_label, loopMax_label;
let resetButton;
function setup() {
createCanvas(400, 400);
n = width/gridSize;
// Initialize the grid
initGrid();
for (let i = 0; i*gridSize <= width; i ++){
grid[i] = [];
for (let j = 0; j*gridSize <= height; j ++){
grid[i][j] = random() < 0.5 ? -1 : 1;
}
}
// Create Temperature Slider and Label
T_label = createElement('label', 'Temp: ');
T_label.position(10, height + 10);
T_label.style('color', 'yellow');
T_slider = createSlider(0, 10, 2.2, 0.01);
T_slider.position(100, height + 10);
// Create LoopMax Slider and Label
loopMax_label = createElement('label', 'Loops: ');
loopMax_label.position(10, height + 40);
loopMax_label.style('color', 'yellow');
loopMax_slider = createSlider(1, 1000, 300, 1);
loopMax_slider.position(100, height + 40);
// Create Reset Button
resetButton = createButton('Reset Grid');
resetButton.position(10, height + 70);
resetButton.mousePressed(initGrid);
}
function draw() {
T = round(T_slider.value(),2);
loopMax = loopMax_slider.value();
T_label.html('Temp: ' + nf(T, 1, 2));
loopMax_label.html('Loops: ' + nf(loopMax, 1, 2));
background(220);
// noLoop();
//simulation function
for(let loop = 0; loop <= loopMax; loop++){
simulate(grid,T);
}
// add a function to display grid
displayGrid(grid);
}
function initGrid() {
for (let i = 0; i < n; i++) {
grid[i] = [];
for (let j = 0; j < n; j++) {
grid[i][j] = random() < 0.5 ? -1 : 1;
}
}
}
function simulate(grid,T){
// now we pick a random cell
let i = int(random(0,n));
let j = int(random(0,n));
// calculate the change
let dH = deltaH(i,j,grid);
//check if we should accept
if(dH <= 0 || (Math.random() < Math.exp(-dH/T))){
grid[i][j] *= -1;
}
}
function deltaH(i, j, grid) {
let leftS = grid[i === 0 ? n - 1 : i - 1][j];
let rightS = grid[i === n - 1 ? 0 : i + 1][j];
let topS = grid[i][j === 0 ? n - 1 : j - 1];
let bottomS = grid[i][j === n - 1 ? 0 : j + 1];
return 2.0 * grid[i][j] * (leftS + rightS + topS + bottomS);
}
function displayGrid(grid){
for (let i = 0; i*gridSize <= width; i ++){
for (let j = 0; j*gridSize <= height; j ++){
//stroke(0,0,0);
noStroke();
if(grid[i][j] < 0){
fill(255,0,0);
}else{
fill(0,0,255);
}
rect(i*gridSize,j*gridSize,gridSize,gridSize);
}
}
}