黄金点游戏开发(三)
程序员文章站
2022-07-13 17:35:54
...
第12周博客
项目设计
项目介绍
游戏规则:N个同学(N通常大于10),每人写一个0~100之间的有理数(不包括0或100),交给裁判,裁判算出所有数字的平均值,然后乘以0.618 (所谓黄金分割数),得到G值。提交的数字最靠近G(取绝对值)的同学得到N分,离G最远的同学得到-2分,其他同学得
分。
项目需求
(1)采用联网方式实现,需要为用户提供便利的输入界面。
(2)该游戏每次至少可以运行10轮以上,并能够保留各轮比赛结果。
(3)做成简单的 browser/server,用户从网页/手机上输入数字,并算出获胜者。
思路设计流程图
具体实现
登陆验证代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.sql.*,java.io.*"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date" %>
<html>
<head>
<meta charset="utf-8">
<title>正在登陆</title>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");//客户端网页我们控制为UTF-8
String userId = request.getParameter("user_id") ;
String userPassword = request.getParameter("user_password") ;
String user_id=userId;
// 定义变量,如果用户是合法用户,则将此标记变为true
boolean flag = false ;
%>
<%
ResultSet rs= null ;
PreparedStatement pstmt = null ;
request.setCharacterEncoding("UTF-8");
//out.println("页面传递过来的数据获取完毕");
System.out.println("页面传递过来的数据获取完毕");
System.out.println("userId="+userId+",userPassword="+userPassword);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
}
System.out.println("加载了JDBC驱动");
//然后链接数据库,开始操作数据表
try {
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=DataUser&password=DYL123&useUnicode=true&characterEncoding=UTF-8");
System.out.println("准备statement。");
String sql="select * from user_goldenpoint where user_id = ? and user_password = ?" ;//查询语句
System.out.println("即将执行的SQL语句是:"+sql);
pstmt = conn.prepareStatement(sql) ;
System.out.println("here now!");
pstmt.setString(1,userId) ;
pstmt.setString(2,userPassword) ;
rs = pstmt.executeQuery() ;//形成结果集
System.out.println(pstmt.toString());
if(rs.next())
{
flag = true ;
}
rs.close();//关闭结果集
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
}
//捕获异常
catch(SQLException ee){
System.out.print(ee);
}
%>
<%
// 判断用户名及密码
if(flag)
{
// 合法用户
System.out.println("执行到这里了!");
%>
<script>
console.log(sessionStorage.getItem("login_flag"))
sessionStorage.setItem("login_flag","1")
sessionStorage.setItem("user_id","<%=user_id%>")
window.location.href="../../room.jsp"
</script>
<%
}
else
{
// 非法用户
%>
<script>
alert("用户名或密码错误,请重新输入")
window.location.href="login.jsp"
</script>
<%
}
%>
</body>
</html>
房间创建代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.sql.*,java.io.*"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date" %>
<html>
<head>
<meta charset="utf-8">
<title>创建房间</title>
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");//客户端网页我们控制为UTF-8
String room_number = request.getParameter("room_number") ;
String room_host = request.getParameter("room_host") ;
// 定义变量,如果用户是未注册用户,则将此标记变为false
boolean flag = true ;
%>
<%
ResultSet rs= null ;
PreparedStatement pstmt = null ;
request.setCharacterEncoding("UTF-8");
//out.println("页面传递过来的数据获取完毕");
System.out.println("页面传递过来的数据获取完毕");
System.out.println("room_number="+room_number);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
}
System.out.println("加载了JDBC驱动");
//然后链接数据库,开始操作数据表
try {
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=DataUser&password=DYL123&useUnicode=true&characterEncoding=UTF-8");
System.out.println("准备statement。");
String sql="select * from room_goldenpoint where room_number = ?" ;//查询语句
pstmt = conn.prepareStatement(sql) ;
System.out.println("here now!");
pstmt.setString(1,room_number) ;
rs = pstmt.executeQuery() ;//形成结果集
System.out.println(pstmt.toString());
if(rs.next())
{
flag = false ;
}
rs.close();//关闭结果集
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
}
//捕获异常
catch(SQLException ee){
System.out.print(ee);
}
%>
<%
// 判断标志
if(!flag )
{
// 房间号重复
System.out.println("房间号重复!");
%>
<script>
console.log(sessionStorage.getItem("login_flag"))
alert("房间号重复,重新输入房间名")
window.location.href="../../room.jsp"
</script>
<%
}
else
{
// 合法用户
try {
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=DataUser&password=DYL123&useUnicode=true&characterEncoding=UTF-8");
System.out.println("准备statement。");
String sql="INSERT INTO `test`.`room_goldenpoint` (`room_number`,`room_host`) VALUES (?,?) " ;//查询语句
System.out.println("即将执行的SQL语句是:"+sql);
pstmt = conn.prepareStatement(sql) ;
System.out.println("here now!");
pstmt.setString(1,room_number) ;
pstmt.setString(2,room_host) ;
pstmt.executeUpdate() ;//形成结果集
System.out.println(pstmt.toString());
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
}
//捕获异常
catch(SQLException ee){
System.out.print(ee);
}
}
%>
<script>
alert("创建房间成功,请返回房间界面")
window.location.href="../../room.jsp"
</script>
</body>
</html>
游戏得分判定代码
package GoldenPoint.Player;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by DYL on 2020/10/17.
*/
public class ServletPlayer extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("执行了service.");
try {
processNumberGetRecord(request,response);
} catch (JSONException e) {
e.printStackTrace();
}
}
protected void processNumberGetRecord(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException {
System.out.println("执行了processNumberGetRecord.");
response.setContentType("text/xml;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Cache-Control", "no-cache");
String Times = request.getParameter("times");
String [] idArray=request.getParameterValues("my_id")[0].split(",");
String [] numberArray = request.getParameterValues("my_number")[0].split(",");
String action=request.getParameter("action");
request.setCharacterEncoding("UTF-8");
System.out.println("页面传递过来的数据获取完毕");
for(int i=0;i<idArray.length;i++)
{
System.out.println("myId="+idArray[i]+",myNumber="+numberArray[i]);
}
List jsonList = new ArrayList();
int score[] = Player.getScore(numberArray);
for(int i=0;i<idArray.length;i++)
{
Player p =new Player();
p.times=Integer.parseInt(Times);
p.player_id=idArray[i];
p.player_number=Double.parseDouble(numberArray[i]);
p.player_score=score[i];
ConnectAndSave(p.times,p.player_id,p.player_number,p.player_score,Player.player_GoldenPonit);
Map map=new HashMap();
map.put("player_id",p.player_id);
map.put("player_number",p.player_number);
map.put("player_score",p.player_score);
map.put("goldenpoint",Player.player_GoldenPonit);
jsonList.add(map);
}
//下面构建返回的json代码
JSONObject json=new JSONObject();
json.put("record_list",jsonList);
json.put("action",action);
json.put("result_msg","ok"); //如果发生错误就设置成"error"等
json.put("result_code",0); //返回0表示正常,不等于0就表示有错误产生,错误代码
System.out.println("最后构造得到的json是:"+json.toString());
response.setContentType("text/html; charset=UTF-8");
try {
response.getWriter().print(json);
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void ConnectAndSave(int times,String id,double number,int score,double point) throws ServletException, IOException, JSONException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=DataUser&password=DYL123&useUnicode=true&characterEncoding=UTF-8");
Statement statement = conn.createStatement();
System.out.println("连接数据库Ok!!!");
//获得自己的总分
int total_score=score;
System.out.println(score);
System.out.println(total_score);
String total_score_sql="select my_total_score from goldenpoint where my_id='"+id+"'ORDER BY play_time DESC";
System.out.println("构造出来的sql语句是:"+total_score_sql);
ResultSet rs = statement.executeQuery(total_score_sql);
while (rs.next()) {
System.out.println(Integer.parseInt(rs.getString("my_total_score")));
total_score += Integer.parseInt(rs.getString("my_total_score"));
break;
}
System.out.println(total_score);
Date date = new Date();
//设置要获取到什么样的时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取String类型的时间
String createdate = sdf.format(date);
//构造sql语句
String sql="insert into goldenpoint(times,my_id,my_number,my_score,play_time,times_goldenpoint,my_total_score) values('" + times + "','" + id +"','" + number +"','" + score +"','" + createdate +"','" + point +"','" + total_score + "')";
System.out.println("构造出来的sql语句是:"+sql);
statement.executeUpdate(sql);
statement.close();
conn.close();
System.out.println("数据库关闭了!!!");
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
效果展示
注册界面
注册成功
注册失败
登录界面
登录成功,进入房间界面
登录失败
进入游戏界面(输入正确房间号)
进入房间失败(输入错误房间名)
注册房间成功
注册房间失败
进行一轮游戏(单人)
查看积分榜
阶段总结
目前已设计单用户交互方式,并且可以查看积分榜。后续准备开发服务端,以及设计界面。
上一篇: 力扣5 最长回文子串
下一篇: 行军图生成器V0.1版