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
35 changes: 35 additions & 0 deletions src/main/java/com/tictactoe/InitServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.tictactoe;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.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();
Map<Integer, Sign> fieldData = field.getField();

// Отримання списку значень поля
List<Sign> data = field.getFieldData();

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

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.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);

// Отримуємо індекс ячейки, на яку відбувся клік
int index = getSelectedIndex(req);
Sign currentSign = field.getField().get(index);

// Перевіряємо, що ячейка, на яку клікнули, порожня.
// В іншому випадку нічого не робимо і направляємо користувача на ту ж сторінку без змін
// параметрів у сесії
if (Sign.EMPTY != currentSign) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(req, resp);
return;
}

// ставимо хрестик у ячейці, по якій клікнув користувач
field.getField().put(index, Sign.CROSS);

// Перевіряємо, чи не переміг хрестик після додавання останнього кліка користувача
if (checkWin(resp, currentSession, field)) {
return;
}

// Отримуємо порожню ячейку поля
int emptyFieldIndex = field.getEmptyFieldIndex();

if (emptyFieldIndex >= 0) {
field.getField().put(emptyFieldIndex, Sign.NOUGHT);
// Перевіряємо, чи не переміг нулик після додавання останнього нулика
if (checkWin(resp, currentSession, field)) {
return;
}
}
// Якщо порожньої ячейки нема і ніхто не переміг – це нічия
else {
// Додаємо до сесії прапорець, який сигналізує, що відбулася нічия
currentSession.setAttribute("draw", true);

// Рахуємо список значків
List<Sign> data = field.getFieldData();

// Оновлюємо цей список в сесії
currentSession.setAttribute("data", data);

// Шлемо редирект
resp.sendRedirect("/index.jsp");
return;
}

// Рахуємо список значків
List<Sign> data = field.getFieldData();

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

resp.sendRedirect("/index.jsp");
}

/**
* Метод перевіряє, чи нема трьох хрестиків/нуликов в ряд.
* Повертає true/false
*/
private boolean checkWin(HttpServletResponse response, HttpSession currentSession, Field field) throws IOException {
Sign winner = field.checkWin();
if (Sign.CROSS == winner || Sign.NOUGHT == winner) {
// Додаємо прапорець, який показує, що хтось переміг
currentSession.setAttribute("winner", winner);

// Рахуємо список значків
List<Sign> data = field.getFieldData();

// Оновлюємо цей список у сесїі
currentSession.setAttribute("data", data);

// Шлемо редирект
response.sendRedirect("/index.jsp");
return true;
}
return false;
}

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;
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/tictactoe/RestartServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.tictactoe;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RestartServlet", value = "/restart")
public class RestartServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.getSession().invalidate();
resp.sendRedirect("/start");
}
}
50 changes: 49 additions & 1 deletion src/main/webapp/index.jsp
Original file line number Diff line number Diff line change
@@ -1,16 +1,64 @@
<%@ page import="com.tictactoe.Sign" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE html>
<html>
<head>
<link href="static/main.css" rel="stylesheet">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script src="<c:url value="/static/jquery-3.6.0.min.js"/>"></script>
<title>Tic-Tac-Toe</title>
</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>

<script>
<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>

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

</body>
Expand Down
89 changes: 89 additions & 0 deletions src/main/webapp/static/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/* main.css – Futuristic Tic Tac Toe style */
@import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@400;700&display=swap');

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: 'Roboto Slab', serif;
background: radial-gradient(circle at top left, #ff7e5f, #feb47b);
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

h1 {
color: #fff;
font-size: 3rem;
margin-bottom: 20px;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}

table {
border-spacing: 10px;
}

td {
width: 120px;
height: 120px;
background: rgba(255, 255, 255, 0.2);
border-radius: 15px;
text-align: center;
vertical-align: middle;
font-size: 3rem;
color: #fff;
cursor: pointer;
transition: transform 0.3s ease, background 0.3s ease;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

td:hover {
background: rgba(255, 255, 255, 0.4);
transform: scale(1.1);
}

hr {
width: 80%;
border: 0;
border-top: 2px dashed rgba(255, 255, 255, 0.7);
margin: 30px 0;
}

button {
background: linear-gradient(45deg, #ff512f, #dd2476);
border: none;
color: #fff;
font-size: 1.5rem;
padding: 10px 20px;
border-radius: 30px;
cursor: pointer;
transition: transform 0.3s ease, background 0.3s ease;
margin-top: 20px;
margin-bottom: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

button:hover {
transform: scale(1.05);
background: linear-gradient(45deg, #dd2476, #ff512f);
}

@media (max-width: 600px) {
td {
width: 90px;
height: 90px;
font-size: 2rem;
}
h1 {
font-size: 2rem;
}
button {
font-size: 1.2rem;
padding: 8px 16px;
}
}