如何解决在Java语言游戏的条件中,使用全局变量多次评估Switch语句的最佳方法?
我正在尝试制作《吃豆人》,我正在弄清楚程序的最后一部分,该程序根据游戏的当前级别激活不同的幻影模式。
因此,目前,我将score和current_level作为全局变量。 我有一个名为scoreToLevel的函数,该函数根据Pacman当前的分数来确定您所处的级别。 一个达到特定分数时转到下一轮的功能增量级别。
我想创建一个名为moveGhost的函数,该函数确定达到一定级别/分数时幽灵所处的模式(随机,分散或追逐)。
我面临的挑战是想出一种方法来迭代切换案例,因为切换案例仅评估一次。切换案例检查我们处于什么级别才能激活指定模式。这些模式在各自的回合结束后会自动停用,因此不必担心。
代码如下:
//Global Variables
let score = 0;
let current_level = 1;
//Ghost Move Function ***NEED HELP HERE***
function moveGhost(graph,ghost){
let timerId = setInterval(function(){
current_level = incrementLevel(current_level,score);
switch(current_level){
case 1: // score < 20 is round 1
activateGhostRandomMode(ghost,20); //score >= 20,then random mode stops
break;
case 2: // score < 40 is round 2
activateGhostScatterMode(graph,ghost,40); //score >= 40,then scatter mode stops
break;
case 3: // score < 80 is round 3
activateGhostChaseMode(graph,80); //score >= 80,then chase mode stops
break;
case 4: //score < 120 is round 4
activateGhostScatterMode(graph,120); //score >= 120,then scatter mode stops
break;
default: //stay in chase mode until player wins the game at score = 1000
clearInterval(timerId);
activateGhostChaseMode(graph,1000); //score >= 1000,then chase mode stops
break;
}
},5000);
}
//For your reference
function scoreToLevel(playerScore){
if(playerScore < 20){
return 1;
}else if (playerScore < 40){
return 2;
}else if(playerScore < 80){
return 3;
}else if(playerScore < 120){
return 4;
}else{
return 5;
}
}
function incrementLevel(current_level,playerScore){
let next_level = scoreToLevel(playerScore);
if(next_level !== current_level){
current_level = next_level;
current_level = parseInt(current_level);
return current_level;
}else{
current_level = parseInt(current_level);
return current_level;
}
}
当前,moveGhost函数中的setInterval有助于迭代模式。问题是,如果pacman移动太慢或根本不移动,或者计时器设置得太快,则setInterval将一遍又一遍地激活模式,由于这些模式自身多次重叠或与其他模式重叠时会引起疯狂的故障。因为它依赖于在“模式”功能中要达到的分数来停用鬼的随机,分散或追逐状态。
如果有人可以使用代码想出解决方案,那么每次分数变化(再次使用全局变量)时,我都必须遍历每个条件以查看幽灵应处于的状态,这将大有帮助!是否有与setInterval不同的函数可以解决问题?也许保持setInterval,但是有一种方法可以暂停,然后在达到新级别时恢复。谢谢!我被这最后一块困了好几天了!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。