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
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 10 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

<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>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
</properties>

<dependencies>
Expand All @@ -37,6 +37,14 @@
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
43 changes: 34 additions & 9 deletions src/main/java/com/tictactoe/Field.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.tictactoe;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;

public class Field {
Expand All @@ -21,11 +19,23 @@ public Field() {
field.put(8, Sign.EMPTY);
}

public Field(Map<Integer, Sign> anotherField){
field = new HashMap<>(anotherField);
}

public Map<Integer, Sign> getField() {
return field;
}

public int getEmptyFieldIndex() {
public int getFieldIndex() {
Field imagineField = new Field(field);

int index = getWinningIndex(Sign.NOUGHT, imagineField); //find winning move
if(index >= 0) return index;

index = getWinningIndex(Sign.CROSS, imagineField); //predict cross winning
if(index >= 0) return index;

return field.entrySet().stream()
.filter(e -> e.getValue() == Sign.EMPTY)
.map(Map.Entry::getKey)
Expand All @@ -39,7 +49,7 @@ public List<Sign> getFieldData() {
.collect(Collectors.toList());
}

public Sign checkWin() {
public boolean checkWin(Sign sign) {
List<List<Integer>> winPossibilities = List.of(
List.of(0, 1, 2),
List.of(3, 4, 5),
Expand All @@ -52,11 +62,26 @@ 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));
if (field.get(winPossibility.get(0)) == sign
&& field.get(winPossibility.get(1)) == sign
&& field.get(winPossibility.get(2)) == sign) {
return true;
}
}
return Sign.EMPTY;
return false;
}
public int getWinningIndex(Sign sign, Field imagineField) {
for (Map.Entry<Integer, Sign> entry: field.entrySet()) {
if(entry.getValue() == Sign.EMPTY){
imagineField.getField().put(entry.getKey(), sign);
if(imagineField.checkWin(sign)){
return entry.getKey();
}
imagineField.getField().put(entry.getKey(), Sign.EMPTY);
}
}
return -1;
}


}
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);
}
}
126 changes: 126 additions & 0 deletions src/main/java/com/tictactoe/LogicServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
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="LogicServer", 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.getFieldIndex();

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");
}



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;
}


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

private boolean checkWin(HttpServletResponse response, HttpSession currentSession, Field field) throws IOException {
if (field.checkWin(Sign.CROSS)) {
// Додаємо прапорець, який показує, що хтось переміг
currentSession.setAttribute("winner", Sign.CROSS);

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

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

// Шлемо редирект
response.sendRedirect("/index.jsp");
return true;
}
if(field.checkWin(Sign.NOUGHT)){
// Додаємо прапорець, який показує, що хтось переміг
currentSession.setAttribute("winner", Sign.NOUGHT);

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

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

// Шлемо редирект
response.sendRedirect("/index.jsp");
return true;
}
return false;
}
}
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");
}
}
52 changes: 51 additions & 1 deletion src/main/webapp/index.jsp
Original file line number Diff line number Diff line change
@@ -1,16 +1,66 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.tictactoe.Sign" %>

<!DOCTYPE html>
<html>
<head>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<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>


<script>
</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>
<br>
<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
Loading