servlet实现猜拳游戏
时间: 2023-12-09 11:03:24 浏览: 133
好的,我可以给你一个简单的servlet实现猜拳游戏的示例代码,你可以参考下面的代码实现:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GuessServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Guess Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Guess Game</h1>");
out.println("<form method=\"post\">");
out.println("<p>Choose your hand:</p>");
out.println("<input type=\"radio\" name=\"hand\" value=\"rock\"> Rock<br>");
out.println("<input type=\"radio\" name=\"hand\" value=\"paper\"> Paper<br>");
out.println("<input type=\"radio\" name=\"hand\" value=\"scissors\"> Scissors<br>");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Guess Servlet</title>");
out.println("</head>");
out.println("<body>");
String hand = request.getParameter("hand");
String[] hands = { "rock", "paper", "scissors" };
int computerHand = (int) (Math.random() * 3);
String result = "";
if (hand.equals(hands[computerHand])) {
result = "Tie!";
} else if ((hand.equals(hands[0]) && computerHand == 1)
|| (hand.equals(hands[1]) && computerHand == 2)
|| (hand.equals(hands[2]) && computerHand == 0)) {
result = "You lose!";
} else {
result = "You win!";
}
out.println("<p>You chose " + hand + " and the computer chose " + hands[computerHand] + "</p>");
out.println("<p>" + result + "</p>");
out.println("<a href=\"guess\">Play Again</a>");
out.println("</body>");
out.println("</html>");
}
}
```
这个servlet实现了一个猜拳游戏,用户可以在网页上选择自己出的拳,然后与电脑对战,最终显示胜负结果。在doGet方法中,我们生成了一个表单,让用户选择自己出的拳;在doPost方法中,我们获取用户选择的拳,生成电脑出的拳,并计算出胜负结果,最终将结果显示在网页上。
阅读全文