xxxxxxxxxx
133
let matrix = [];
let probabilities = {};
let inp = '';
let out = '';
let cellSize = 22;
function preload() {
matrix = loadStrings('xuanjitu.txt');
}
function setup() {
createCanvas(638, 638);
textAlign(CENTER, CENTER);
textSize(20);
// Convert rows to individual character arrays
matrix = matrix.map(row => row.trim().split(''));
// Calculate neighbor probabilities
probabilities = tally(matrix);
}
function draw() {
background(230, 230, 250);
// Input and output
if (inp !== '') {
drawMatrix();
fill(0);
textSize(30);
text(`Laid 伏: ${inp}`, width / 2, height / 2);
text(`Rise 起: ${out}`, width / 2, height / 2 + 35);
} else {
text('抚', width / 2, height / 2);
text('Lay down your digits (click anywhere)', width / 2, height / 2 + 35);
}
}
function drawMatrix() {
fill(200);
textSize(20);
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
let x = col * cellSize;
let y = row * cellSize;
text(matrix[row][col], x + cellSize / 2, y + cellSize / 2);
}
}
}
// Function to handle mouse clicks and map them to the matrix
function mousePressed() {
let row = Math.floor(mouseY / cellSize);
let col = Math.floor(mouseX / cellSize);
if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[0].length) {
inp = matrix[row][col];
out = generate(inp, probabilities);
}
}
function getNeighbors(matrix, row, col) {
let neighbors = [];
let directions = [
[-1, -1], [-1, 0], [-1, 1],
[0, -1], [0, 1],
[1, -1], [1, 0], [1, 1]
];
for (let [dr, dc] of directions) {
let newRow = row + dr;
let newCol = col + dc;
if (newRow >= 0 && newRow < matrix.length && newCol >= 0 && newCol < matrix[0].length) {
neighbors.push(matrix[newRow][newCol]);
}
}
return neighbors;
}
function tally(matrix) {
let charCounts = {};
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
let char = matrix[row][col];
if (!charCounts[char]) {
charCounts[char] = {};
}
let neighbors = getNeighbors(matrix, row, col);
for (let neighbor of neighbors) {
if (!charCounts[char][neighbor]) {
charCounts[char][neighbor] = 0;
}
charCounts[char][neighbor] += 1;
}
}
}
// Convert counts to probabilities
let probabilities = {};
for (let char in charCounts) {
let totalNeighbors = 0;
for (let neighbor in charCounts[char]) {
totalNeighbors += charCounts[char][neighbor];
}
probabilities[char] = {};
for (let neighbor in charCounts[char]) {
probabilities[char][neighbor] = charCounts[char][neighbor] / totalNeighbors;
}
}
return probabilities;
}
// Find the most likely neighbor
function generate(char, probabilities) {
let surrounding_probs = probabilities[char];
if (!surrounding_probs) {
return '';
}
let maxProb = Math.max(Object.values(surrounding_probs));
let mostLikelyChars = Object.keys(surrounding_probs).filter(
neighbor => surrounding_probs[neighbor] === maxProb
);
return random(mostLikelyChars);
}