我正在尝试在p5.js中实现Sudoku表,我能够实现一个单元格,在其中可以写下数字(1-9)。但是我无法删除数字,即如果我先在一个单元格上写“ 1”并写上“ 2”,那么它就写在它的顶部。
那么,如何删除现有号码并写一个不同的号码?
编辑:
到目前为止,我的代码:
//make a grid
function makegrid(rows, cols) {
var regrid = new Array(rows);
for (var i = 0; i < rows; i++) {
regrid[i] = new Array(cols);
}
return regrid;
}
var numrec = [];
var rows = 9;
var grid = [];
var cols = 9;
var w = 50;
var input;
//show the boxes
function show(i, j) {
this.i = i;
this.j = j;
var x = w * this.i;
var y = w * this.j;
noFill();
//input = createInput();
//input.position(x+5,y+5,w);
strokeWeight(1);
rect(x + 5, y + 5, w, w); //just to see line clearly
}
//there must be a better way to do it but for now ---> here we go for separation
// of tables
function boldlines() {
strokeWeight(4);
stroke(51);
line(5, 5, 5, w * 9 + 5);
line(w * 3 + 5, 5, w * 3 + 5, w * 9 + 5);
line(w * 6 + 5, 5, w * 6 + 5, w * 9 + 5);
line(5, w * 9 + 5, w * 9 + 5, w * 9 + 5);
line(5, 5, w * 9 + 5, 5);
line(w * 9 + 5, 5, w * 9 + 5, w * 9 + 5);
line(5, w * 3 + 5, w * 9 + 5, w * 3 + 5);
line(5, w * 6 + 5, w * 9 + 5, w * 6 + 5);
}
function setup() {
createCanvas(600, 600);
grid = makegrid(rows, cols);
numrec = makegrid(rows, cols);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
numrec[i][j] = 1;
}
}
}
function draw() {
boldlines();
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
show(i, j);
//console.log(mouseX,mouseY);
}
}
}
function numput(x, y, num) {
//background(0);
if (num === 0) {
num = "";
}
textSize(30);
//textAlign(CENTER);
text(num, x + 30, y + 40);
}
function mousePressed() {
var mx = mouseX;
var my = mouseY;
var i = floor((mx + 5) / w);
var j = floor((my + 5) / w);
if (i >= 0 && j >= 0 && i < rows && j < cols) {
//console.log(i, j);
var num = numrec[i][j];
if (num === 10) {
num = 0;
}
numrec[i][j] = num + 1;
numput(i * w, j * w, num);
}
}
答案 0 :(得分:1)
我想出了一种方法,可以在该单元格中隐藏旧数字并保留所有其他单元格的内容。我通过在其顶部绘制一个矩形并使其具有与单元格相同的尺寸来隐藏前一个数字,然后用新数字更新该单元格。
function numput(x, y, num) {
//background(0);
if (num === 0) {
num = "";
}
textSize(30);
//textAlign(CENTER);
//Newly added
strokeWeight(0);
fill(255,255,255);
rect(x+4 , y+4 , w, w);
boldlines();
text(num, x + 30, y + 40);
}
我在function numput()
中做了一些更改以实现它。