简单http请求实现石头剪刀布

这是一个使用HTML、CSS和JavaScript实现的网页版石头剪刀布游戏。用户点击石头、剪刀或布的按钮,服务器通过Node.js接收请求并返回游戏结果。服务器端通过随机数决定电脑出拳,并判断胜负。游戏进行三次后,服务器会返回'告辞'结束游戏。
摘要由CSDN通过智能技术生成
//index.htnl
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
 
 <div id="output" style="height: 400px;width: 600px; overflow: auto; background: #eee;"></div>
  <div style="display: flex;">
    <div id="rock" style="height: 40px;width: 80px">石头</div>
    <div id="scissor" style="height: 40px;width: 80px">剪刀</div>
    <div id="paper" style="height: 40px;width: 80px"></div>
  </div>

</body>
</html>
<script>
  const $button={
    rock:document.getElementById('rock'),
    scissor:document.getElementById('scissor'),
    paper:document.getElementById('paper')
  }
  const $output=document.getElementById('output')
  Object.keys($button).forEach(key=>[
    $button[key].addEventListener('click',function(){
      fetch(`http://${location.host}/game?action=${key}`)
        .then((res)=>{
          return res.text()
        })
        .then((res)=>{
          $output.innerHTML+=res+'<br/>'
        })
    })
  ])
</script>
//index.js
const http=require('http')
const url=require('url')
const queryString=require('querystring')
const fs=require('fs')
const game=require('../commonjs/lib')
let count=0
http.createServer((req,res)=>{
  const pathUrl=url.parse(req.url)
  if(pathUrl.pathname=='/'){
  //服务端渲染页面
    fs.createReadStream(__dirname+'/index.html').pipe(res)
  }
  if(pathUrl.pathname=='/game'){
    const query=queryString.parse(pathUrl.query)
    const playAction=query.action
    const gameResult=game(playAction)
    if(count>=3){
      res.writeHead(500)
      res.end('告辞')
      return 
    }
    if(gameResult==0){
      res.end('平局')
    }else if(gameResult==-1){
      ++count
      res.end('你赢了')
    }else{
      res.end('你输了')
    }
    res.writeHead(200)
  }
}).listen(3000)
//lib.js
module.exports=function(playerAction){
  let computerAcition//电脑出的手势
  var random=Math.random()*3
  if(random<1){
    computerAcition='rock'
  }else if(random>2){
    computerAcition='scissor'
  }else{
    computerAcition='paper'
  }
  
  console.log(computerAcition);
  if(playerAction==computerAcition){
    // console.log('平局');
    return 0
  }else{
    if((playerAction=='rock'&&computerAcition=='scissor')||(playerAction=='scissor'&&computerAcition=='papper'||(playerAction=='papper'&&computerAcition=='rock'))){
      // console.log('你赢了');
      return -1
    }else{
      // console.log('你输了');
      return 1
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值