Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,35 @@

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>18</maven.compiler.target>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.2.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
</dependency>
</dependencies>

Expand Down
37 changes: 37 additions & 0 deletions src/main/java/com/tictactoe/controller/InitServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.tictactoe.controller;

import com.tictactoe.entity.Field;
import com.tictactoe.entity.Sign;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(name = "InitServlet", value = "/start")
public class InitServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Создание новой сессии
HttpSession currentSession = req.getSession(true);

// Создание игрового поля
Field field = new Field();

// Получение списка значений поля
List<Sign> data = field.getFieldData();

// Добавление в сессию параметров поля (нужно будет для хранения состояния между запросами)
currentSession.setAttribute("field", field);
// и значений поля, отсортированных по индексу (нужно для отрисовки крестиков и ноликов)
currentSession.setAttribute("data", data);

// Перенаправление запроса на страницу index.jsp через сервер
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(req, resp);
}
}
125 changes: 125 additions & 0 deletions src/main/java/com/tictactoe/controller/LogicServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package com.tictactoe.controller;

import com.tictactoe.entity.Field;
import com.tictactoe.entity.Sign;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;


@WebServlet(name = "LogicServlet", value = "/logic")
public class LogicServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Получаем текущую сессию

HttpSession currentSession = req.getSession();
// Получаем объект игрового поля из сессии
Field field = extractField(currentSession);
Sign currentSign;
int index = getSelectedIndex(req);

// получаем индекс ячейки, по которой произошел клик

currentSign = field.getField().get(index);
// Проверяем, что ячейка, по которой был клик пустая.
// Иначе ничего не делаем и отправляем пользователя на ту же страницу без изменений
// параметров в сессии
if (Sign.EMPTY != currentSign) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(req, resp);
return;
}
// ставим крестик в ячейке, по которой кликнул пользователь
field.getField().put(index, Sign.CROSS);
// Проверяем, не победил ли крестик после добавления последнего клика пользователя
if (checkWin(resp, req, currentSession, field)) {
return;
}
// Получаем пустую ячейку поля
int emptyFieldIndex = field.getEmptyFieldIndex();

if (emptyFieldIndex >= 0) {
field.getField().put(emptyFieldIndex, Sign.NOUGHT);
// Проверяем, не победил ли нолик после добавление последнего нолика
if (checkWin(resp, req, currentSession, field)) {
return;
}
}
// Если пустой ячейки нет и никто не победил - значит это ничья
else {
// Добавляем в сессию флаг, который сигнализирует что произошла ничья
currentSession.setAttribute("draw", true);

// Считаем список значков
List<Sign> data = field.getFieldData();

// Обновляем этот список в сессии
currentSession.setAttribute("data", data);

// Шлем редирект
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(req, resp);
return;
}

// Считаем список значков
List<Sign> data = field.getFieldData();

// Обновляем объект поля и список значков в сессии
currentSession.setAttribute("data", data);
currentSession.setAttribute("field", field);

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(req, resp);

}


private int getSelectedIndex(HttpServletRequest request) {
String click = request.getParameter("click");
boolean isNumeric = click.chars().allMatch(Character::isDigit);
return isNumeric ? Integer.parseInt(click) : 0;
}

private Field extractField(HttpSession currentSession) {
Object fieldAttribute = currentSession.getAttribute("field");
if (Field.class != fieldAttribute.getClass()) {
currentSession.invalidate();
throw new RuntimeException("Session is broken, try one more time");
}
return (Field) fieldAttribute;
}

/**
* Метод проверяет, нет ли трех крестиков/ноликов в ряд.
* Возвращает true/false
*/
private boolean checkWin(HttpServletResponse resp, HttpServletRequest req, HttpSession currentSession, Field field) throws IOException, ServletException {
Sign winner = field.checkWin();
if (Sign.CROSS == winner || Sign.NOUGHT == winner) {
// Добавляем флаг, который показывает что кто-то победил
currentSession.setAttribute("winner", winner);

// Считаем список значков
List<Sign> data = field.getFieldData();

// Обновляем этот список в сессии
currentSession.setAttribute("data", data);

// Шлем редирект
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(req, resp);
return true;
}
return false;
}

}
17 changes: 17 additions & 0 deletions src/main/java/com/tictactoe/controller/RestartServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.tictactoe.controller;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(name = "RestartServlet", value = "/restart")
public class RestartServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.getSession().invalidate();
resp.sendRedirect("/start");
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.tictactoe;
package com.tictactoe.entity;

import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -54,7 +54,7 @@ public Sign checkWin() {
for (List<Integer> winPossibility : winPossibilities) {
if (field.get(winPossibility.get(0)) == field.get(winPossibility.get(1))
&& field.get(winPossibility.get(0)) == field.get(winPossibility.get(2))) {
return field.get(winPossibility.get(0));
return field.get(winPossibility.getFirst());
}
}
return Sign.EMPTY;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.tictactoe;
package com.tictactoe.entity;

public enum Sign {
EMPTY(' '),
Expand Down
65 changes: 65 additions & 0 deletions src/main/webapp/WEB-INF/index.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<%@ page import="com.tictactoe.entity.Sign" %>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
<link href="../static/main.css" rel="stylesheet">
<script src="<c:url value="/static/jquery-3.6.0.min.js"/>"></script>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<table>
<tr>
<td onclick="window.location='/logic?click=0'">${data.get(0).getSign()}</td>
<td onclick="window.location='/logic?click=1'">${data.get(1).getSign()}</td>
<td onclick="window.location='/logic?click=2'">${data.get(2).getSign()}</td>
</tr>
<tr>
<td onclick="window.location='/logic?click=3'">${data.get(3).getSign()}</td>
<td onclick="window.location='/logic?click=4'">${data.get(4).getSign()}</td>
<td onclick="window.location='/logic?click=5'">${data.get(5).getSign()}</td>
</tr>
<tr>
<td onclick="window.location='/logic?click=6'">${data.get(6).getSign()}</td>
<td onclick="window.location='/logic?click=7'">${data.get(7).getSign()}</td>
<td onclick="window.location='/logic?click=8'">${data.get(8).getSign()}</td>
</tr>
</table>
<hr>
<c:set var="CROSSES" value="<%=Sign.CROSS%>"/>
<c:set var="NOUGHTS" value="<%=Sign.NOUGHT%>"/>

<c:if test="${winner == CROSSES}">
<h1>CROSSES WIN!</h1>
<button onclick="restart()">Start again</button>
</c:if>
<c:if test="${winner == NOUGHTS}">
<h1>NOUGHTS WIN!</h1>
<button onclick="restart()">Start again</button>
</c:if>
<c:if test="${draw}">
<h1>IT'S A DRAW</h1>
<button onclick="restart()">Start again</button>
</c:if>
<c:if test="${winner != NOUGHTS && winner != CROSSES && !draw}">
<h1></h1>
</c:if>

<script>
function restart() {
$.ajax({
url: '/restart',
type: 'GET',
contentType: 'application/json;charset=UTF-8',
async: false,
success: function () {
window.location = "/start";
}
});
}
</script>

</body>
</html>
6 changes: 6 additions & 0 deletions src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
17 changes: 0 additions & 17 deletions src/main/webapp/index.jsp

This file was deleted.

19 changes: 19 additions & 0 deletions src/main/webapp/static/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
body {
text-align: center;
}
table {
display: flex;
align-items: center;
justify-content: center;
}
td {
border: 3px solid black;
padding: 10px;
border-collapse: separate;
margin: 10px;
width: 100px;
height: 100px;
font-size: 50px;
text-align: center;
empty-cells: show;
}