使用jsp实现猜拳游戏
时间: 2024-04-30 10:17:47 浏览: 47
猜拳游戏JSP
好的,下面是实现猜拳游戏的jsp代码:
```jsp
<html>
<head>
<title>猜拳游戏</title>
</head>
<body>
<h1>猜拳游戏</h1>
<%
String guess = request.getParameter("guess");
int computer = (int)(Math.random()*3);
String result = "";
if(guess != null){
int player = Integer.parseInt(guess);
if(player == computer){
result = "平局";
}else if((player == 0 && computer == 1) || (player == 1 && computer == 2) || (player == 2 && computer == 0)){
result = "你输了";
}else{
result = "你赢了";
}
}
%>
<form method="post">
<input type="radio" name="guess" value="0" <% if(guess != null && guess.equals("0")) out.print("checked"); %>>石头
<input type="radio" name="guess" value="1" <% if(guess != null && guess.equals("1")) out.print("checked"); %>>剪刀
<input type="radio" name="guess" value="2" <% if(guess != null && guess.equals("2")) out.print("checked"); %>>布
<br>
<input type="submit" value="提交">
</form>
<br>
<%
if(result.length() > 0){
out.print("你出了" + (guess.equals("0") ? "石头" : guess.equals("1") ? "剪刀" : "布") + ",电脑出了" + (computer == 0 ? "石头" : computer == 1 ? "剪刀" : "布") + "," + result);
}
%>
</body>
</html>
```
这段代码实现了一个简单的猜拳游戏,用户可以选择石头、剪刀或布,然后与电脑进行比较,输出胜负结果。其中,使用了随机数来模拟电脑的出拳,使用了if语句来判断胜负关系。同时,为了防止用户没有选择就提交表单,使用了if语句进行判断。
阅读全文