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.

14 changes: 14 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.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
To run the project, please run EmbeddedTomcat.java and go to http://localhost:8081/start
17 changes: 17 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,23 @@
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.99</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.99</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/tictactoe/InitServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
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);
getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
77 changes: 77 additions & 0 deletions src/main/java/com/tictactoe/LogicServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
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");
}

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");
}
}
47 changes: 47 additions & 0 deletions src/main/java/org/example/EmbeddedTomcat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.example;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import com.tictactoe.InitServlet;
import com.tictactoe.LogicServlet;
import com.tictactoe.RestartServlet;
import java.io.File;

public class EmbeddedTomcat {
public static void main(String[] args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8081);

String webappDirLocation = new File("src/main/webapp/").getAbsolutePath();
File webAppDir = new File(webappDirLocation);

if (!webAppDir.exists()) {
System.err.println("Error: The webapp folder was not found! Path: " + webAppDir.getAbsolutePath());
return;
}

Context context = tomcat.addWebapp("", webAppDir.getAbsolutePath());

if (context == null) {
System.err.println("Error: Tomcat context was not created! There may be an issue with webapp.");
return;
}

Tomcat.addServlet(context, "InitServlet", new InitServlet());
Tomcat.addServlet(context, "LogicServlet", new LogicServlet());
Tomcat.addServlet(context, "RestartServlet", new RestartServlet());

context.addServletMappingDecoded("/start", "InitServlet");
context.addServletMappingDecoded("/logic", "LogicServlet");
context.addServletMappingDecoded("/restart", "RestartServlet");

System.out.println("Starting Tomcat. Open in your browser: http://localhost:8081/start");

tomcat.getConnector();

tomcat.start();
tomcat.getServer().await();
}
}

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
22 changes: 22 additions & 0 deletions src/main/webapp/static/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
body {
text-align: center;
font-family: Arial, sans-serif;
}

table {
margin: auto;
border-collapse: collapse;
}

td {
width: 60px;
height: 60px;
text-align: center;
font-size: 24px;
border: 2px solid black;
cursor: pointer;
}

td:hover {
background-color: #f0f0f0;
}
Binary file not shown.
Loading