首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript返回到代码顶部或重新启动它

Javascript返回到代码顶部或重新启动它
EN

Stack Overflow用户
提问于 2022-09-15 07:38:53
回答 3查看 106关注 0票数 0

嗨,我正在寻找一种方法重新启动我的代码或返回到它的顶部让它再次运行。有什么方法或代码我可以查找并在我的代码中进行整数吗??如您所见,我有一个if语句,其中有一个输入作为条件。如果在控制台中键入reset,我想重新启动我的代码。

代码语言:javascript
运行
复制
//wiederholung von buchstaben message
//when entry is wrong or repeated --> list previous wrong letters
//Win message 
//difficulty

const constants = require('./constants');
// In node.js: install a prompt library by running: `npm install prompt-sync` in the current folder
const prompt = require("prompt-sync")();

// Here you see an example how to get your
// constants from constants.js
/*for(let figure of constants.HANGMAN_PICS)
{
   console.log(figure);
}
*/
let answer = [];
let count = 0;
let usedLetters = [];

var word = constants.WORDS_TO_GUESS[Math.floor(Math.random()*constants.WORDS_TO_GUESS.length)];

for(let i=0; i < word.length; i++) {
   answer[i]="_";
}

console.log(answer.join(" "));

for(;answer!==word;) {

input = prompt (`Finde das Wort.`).toLocaleLowerCase();

if(word.toLocaleLowerCase().includes(input)) {
   for(let i=0; i < word.length; i++) {
   if (word[i].toLocaleLowerCase() === input) {
   console.clear();
   answer[i]=word[i];
   console.log("Good Job!");
   console.log(constants.HANGMAN_PICS[count]);
} 

}
}else if(!word.includes(input)){
   console.clear();
   console.log("Falsche Eingabe!");
   console.log("Hello");
   count++;
   console.log(constants.HANGMAN_PICS[count]); 
   if(usedLetters.includes(input)){
      console.log("Erneute Falscheingabe");
      console.log(usedLetters);
   }
 usedLetters.push(input);
}

if(input === "quit"){
   return;
}
else{

console.log(answer.join(" "));

}
}
// how to use the prompt - e.g.:
// const name = prompt('What is your name?');

EN

回答 3

Stack Overflow用户

发布于 2022-09-15 08:41:17

将执行游戏逻辑的代码包装在函数中。让我们给这个函数命名为game,这样我们就可以引用并调用它。

在我们调用函数之前,game内部的代码是不会运行的。这意味着告诉函数启动。要运行游戏,使用game()调用函数。函数内部的代码现在将从上到下运行。

函数能够调用自己,这意味着您可以从(函数本身的)中重新启动该函数。这叫做递归

在下面的片段中,游戏逻辑是在game函数中定义的。然后调用函数来启动逻辑。在游戏中,我们被要求重复游戏。如果true是来自confirm提示符的结果,那么将再次调用game,从顶部开始逻辑。

代码语言:javascript
运行
复制
function game() {
  const name = prompt('What is your name?');
  const repeat = confirm(`Hi ${name}, do you want to ask again?`);
  
  if (repeat === true) {
    game();
  }
}

game();

票数 1
EN

Stack Overflow用户

发布于 2022-09-30 15:55:36

做同样事情的另一种方法是:

代码语言:javascript
运行
复制
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Class Game</title>
</head>
<body>
    <script>
        class Game{
            constructor(gameName){
                this.name = gameName;
            }
            init(){
                alert("Lets play at " + this.name);
                const userName = prompt('What is your name?');
                if (userName.length == 0){
                    alert("please fill the name field");
                    this.init();
                };
                const repeat = confirm(`Hi ${userName}, do you want to ask again?`);
                if (repeat == true) {
                    this.init();
                }
            }
        }
        let myGame = new Game("Simple Game");
        myGame.init();
    </script>
</body>
</html>

每次你想重新开始游戏,打电话:myGame.init();

此代码更长,但您可能会清楚地了解它是如何工作的..。

代码语言:javascript
运行
复制
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Class Example</title>
</head>
<body>
    <div id="outputDiv" style="font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', 'DejaVu Sans', Verdana, 'sans-serif'; font-size: 18px; font-weight: bold">
        &nbsp;
    </div>
<script>
class SomeGame{
    constructor(name,targ){
        this.gameName = name; // The name of the game
        this.goal = targ; // The score You need to win
    }
        init(){
            this.score = 0;
            this.counter = 0;
            this.winMsg = false;
            document.getElementById("outputDiv").innerHTML = this.getResults();
            alert("We will play at " + this.gameName + " GET " + this.goal + " POINTS TO WIN!");
        }
        getScore(){
            return this.score;
        }
        getCounter(){
            return this.counter;
        }
        increaseScore(numb){
            this.score += numb;
        }
        increaseCounter(){
                this.counter += 1;
        }
        getResults(){
            let res = ("counter = " + this.getCounter() + ", score = " + this.getScore());
            return(res);
        }
        increaseValues(){
            if(this.score<this.goal){
                this.increaseScore(100);
                this.increaseCounter();
                document.getElementById("outputDiv").innerHTML = this.getResults();
            }
            if(this.score==this.goal && this.winMsg == false){
                alert("You win! You reached " + this.goal + " POINTS.");
                this.winMsg = true
            }
        }
    }
    let aGame = new SomeGame("Get 500", 500);
    aGame.init();
</script>   
<input type="button" name="button1" id="button1" value="Score++" onClick="aGame.increaseValues()">
<input type="button" name="button2" id="button2" value="Reset" onClick="aGame.init()">
</body>
</html>

诚挚的问候。尼古拉斯。

票数 0
EN

Stack Overflow用户

发布于 2022-09-30 18:24:45

您所描述的是goto语句。Javascript不支持它,而且在大多数支持Javascript的语言中,它也被认为是错误的做法,因为它导致了意大利面代码。

它被广泛地应用于像Fortran这样的语言中,因为除了循环之类的语言别无选择。

正如其他答案所描述的,您可以简单地将您想要在函数中重复的代码包装起来,并随时调用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73727282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档