因此,我正在尝试创建此“剪刀石头布”程序以在telnet服务器上运行。除了不允许我输入单词“ Rock”,“ Paper”或“ Scissors”。


第一个CPUhand显示为未定义,并且未设置为if语句中的选项之一。
其次,每当我在命令提示符下输入单个字符时,它就会提示我“无效,请重试!” else语句并跳至下一行。


有谁能弄清楚为什么我的CPUhand的if语句不起作用,或者为什么我不能在命令提示符下输入多个字符?

Screenshot1 Screenshot2



"use strict";
const
  net = require('net'),
  server = net.createServer(function(connection) { //create server

      let randomNum = randomNumber(1, 3);
      let CPUhand

      if(randomNum == 1){
          CPUhand == "Rock";
      } else if(randomNum == 2){
          CPUhand == "Paper";
      } else if(randomNum == 3){
          CPUhand == "Scissors";
      }

	connection.write("Enter: Rock, Paper, or Scissors!\r\n");

	connection.on('data', function(chunk) { //collect data from user

		let USERhand = chunk.toString();

		if(CPUhand === "Rock" && USERhand === "Scissors" || USERhand === "Rock" && CPUhand === "Scissors"){
			connection.write("Rock beats Scissors!\r\n");
		}
		else if(CPUhand === "Paper" && USERhand === "Rock" || USERhand === "Paper" && CPUhand === "Rock"){
			connection.write("Paper beats Rock!\r\n");
		}
		else if(CPUhand === "Scissors" && USERhand === "Paper" || USERhand === "Scissors" && CPUhand === "Paper"){
			connection.write("Scissors beats Paper!\r\n");
		}
        else if(CPUhand === USERhand){
            connection.write("Draw!\r\n");
        }
		else{
			connection.write("Invalid! Try Again! \r\n");
		}

	});

}); server.listen(5432); //bind port

    function randomNumber(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

最佳答案

1)拼写错误:

if(randomNum == 1){ CPUhand == "Rock";} else ...

应该:

if(randomNum == 1){ CPUhand = "Rock";} else ...

2)在用户输入中,您还具有换行符:

let USERhand = chunk.toString();

用。。。来代替:

let USERhand = chunk.toString().trim();

10-06 15:18