2017-02-25 64 views
1

所以我試圖創建這個Rock,Paper,Scissors程序在telnet服務器上運行。除了它不允許我輸入「Rock」,「Paper」或「Scissors」這些詞。Node.js:telnet「Rock,Paper,Scissors」程序不能正常工作

  1. 第一個CPUhand顯示爲未定義,並未設置爲我if語句中的某個選項。
  2. 第二次,每當我在命令提示符中輸入單個字符,它會給我我的「無效,再試一次!」 else語句並跳到下一行。

是否有人能夠找出爲什麼我的if語句爲什麼CPUhand不工作或爲什麼我不能在命令提示符下輸入多個單個字符?在塊

Screenshot1Screenshot2

"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"; 
 
     } 
 
    
 
\t connection.write("Enter: Rock, Paper, or Scissors!\r\n"); 
 
     
 
\t connection.on('data', function(chunk) { //collect data from user 
 
\t \t 
 
\t \t let USERhand = chunk.toString(); 
 
\t \t 
 
\t \t if(CPUhand === "Rock" && USERhand === "Scissors" || USERhand === "Rock" && CPUhand === "Scissors"){ 
 
\t \t \t connection.write("Rock beats Scissors!\r\n"); 
 
\t \t } 
 
\t \t else if(CPUhand === "Paper" && USERhand === "Rock" || USERhand === "Paper" && CPUhand === "Rock"){ 
 
\t \t \t connection.write("Paper beats Rock!\r\n"); 
 
\t \t } 
 
\t \t else if(CPUhand === "Scissors" && USERhand === "Paper" || USERhand === "Scissors" && CPUhand === "Paper"){ 
 
\t \t \t connection.write("Scissors beats Paper!\r\n"); 
 
\t \t } 
 
     else if(CPUhand === USERhand){ 
 
      connection.write("Draw!\r\n"); 
 
     } 
 
\t \t else{ 
 
\t \t \t connection.write("Invalid! Try Again! \r\n"); 
 
\t \t } \t \t 
 
\t \t 
 
\t }); 
 

 
}); 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; 
 
    }

+4

'。對( '數據')'被觸發每當程序接收任何數據,並且當您輸入內容時,通常是一次一個字符。您必須將數據收集到變量,直到它收到換行符。另一個問題是因爲你試圖用'=='而不是'='分配值。 – JJJ

回答

-1

1)錯字:

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

應該是:

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

2)在用戶輸入你有也換行符符號:

let USERhand = chunk.toString();

替換:

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