JavaScript之猜拳游戏
// 猜拳游戏
// 清屏函数
let clear = () => process.stdout.write(process.platform === 'win32' ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H');
let readline = require("readline-sync");
let player = {
name : "玩家", // 默认玩家名
victory : 0 // 玩家胜利局数
};
let com = {
name : "电脑",
victory : 0 // 电脑胜利局数
}
// 胜负判断函数 接收两个参数 玩家猜拳数字 电脑猜拳数字
let judge = function(i,j){
// 返回数字 0 1 2,0代表平局 1代表玩家获胜 2代表电脑获胜
let result = j - i;
if(result === 0)
{
return 0;
}
else if(result > 0)
{
if(i === 1 && j === 3)
{
return 2;
}
else{
return 1;
}
}
else{
if(i === 3 && j === 1)
{
return 1;
}
else{
return 2;
}
}
}
// 描述函数 根据传递过来的数字返回对应的文字
let desc = function(i){
let str = "";
switch(i)
{
case 1:str = "石头";return str;
case 2:str = "剪刀";return str;
case 3:str = "布";return str;
}
}
let main = function(){
clear();
console.log("请输入您的玩家名:");
let playerName = readline.question("");
player.name = playerName;
let useSys = true;
while(useSys)
{
clear();
console.log("欢迎来到猜拳游戏,",player.name);
console.log("请选择游戏选项: 1.开始游戏 2.游戏说明 3.退出游戏");
let funcSelect = readline.question("");
switch(funcSelect)
{
// 开始游戏
case "1":
let playNow = true; // 设置游戏状态为true
while(playNow)
{
clear();
console.log("请选择你要出的拳: 1.石头 2.剪刀 3.布 4.返回");
let playerChoose = parseInt(readline.question(""));
switch(playerChoose)
{
case 1:
case 2:
case 3:
{
// 电脑随机出拳 返回1-3的随机数 1.石头 2.剪刀 3.布
let computChoose = Math.floor(Math.random()*3 + 1);
let result = judge(playerChoose,computChoose);
// 根据返回结果来输出不同内容
switch(result)
{
// 平局
case 0:
console.log("你出的是:",desc(playerChoose));
console.log("电脑出的是:",desc(computChoose));
console.log("本轮平局,不记分");
console.log(player.name + ":" + player.victory + " vs " + com.name + ":" + com.victory);
console.log("按回车键继续");
readline.question("");
break;
// 玩家获胜
case 1:
console.log("你出的是:",desc(playerChoose));
console.log("电脑出的是:",desc(computChoose));
console.log("玩家胜利!");
player.victory++;
console.log(player.name + ":" + player.victory + " vs " + com.name + ":" + com.victory);
console.log("按回车键继续");
readline.question("");
break;
// 电脑获胜
case 2:
console.log("你出的是:",desc(playerChoose));
console.log("电脑出的是:",desc(computChoose));
console.log("电脑胜利!");
com.victory++;
console.log(player.name + ":" + player.victory + " vs " + com.name + ":" + com.victory);
console.log("按回车键继续");
readline.question("");
break;
}
}
break;
case 4:
playNow = false; // 返回上级菜单 只需要将 playNow需改为false
break;
default:
console.log("输入有误,请重新输入,按回车键继续");
readline.question("");
}
}
break;
// 游戏说明
case "2":
clear();
console.log("就和平时我们玩的猜拳游戏一样");
console.log("玩家选择是出石头,剪刀,还是布,然后和电脑出的拳进行比较");
console.log("比较规则如下:");
console.log("石头克剪刀 剪刀克布 布克石头");
console.log("按回车键返回");
readline.question("");
break;
// 退出游戏
case "3":
useSys = false;
break;
default:
console.log("输入有误,请重新输入,按回车键继续");
readline.question("");
}
}
clear();
console.log("最终比分为:");
console.log(player.name + ":" + player.victory + " vs " + com.name + ":" + com.victory);
console.log("Thank you for playing,",player.name);
}
main();