我有一个我试图完成的俄罗斯方块游戏但是在游戏结束后保存高分导致了一些问题。当游戏结束时,如果得分高于之前保存为高分的得分,则应该将该新得分保存为本地高分并显示新的高分。我无法弄清楚为什么没有发生这种情况。以下是我的代码中与高分相关的三个不同区域。任何帮助,将不胜感激。
在游戏侧面创建菜单
<div id="tetris">
<div id="menu">
<p id="start"><a href="javascript:play();">Press Space to Play.</a></p>
<p><canvas id="upcoming"></canvas></p>
<p>score <span id="score">00000</span></p>
<p>rows <span id="rows">0</span></p>
<p>high score <span id="highscore">0</span></p>
</div>
<canvas id="canvas">
Sorry, this example cannot be run because your browser does not support the <canvas> element
</canvas>
在游戏结束时设置高分
var highscore = localStorage.getItem("highscore");
if (playing == false){
if(highscore !==null){
if(vscore > highscore) {
localStorage.setItem("highscore", vscore);
}
}
else{
localStorage.setItem("highscore", vscore);
}
}
else{
null;
}
更新分数以显示它们
function play() { hide('start'); reset(); playing = true; }
function lose() { show('start'); setVisualScore(); playing = false; }
function setVisualScore(n) { vscore = n || score; invalidateScore(); }
function setScore(n) { score = n; setVisualScore(n); }
function addScore(n) { score = score + n; }
function clearScore() { setScore(0); }
function clearRows() { setRows(0); }
function setRows(n) { rows = n; step = Math.max(speed.min, speed.start - (speed.decrement*rows)); invalidateRows(); }
function addRows(n) { setRows(rows + n); }
function setHighScore(n) { highscore = n; }
function addHighScore(n) { setHighScore(highscore); }
function getBlock(x,y) { return (blocks && blocks[x] ? blocks[x][y] : null); }
function setBlock(x,y,type) { blocks[x] = blocks[x] || []; blocks[x][y] = type; invalidate(); }
function clearBlocks() { blocks = []; invalidate(); }
function clearActions() { actions = []; }
function setCurrentPiece(piece) { current = piece || randomPiece(); invalidate(); }
function setNextPiece(piece) { next = piece || randomPiece(); invalidateNext(); }
function reset() {
dt = 0;
clearActions();
clearBlocks();
clearRows();
clearScore();
setCurrentPiece(next);
setNextPiece();
}
function update(idt) {
if (playing) {
if (vscore < score)
setVisualScore(vscore + 1);
handle(actions.shift());
dt = dt + idt;
if (dt > step) {
dt = dt - step;
drop();
}
}
}
如果需要,我可以添加完整的游戏代码,但这些是与高分问题直接相关的三个方面。
答案 0 :(得分:0)
尝试以下方法:
function update(idt) {
if (playing) {
if (vscore < score)
setVisualScore(vscore + 1);
handle(actions.shift());
dt = dt + idt;
if (dt > step) {
dt = dt - step;
drop();
}
// Add the following to update the highscore while playing.
if (score > highscore) {
setHighScore(score);
}
}
}
setHighScore = (score) => {
// update highscore
highscore = score;
// update it visually?
document.getElementById('highscore').text = highscore;
}
然后在某个地方你想要在比赛结束后进行检查 - 我立即假设你将播放布尔值设置为假。
if (playing === false){
if(vscore > highscore) {
// For future games.
localStorage.setItem("highscore", vscore);
}
}
编辑: 我在手机上输入此内容,如果格式不稳定,请道歉。 请参阅示例:https://codepen.io/anon/pen/pVEJJW