총 2개의 JSP 파일을 생성하시면 됩니다.
index.jsp play.jsp
먼저 index.jsp 파일에 입력 합니다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>가위 바위 보 게임</title>
</head>
<body>
<h2>가위 바위 보 게임</h2>
<form method="post" action="play.jsp">
<input type="radio" name="playerChoice" value="rock" checked>바위
<input type="radio" name="playerChoice" value="paper">보
<input type="radio" name="playerChoice" value="scissors">가위
<input type="submit" value="결과 확인">
</form>
</body>
</html>
그다음 play.jsp 파일에 아래와 같이 입력합니다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Random" %>
<%
String[] choices = {"rock", "paper", "scissors"};
Random rand = new Random();
int computerIndex = rand.nextInt(choices.length);
String computerChoice = choices[computerIndex];
String playerChoice = request.getParameter("playerChoice");
String resultMessage = "";
if (playerChoice.equals(computerChoice)) {
resultMessage = "비겼습니다.";
} else if (playerChoice.equals("rock") && computerChoice.equals("scissors")
|| playerChoice.equals("paper") && computerChoice.equals("rock")
|| playerChoice.equals("scissors") && computerChoice.equals("paper")) {
resultMessage = "당신이 이겼습니다!";
} else {
resultMessage = "컴퓨터가 이겼습니다.";
}
%>
<!DOCTYPE html>
<html>
<head>
<title>가위 바위 보 게임 결과</title>
</head>
<body>
<h2>가위 바위 보 게임 결과</h2>
<p>당신의 선택: <%=playerChoice%></p>
<p>컴퓨터의 선택: <%=computerChoice%></p>
<p><%=resultMessage%></p>
<a href="index.jsp">다시 하기</a>
</body>
</html>
이렇게 입력하신 후, 이클립스에서 프로젝트 실행을 해줍니다.
아래와 같이 톰캣을 지정해 준 다음 완료 누르시면 웹 브라우저에서 실행됩니다
이런 식으로 가위 바위 보 중에 골라서 결과 확인 누르면
우측과 같이 랜덤으로 뜹니다!
다시 하기 누르시면 다시 좌측 화면으로 돌아갑니다.
감사합니다.