//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>
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)
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){
return 0
}else{
if((playerAction=='rock'&&computerAcition=='scissor')||(playerAction=='scissor'&&computerAcition=='papper'||(playerAction=='papper'&&computerAcition=='rock'))){
return -1
}else{
return 1
}
}
}