总体概述
实现一个网页版五子棋对战程序,支持以下核心功能:
1. 用户模块:用户注册、用户登录、用户天梯分数记录 以及 用户比赛场次记录
2. 匹配模块:按照用户的天梯分数实现匹配机制
3. 对战模块:实现两个玩家在网页端进行五子棋对战功能
核心技术
Spring/SpringBoot/SpringMVC
WebSocket
MySQL
MyBatis
HTML/CSS/AJAX
需求分析
整个项目主要分为三个模块:
用户模块
匹配模块
对战模块
用户模块
用户模块主要涉及用户的注册、登录 以及 分数的记录功能
使用 MySQL 数据库存储数据
客户端提供 登录页面 和 注册页面
服务端基于 Spring + MyBatis 实现数据库的增删改查
匹配模块
用户登录成功,进入游戏大厅页面
在游戏大厅中,显示用户名、天梯分数、比赛场次等基本信息和一个匹配按钮
点击匹配按钮,用户进入匹配队列,按钮显示 "正在匹配"
再次点击,将用户从匹配队列中移除,显示 "点击进行匹配"
若用户成功匹配到对手,显示对手信息,点击确定,跳转至游戏房间页面
对战模块
玩家匹配成功,进入游戏房间页面
匹配成功的两个玩家处于同一游戏房间
在游戏房间页面中,显示五子棋棋盘,以及落子提示信息
轮到当前玩家落子时,玩家点击棋盘对应位置实现落子
当棋盘上存在五个连续的同色棋子时,判定游戏结束,显示 胜利/失败信息,同时显示"返回游戏大厅"按钮
若玩家中途退出,则直接判断对手胜利
数据库设计
create database if not exists java_gobang;
use java_gobang;
drop table if exists user;
create table user(
userid int primary key auto_increment,
username varchar(50) unique,
password varchar(50) not null,
socre int,
totalCount int,
winCount int
);
insert into user(username,password,socre,totalCount,winCount) values('admin','admin',0,0,0);
insert into user(username,password,socre,totalCount,winCount) values('zhangsan','123456',0,0,0);
insert into user(username,password,socre,totalCount,winCount) values('lisi','123456',0,0,0);
数据库配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/java_gobang?characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
configuration:
map-underscore-to-camel-case: true #配置驼峰自动转换
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句
mapper-locations: classpath:mapper/**Mapper.xml
logging:
file:
name: logs/springboot.log
项目创建
jackson
在前后端交互的过程中,经常会使用 JSON 格式来传递数据,这也就涉及到 序列化 和 反序列化,此外,我们在进行日志打印时,也会涉及到序列化
因此,我们可以定义一个工具类,来专门处理 序列化
在 java 中,通常使用 ObjectMapper 来处理 Java 对象与 JSON 数据之间的转换
因此,我们首先来学习一下 ObjectMapper 的相关方法和使用
序列化需要使用 ObjectMapper 中的 writeValueAsString 方法:
序列化讲java对象转化为json字符串形式
@SpringBootTest
public class JacksonTest {
@Test
void jacksonTest() {
// 创建 ObjectMapper 实例
ObjectMapper objectMapper = new ObjectMapper();
// 序列化
CommonResult<String> result = CommonResult.success("成功"); // 创建 java 对象
String str = null;
try {
str = objectMapper.writeValueAsString(result);
System.out.println("序列化结果:" + str);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
反序列化需要使用 readValue 方法:
讲json字符串转化为java对象
// 反序列化
try {
CommonResult<String> result1 = objectMapper.readValue(str, CommonResult.class);
System.out.println(result1.getCode() + " " + result1.getData());
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}