javaweb猜拳代码
时间: 2023-10-14 17:06:35 浏览: 71
以下是一个简单的JavaWeb猜拳游戏实现的代码:
Java代码(JSP页面):
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>猜拳游戏</title>
</head>
<body>
<h2>猜拳游戏</h2>
<form action="play.jsp" method="post">
<input type="radio" name="player" value="1" checked> 石头
<input type="radio" name="player" value="2"> 剪刀
<input type="radio" name="player" value="3"> 布
<br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
```
Java代码(play.jsp页面):
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>猜拳游戏</title>
</head>
<body>
<%
int player = Integer.parseInt(request.getParameter("player")); // 获取用户选择
int computer = (int) (Math.random() * 3) + 1; // 电脑随机出拳
int result = (player - computer + 3) % 3; // 计算胜负
%>
<h2>猜拳游戏</h2>
<p>你出拳:
<%
switch (player) {
case 1:
out.print("石头");
break;
case 2:
out.print("剪刀");
break;
case 3:
out.print("布");
break;
}
%>
</p>
<p>电脑出拳:
<%
switch (computer) {
case 1:
out.print("石头");
break;
case 2:
out.print("剪刀");
break;
case 3:
out.print("布");
break;
}
%>
</p>
<p>
<%
switch (result) {
case 0:
out.print("平局!");
break;
case 1:
out.print("你赢了!");
break;
case 2:
out.print("你输了!");
break;
}
%>
</p>
</body>
</html>
```
此代码实现了一个简单的猜拳游戏,用户可以在页面上选择石头、剪刀、布中的一种,点击“提交”按钮后,对应的Java代码会生成一个随机数作为电脑出拳,然后计算出胜负并在页面上展示出来。
阅读全文