我一直在尝试制作自己版本的扫雷程序,但出于某种原因,控制台和画布总是每隔500毫秒左右就会清理一次。这可能只是我的电脑有问题,但我已经尝试过重启和切换浏览器(Chrome,MS Edge)。有谁可以帮我?
代码:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var tileCount;
var mineCount;
var tileSize = canvas.width / tileCount;
var tiles = [];
function draw() {
for (var i = 0; i < tileCount; i++) {
for (var j = 0; j < tileCount; j++) {
if (tiles[i][j].mine == true) {
ctx.beginPath();
ctx.fillText("M", i * 400 / tileCount, j * 400 / tileCount, 20);
//"M" is for "mine"
}
}
}
}
function init(tilecount, minecount) {
console.log(tilecount);
tileCount = tilecount;
mineCount = minecount;
for (var i = 0; i < tileCount; i++) {
tiles[i] = [];
for (var j = 0; j < tileCount; j++) {
tiles[i][j] = {
covered: true,
flagged: false,
numb: undefined,
mine: false
}
}
}
var temp = mineCount,
x, y;
while (temp > 0) {
x = Math.round(Math.random() * (tileCount - 1));
y = Math.round(Math.random() * (tileCount - 1));
if (tiles[x][y].mine == false) {
tiles[x][y].mine = true;
temp--;
}
}
//delete temp, x, y;
update();
}
function update() {
draw();
}body {
background-color: lightgrey;
}
canvas {
background-color: lightgrey;
border-style: solid;
}
h1 {
text-align: center;
}
* {
font-family: verdana;
}<!DOCTYPE html>
<html>
<head>
<title>MINESWEEPER</title>
</head>
<body>
<h1>MINESWEEPER</h1>
<br>
<form>
Tiles:<input type="text" name="tc" value="10"> Mines:
<input type="text" name="mc" value="40">
<button onclick="init(this.form.tc.value,
this.form.mc.value)">submit</button>
</form>
<br>
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>
Stackoverflow不让我发布它,因为它“主要是代码”,我想我必须找到一种方法来绕过他们的规则._。
发布于 2018-12-12 01:39:01
如果我没理解错的话,那是因为当你点击按钮时,表单一直在提交。
解决此问题的一种方法是将事件传递给函数,然后使用preventDefault阻止表单提交:
HTML
<button onclick="init(event, this.form.tc.value, this.form.mc.value)">submit</button>JS
function init(event, tilecount, minecount) {
event.preventDefault();
//
}或者,为了符合最佳实践,删除内联JS并将侦听器添加到JS代码中的按钮:
HTML
提交
JS
// Cache the form and button elements, and
// add a click listener to the button
var form = document.querySelector('form');
var button = document.querySelector('button');
button.addEventListener('click', init, false);
function init(e) {
// Still preventDefault...
e.preventDefault();
// ...but assign the values from the cached form instead
var tilecount = form.tc.value;
var minecount = form.mc.value;
//
}https://stackoverflow.com/questions/53729233
复制相似问题