initial issue
This commit is contained in:
parent
d62a044ec1
commit
17902a52d5
|
|
@ -1,26 +1,39 @@
|
|||
# ---> Java
|
||||
# Compiled class file
|
||||
### java ###
|
||||
api/bin/
|
||||
api/target/
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
replay_pid*
|
||||
### web ###
|
||||
# dependencies
|
||||
web/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# next.js
|
||||
web/.next/
|
||||
web/out/
|
||||
|
||||
# production
|
||||
web/build
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
### Logs ###
|
||||
*.log
|
||||
|
||||
### OS ###
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
FROM openjdk:21
|
||||
COPY ./ApiMastermind-0.0.1.jar app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# ApiMastermind
|
||||
REST API for Mastermind Game
|
||||
|
||||
```bash
|
||||
mvn test
|
||||
mvn package -DskipTests
|
||||
```
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
version: '3.3'
|
||||
|
||||
services:
|
||||
s_app_mastermind:
|
||||
container_name: c_app_mastermind
|
||||
image: app_mastermind
|
||||
restart: always
|
||||
ports:
|
||||
- 8005:8080
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.5.3</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.mmkilic.game</groupId>
|
||||
<artifactId>ApiMastermind</artifactId>
|
||||
<version>0.2</version>
|
||||
<name>ApiMastermind</name>
|
||||
<description>Mastermind Game REST API</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.mmkilic.game;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ApiMastermindApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApiMastermindApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.mmkilic.game.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/** Enables the multiplayer sweeper (disconnect detection + cleanup of closed games). */
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class SchedulingConfig {}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
package com.mmkilic.game.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.headers(headers -> headers.frameOptions(fo -> fo.sameOrigin()))
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
//configuration.setAllowedOrigins(Arrays.asList("*"));
|
||||
configuration.setAllowedOrigins(List.of("http://localhost:3000", "https://www.mmkilic.com"));
|
||||
//configuration.setAllowedOriginPatterns(List.of("http://localhost:*"));
|
||||
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(List.of("*"));
|
||||
//configuration.setAllowedHeaders(Arrays.asList("content-type"));
|
||||
//configuration.setAllowedHeaders(Arrays.asList(HttpHeaders.CONTENT_TYPE, HttpHeaders.AUTHORIZATION));
|
||||
configuration.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.mmkilic.game.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.mmkilic.game.entity.ResponseGuess;
|
||||
import com.mmkilic.game.service.SingleGameService;
|
||||
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class SingleGameController {
|
||||
private final SingleGameService srv;
|
||||
|
||||
@PostMapping("/start")
|
||||
public ResponseEntity<ResponseGuess> start(HttpSession session, @RequestParam int digitNumber) {
|
||||
return ResponseEntity.ok(srv.start(session, digitNumber));
|
||||
}
|
||||
|
||||
@PostMapping("/guess")
|
||||
public ResponseEntity<ResponseGuess> guess(HttpSession session, @RequestParam String guess) {
|
||||
return ResponseEntity.ok(srv.guess(session, guess));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
package com.mmkilic.game.entity;
|
||||
|
||||
public record ResponseGuess (int attempts, String guess, boolean win, int positive, int negative) {}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
package com.mmkilic.game.multi.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.mmkilic.game.multi.dto.CreateGameRequest;
|
||||
import com.mmkilic.game.multi.dto.GameSummary;
|
||||
import com.mmkilic.game.multi.dto.GameView;
|
||||
import com.mmkilic.game.multi.dto.JoinResponse;
|
||||
import com.mmkilic.game.multi.dto.NumberRequest;
|
||||
import com.mmkilic.game.multi.service.MultiGameService;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
/**
|
||||
* Multiplayer REST API. Player specific endpoints need the token returned by create/join
|
||||
* in the {@value #TOKEN_HEADER} header.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/multi/games")
|
||||
@RequiredArgsConstructor
|
||||
public class MultiGameController {
|
||||
public static final String TOKEN_HEADER = "X-Player-Token";
|
||||
|
||||
private final MultiGameService srv;
|
||||
|
||||
@GetMapping
|
||||
public List<GameSummary> list() {
|
||||
return srv.list();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public JoinResponse create(@RequestBody CreateGameRequest req) {
|
||||
return srv.create(req);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/join")
|
||||
public JoinResponse join(@PathVariable String id) {
|
||||
return srv.join(id);
|
||||
}
|
||||
|
||||
/** Polled by the client (about once per second); also acts as the heartbeat. */
|
||||
@GetMapping("/{id}/state")
|
||||
public GameView state(@PathVariable String id, @RequestHeader(TOKEN_HEADER) String token) {
|
||||
return srv.state(id, token);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/secret")
|
||||
public GameView secret(@PathVariable String id, @RequestHeader(TOKEN_HEADER) String token,
|
||||
@RequestBody NumberRequest req) {
|
||||
return srv.chooseSecret(id, token, req == null ? null : req.number());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/guess")
|
||||
public GameView guess(@PathVariable String id, @RequestHeader(TOKEN_HEADER) String token,
|
||||
@RequestBody NumberRequest req) {
|
||||
return srv.guess(id, token, req == null ? null : req.number());
|
||||
}
|
||||
|
||||
/** Token may come as header or query param (navigator.sendBeacon cannot set headers). */
|
||||
@PostMapping("/{id}/leave")
|
||||
public ResponseEntity<Void> leave(@PathVariable String id,
|
||||
@RequestHeader(value = TOKEN_HEADER, required = false) String headerToken,
|
||||
@RequestParam(value = "token", required = false) String paramToken) {
|
||||
srv.leave(id, headerToken != null ? headerToken : paramToken);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.mmkilic.game.multi.controller;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import com.mmkilic.game.multi.service.GameException;
|
||||
|
||||
/** Returns {"message": "..."} errors for the multiplayer API only. */
|
||||
@RestControllerAdvice(assignableTypes = MultiGameController.class)
|
||||
public class MultiGameExceptionHandler {
|
||||
|
||||
@ExceptionHandler(GameException.class)
|
||||
public ResponseEntity<Map<String, String>> game(GameException e) {
|
||||
return ResponseEntity.status(e.getStatus()).body(Map.of("message", e.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<Map<String, String>> unreadable(HttpMessageNotReadableException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", "Invalid request body!"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<Map<String, String>> missingHeader(MissingRequestHeaderException e) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("message", "Player token is missing!"));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
import com.mmkilic.game.multi.model.GameType;
|
||||
|
||||
public record CreateGameRequest(String name, int digits, GameType type) {}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
import com.mmkilic.game.multi.model.GameStatus;
|
||||
import com.mmkilic.game.multi.model.GameType;
|
||||
|
||||
public record GameSummary(String id, String name, int digits, GameType type, GameStatus status,
|
||||
int players, long createdAt) {}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
import com.mmkilic.game.multi.model.EndReason;
|
||||
import com.mmkilic.game.multi.model.GameStatus;
|
||||
import com.mmkilic.game.multi.model.GameType;
|
||||
|
||||
/** Game state seen by one player. */
|
||||
public record GameView(
|
||||
String id,
|
||||
String name,
|
||||
int digits,
|
||||
GameType type,
|
||||
GameStatus status,
|
||||
/** WAITING, SETUP, PLAYING or FINISHED. */
|
||||
String stage,
|
||||
long serverTime,
|
||||
/** Time since guessing started (frozen when closed). */
|
||||
long elapsedMs,
|
||||
/** Round based modes: current round number. */
|
||||
int round,
|
||||
boolean canGuess,
|
||||
boolean waitingForRival,
|
||||
boolean canChooseSecret,
|
||||
PlayerView you,
|
||||
PlayerView rival,
|
||||
/** WIN, LOSE, DRAW or null while not finished. */
|
||||
String outcome,
|
||||
EndReason endReason,
|
||||
/** true if YOU are the player who left. */
|
||||
boolean youLeft) {}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
/** positive/negative are null while the round result is not revealed yet. */
|
||||
public record GuessView(int turn, String guess, Integer positive, Integer negative) {}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
public record JoinResponse(String gameId, String playerToken, GameView state) {}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
/** Body for guess and secret endpoints. */
|
||||
public record NumberRequest(String number) {}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package com.mmkilic.game.multi.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PlayerView(
|
||||
int slot,
|
||||
boolean connected,
|
||||
/** PLAYER_GUESSTURES: has this player chosen the number for the rival? */
|
||||
boolean secretChosen,
|
||||
/** Own view only: the number you chose for the rival. */
|
||||
String secretForRival,
|
||||
int attempts,
|
||||
boolean found,
|
||||
/** null when not revealed yet. */
|
||||
Long timeMs,
|
||||
Integer score,
|
||||
/** The number this player had to find, revealed when the game is closed. */
|
||||
String numberToFind,
|
||||
List<GuessView> history) {}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
public enum EndReason {
|
||||
/** The game ended by the rules (number found). */
|
||||
SOLVED,
|
||||
/** A player left (explicitly or by losing connection). */
|
||||
PLAYER_LEFT
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
public enum GameStatus {
|
||||
/** Created, waiting for the second player. */
|
||||
WAITING,
|
||||
/** Both players joined (includes the secret selection step of PLAYER_GUESSTURES). */
|
||||
PLAYING,
|
||||
/** Finished normally or because a player left. */
|
||||
CLOSED
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
public enum GameType {
|
||||
/** Server picks a different secret for each player, rounds are played together. */
|
||||
AUTO_GUESSTURES,
|
||||
/** Each player chooses the secret their rival has to find, rounds are played together. */
|
||||
PLAYER_GUESSTURES,
|
||||
/** Server picks one secret for both players, turns are independent and timed. */
|
||||
TIME_CHALLENGE;
|
||||
|
||||
public boolean isRoundBased() {
|
||||
return this != TIME_CHALLENGE;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
public record GuessRecord(int turn, String guess, int positive, int negative, long submittedAt) {}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/** In-memory game. All mutations are done while holding the game's monitor. */
|
||||
@Getter
|
||||
@Setter
|
||||
public class MultiGame {
|
||||
private final String id;
|
||||
private final String name;
|
||||
private final int digits;
|
||||
private final GameType type;
|
||||
private final long createdAt;
|
||||
|
||||
private GameStatus status = GameStatus.WAITING;
|
||||
private Player player1;
|
||||
private Player player2;
|
||||
|
||||
/** When guessing started (after both joined, or after both secrets were set). */
|
||||
private long startedAt;
|
||||
/** Round based modes: when the current round opened. */
|
||||
private long roundStartedAt;
|
||||
/** Round based modes: number of completed rounds. */
|
||||
private int completedRounds;
|
||||
|
||||
private long closedAt;
|
||||
private EndReason endReason;
|
||||
/** Slot of the winner, 0 = draw / no winner. */
|
||||
private int winnerSlot;
|
||||
/** Slot of the player who left, 0 if nobody left. */
|
||||
private int leftSlot;
|
||||
|
||||
public MultiGame(String id, String name, int digits, GameType type, long now) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.digits = digits;
|
||||
this.type = type;
|
||||
this.createdAt = now;
|
||||
}
|
||||
|
||||
public int playerCount() {
|
||||
return (player1 != null ? 1 : 0) + (player2 != null ? 1 : 0);
|
||||
}
|
||||
|
||||
public Player byToken(String token) {
|
||||
if (token == null) return null;
|
||||
if (player1 != null && player1.getToken().equals(token)) return player1;
|
||||
if (player2 != null && player2.getToken().equals(token)) return player2;
|
||||
return null;
|
||||
}
|
||||
|
||||
public Player rivalOf(Player p) {
|
||||
return p == player1 ? player2 : player1;
|
||||
}
|
||||
|
||||
/** True while PLAYER_GUESSTURES players are still choosing numbers for each other. */
|
||||
public boolean isInSetup() {
|
||||
return status == GameStatus.PLAYING && startedAt == 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package com.mmkilic.game.multi.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class Player {
|
||||
private final String token;
|
||||
private final int slot; // 1 = creator, 2 = joiner
|
||||
private volatile long lastSeen;
|
||||
|
||||
/** The number THIS player has to find. */
|
||||
private String secretToFind;
|
||||
/** PLAYER_GUESSTURES: the number this player chose for the rival (null until set). */
|
||||
private String secretForRival;
|
||||
|
||||
private final List<GuessRecord> guesses = new ArrayList<>();
|
||||
private boolean found;
|
||||
/** Thinking time (ms) used for scoring; see ScoreCalculator. */
|
||||
private long timeMs;
|
||||
private int score;
|
||||
private boolean left;
|
||||
|
||||
public Player(String token, int slot, long now) {
|
||||
this.token = token;
|
||||
this.slot = slot;
|
||||
this.lastSeen = now;
|
||||
}
|
||||
|
||||
public int getAttempts() {
|
||||
return guesses.size();
|
||||
}
|
||||
|
||||
public GuessRecord lastGuess() {
|
||||
return guesses.isEmpty() ? null : guesses.get(guesses.size() - 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package com.mmkilic.game.multi.service;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class GameException extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final HttpStatus status;
|
||||
|
||||
public GameException(HttpStatus status, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,358 @@
|
|||
package com.mmkilic.game.multi.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.mmkilic.game.multi.dto.CreateGameRequest;
|
||||
import com.mmkilic.game.multi.dto.GameSummary;
|
||||
import com.mmkilic.game.multi.dto.GameView;
|
||||
import com.mmkilic.game.multi.dto.GuessView;
|
||||
import com.mmkilic.game.multi.dto.JoinResponse;
|
||||
import com.mmkilic.game.multi.dto.PlayerView;
|
||||
import com.mmkilic.game.multi.model.EndReason;
|
||||
import com.mmkilic.game.multi.model.GameStatus;
|
||||
import com.mmkilic.game.multi.model.GameType;
|
||||
import com.mmkilic.game.multi.model.GuessRecord;
|
||||
import com.mmkilic.game.multi.model.MultiGame;
|
||||
import com.mmkilic.game.multi.model.Player;
|
||||
import com.mmkilic.game.service.NumberRules;
|
||||
|
||||
/**
|
||||
* In-memory multiplayer games (no database). Every player is identified by a random token
|
||||
* returned on create/join. Clients poll {@link #state} which also works as a heartbeat;
|
||||
* a player that stops polling for {@code playerTimeoutMs} is treated as having left.
|
||||
*/
|
||||
@Service
|
||||
public class MultiGameService {
|
||||
private static final int MAX_NAME_LENGTH = 30;
|
||||
|
||||
private final Map<String, MultiGame> games = new ConcurrentHashMap<>();
|
||||
private final Object createLock = new Object();
|
||||
|
||||
private final long playerTimeoutMs;
|
||||
private final long closedRetentionMs;
|
||||
|
||||
public MultiGameService(
|
||||
@Value("${multiplayer.player-timeout-ms:20000}") long playerTimeoutMs,
|
||||
@Value("${multiplayer.closed-retention-ms:300000}") long closedRetentionMs) {
|
||||
this.playerTimeoutMs = playerTimeoutMs;
|
||||
this.closedRetentionMs = closedRetentionMs;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ lobby
|
||||
|
||||
public List<GameSummary> list() {
|
||||
return games.values().stream()
|
||||
.sorted(Comparator.<MultiGame>comparingInt(g -> g.getStatus().ordinal())
|
||||
.thenComparing(Comparator.comparingLong(MultiGame::getCreatedAt).reversed()))
|
||||
.map(g -> new GameSummary(g.getId(), g.getName(), g.getDigits(), g.getType(),
|
||||
g.getStatus(), g.playerCount(), g.getCreatedAt()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public JoinResponse create(CreateGameRequest req) {
|
||||
if (req == null) throw bad("Request body is missing!");
|
||||
String name = req.name() == null ? "" : req.name().trim();
|
||||
if (name.isEmpty()) throw bad("Game name is required!");
|
||||
if (name.length() > MAX_NAME_LENGTH) throw bad("Game name can be at most " + MAX_NAME_LENGTH + " characters!");
|
||||
if (!NumberRules.isValidDigitCount(req.digits()))
|
||||
throw bad("Number limit must be between " + NumberRules.MIN_DIGITS + " and " + NumberRules.MAX_DIGITS + "!");
|
||||
if (req.type() == null) throw bad("Game type is required!");
|
||||
|
||||
long now = now();
|
||||
synchronized (createLock) {
|
||||
boolean taken = games.values().stream()
|
||||
.anyMatch(g -> g.getStatus() != GameStatus.CLOSED && g.getName().equalsIgnoreCase(name));
|
||||
if (taken) throw new GameException(HttpStatus.CONFLICT, "Game name '" + name + "' is already in use!");
|
||||
|
||||
MultiGame game = new MultiGame(UUID.randomUUID().toString(), name, req.digits(), req.type(), now);
|
||||
Player creator = new Player(UUID.randomUUID().toString(), 1, now);
|
||||
game.setPlayer1(creator);
|
||||
games.put(game.getId(), game);
|
||||
synchronized (game) {
|
||||
return new JoinResponse(game.getId(), creator.getToken(), view(game, creator, now));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JoinResponse join(String gameId) {
|
||||
MultiGame game = find(gameId);
|
||||
long now = now();
|
||||
synchronized (game) {
|
||||
if (game.getStatus() != GameStatus.WAITING || game.getPlayer2() != null)
|
||||
throw new GameException(HttpStatus.CONFLICT, "This game is not waiting for players anymore!");
|
||||
|
||||
Player joiner = new Player(UUID.randomUUID().toString(), 2, now);
|
||||
game.setPlayer2(joiner);
|
||||
game.setStatus(GameStatus.PLAYING);
|
||||
|
||||
if (game.getType() == GameType.AUTO_GUESSTURES) {
|
||||
String s1 = NumberRules.generate(game.getDigits());
|
||||
String s2;
|
||||
do { s2 = NumberRules.generate(game.getDigits()); } while (s2.equals(s1));
|
||||
game.getPlayer1().setSecretToFind(s1);
|
||||
joiner.setSecretToFind(s2);
|
||||
startGuessing(game, now);
|
||||
} else if (game.getType() == GameType.TIME_CHALLENGE) {
|
||||
String shared = NumberRules.generate(game.getDigits());
|
||||
game.getPlayer1().setSecretToFind(shared);
|
||||
joiner.setSecretToFind(shared);
|
||||
startGuessing(game, now);
|
||||
}
|
||||
// PLAYER_GUESSTURES: stays in setup until both players choose a number.
|
||||
|
||||
return new JoinResponse(game.getId(), joiner.getToken(), view(game, joiner, now));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ game actions
|
||||
|
||||
public GameView state(String gameId, String token) {
|
||||
MultiGame game = find(gameId);
|
||||
long now = now();
|
||||
synchronized (game) {
|
||||
Player me = player(game, token);
|
||||
me.setLastSeen(now);
|
||||
return view(game, me, now);
|
||||
}
|
||||
}
|
||||
|
||||
/** PLAYER_GUESSTURES: choose the number the rival has to find. Can be changed until the rival also chose. */
|
||||
public GameView chooseSecret(String gameId, String token, String number) {
|
||||
MultiGame game = find(gameId);
|
||||
long now = now();
|
||||
synchronized (game) {
|
||||
Player me = player(game, token);
|
||||
me.setLastSeen(now);
|
||||
if (game.getType() != GameType.PLAYER_GUESSTURES) throw conflict("This game type has no number selection!");
|
||||
if (!game.isInSetup()) throw conflict("Number selection is not open!");
|
||||
if (!NumberRules.isValidNumber(number, game.getDigits()))
|
||||
throw bad("Number must have " + game.getDigits() + " digits and each digit can be used only once!");
|
||||
|
||||
Player rival = game.rivalOf(me);
|
||||
me.setSecretForRival(number);
|
||||
rival.setSecretToFind(number);
|
||||
|
||||
if (rival.getSecretForRival() != null) startGuessing(game, now);
|
||||
return view(game, me, now);
|
||||
}
|
||||
}
|
||||
|
||||
public GameView guess(String gameId, String token, String number) {
|
||||
MultiGame game = find(gameId);
|
||||
long now = now();
|
||||
synchronized (game) {
|
||||
Player me = player(game, token);
|
||||
me.setLastSeen(now);
|
||||
if (game.getStatus() != GameStatus.PLAYING) throw conflict("The game is not being played!");
|
||||
if (game.isInSetup()) throw conflict("Waiting for both players to choose a number!");
|
||||
if (!NumberRules.isValidNumber(number, game.getDigits()))
|
||||
throw bad("Guess must have " + game.getDigits() + " digits and each digit can be used only once!");
|
||||
if (me.isFound()) throw conflict("You already found the number!");
|
||||
|
||||
boolean roundBased = game.getType().isRoundBased();
|
||||
if (roundBased && me.getAttempts() > game.getCompletedRounds())
|
||||
throw conflict("Wait for your rival to finish this round!");
|
||||
|
||||
Player rival = game.rivalOf(me);
|
||||
int[] r = NumberRules.check(me.getSecretToFind(), number);
|
||||
me.getGuesses().add(new GuessRecord(me.getAttempts() + 1, number, r[0], r[1], now));
|
||||
|
||||
if (roundBased) {
|
||||
me.setTimeMs(me.getTimeMs() + (now - game.getRoundStartedAt()));
|
||||
if (rival.getAttempts() == me.getAttempts()) completeRound(game, now);
|
||||
} else {
|
||||
if (r[0] == game.getDigits()) {
|
||||
me.setFound(true);
|
||||
me.setTimeMs(now - game.getStartedAt());
|
||||
me.setScore(ScoreCalculator.score(true, game.getDigits(), me.getAttempts(), me.getTimeMs()));
|
||||
if (rival.isFound()) finish(game, EndReason.SOLVED, now);
|
||||
}
|
||||
}
|
||||
return view(game, me, now);
|
||||
}
|
||||
}
|
||||
|
||||
public void leave(String gameId, String token) {
|
||||
MultiGame game = games.get(gameId);
|
||||
if (game == null) return;
|
||||
synchronized (game) {
|
||||
Player me = game.byToken(token);
|
||||
if (me != null) playerLeft(game, me, now());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ housekeeping
|
||||
|
||||
/** Detects disconnected players and removes old closed games. */
|
||||
@Scheduled(fixedDelayString = "${multiplayer.sweep-interval-ms:2000}")
|
||||
public void sweep() {
|
||||
long now = now();
|
||||
for (MultiGame game : games.values()) {
|
||||
synchronized (game) {
|
||||
if (game.getStatus() == GameStatus.CLOSED) {
|
||||
if (now - game.getClosedAt() > closedRetentionMs) games.remove(game.getId());
|
||||
continue;
|
||||
}
|
||||
for (Player p : new Player[] { game.getPlayer1(), game.getPlayer2() }) {
|
||||
if (p != null && game.getStatus() != GameStatus.CLOSED && now - p.getLastSeen() > playerTimeoutMs)
|
||||
playerLeft(game, p, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ internals
|
||||
|
||||
private void startGuessing(MultiGame game, long now) {
|
||||
game.setStartedAt(now);
|
||||
game.setRoundStartedAt(now);
|
||||
}
|
||||
|
||||
private void completeRound(MultiGame game, long now) {
|
||||
game.setCompletedRounds(game.getCompletedRounds() + 1);
|
||||
game.setRoundStartedAt(now);
|
||||
boolean anyFound = false;
|
||||
for (Player p : new Player[] { game.getPlayer1(), game.getPlayer2() }) {
|
||||
if (p.lastGuess().positive() == game.getDigits()) {
|
||||
p.setFound(true);
|
||||
anyFound = true;
|
||||
}
|
||||
}
|
||||
if (anyFound) finish(game, EndReason.SOLVED, now);
|
||||
}
|
||||
|
||||
private void playerLeft(MultiGame game, Player leaver, long now) {
|
||||
if (game.getStatus() == GameStatus.CLOSED) return;
|
||||
leaver.setLeft(true);
|
||||
game.setLeftSlot(leaver.getSlot());
|
||||
finish(game, EndReason.PLAYER_LEFT, now);
|
||||
}
|
||||
|
||||
private void finish(MultiGame game, EndReason reason, long now) {
|
||||
game.setStatus(GameStatus.CLOSED);
|
||||
game.setClosedAt(now);
|
||||
game.setEndReason(reason);
|
||||
|
||||
Player p1 = game.getPlayer1();
|
||||
Player p2 = game.getPlayer2();
|
||||
for (Player p : new Player[] { p1, p2 }) {
|
||||
if (p != null)
|
||||
p.setScore(ScoreCalculator.score(p.isFound(), game.getDigits(), p.getAttempts(), p.getTimeMs()));
|
||||
}
|
||||
if (p2 == null) { // closed while waiting
|
||||
game.setWinnerSlot(0);
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason == EndReason.PLAYER_LEFT) {
|
||||
Player leaver = p1.isLeft() ? p1 : p2;
|
||||
Player stayer = game.rivalOf(leaver);
|
||||
// The player who stays wins, unless the leaver had already solved the number and the stayer had not.
|
||||
boolean leaverEarnedIt = leaver.isFound() && !stayer.isFound();
|
||||
game.setWinnerSlot(leaverEarnedIt ? leaver.getSlot() : stayer.getSlot());
|
||||
} else if (p1.getScore() != p2.getScore()) {
|
||||
game.setWinnerSlot(p1.getScore() > p2.getScore() ? 1 : 2);
|
||||
} else {
|
||||
game.setWinnerSlot(0);
|
||||
}
|
||||
}
|
||||
|
||||
private GameView view(MultiGame game, Player me, long now) {
|
||||
Player rival = game.rivalOf(me);
|
||||
boolean closed = game.getStatus() == GameStatus.CLOSED;
|
||||
boolean roundBased = game.getType().isRoundBased();
|
||||
|
||||
String stage;
|
||||
if (closed) stage = "FINISHED";
|
||||
else if (game.getStatus() == GameStatus.WAITING) stage = "WAITING";
|
||||
else if (game.isInSetup()) stage = "SETUP";
|
||||
else stage = "PLAYING";
|
||||
|
||||
boolean playing = "PLAYING".equals(stage);
|
||||
boolean waitingForRival = playing && roundBased && me.getAttempts() > game.getCompletedRounds();
|
||||
boolean canGuess = playing && !me.isFound() && !waitingForRival;
|
||||
|
||||
long elapsed = 0;
|
||||
if (game.getStartedAt() > 0) elapsed = (closed ? game.getClosedAt() : now) - game.getStartedAt();
|
||||
|
||||
String outcome = null;
|
||||
if (closed && rival != null) {
|
||||
if (game.getWinnerSlot() == 0) outcome = "DRAW";
|
||||
else outcome = game.getWinnerSlot() == me.getSlot() ? "WIN" : "LOSE";
|
||||
}
|
||||
|
||||
return new GameView(
|
||||
game.getId(), game.getName(), game.getDigits(), game.getType(), game.getStatus(), stage,
|
||||
now, elapsed,
|
||||
roundBased ? game.getCompletedRounds() + 1 : me.getAttempts() + 1,
|
||||
canGuess, waitingForRival,
|
||||
"SETUP".equals(stage),
|
||||
playerView(game, me, true),
|
||||
rival == null ? null : playerView(game, rival, false),
|
||||
outcome, game.getEndReason(), me.isLeft());
|
||||
}
|
||||
|
||||
private PlayerView playerView(MultiGame game, Player p, boolean own) {
|
||||
boolean closed = game.getStatus() == GameStatus.CLOSED;
|
||||
boolean roundBased = game.getType().isRoundBased();
|
||||
|
||||
List<GuessView> history = new ArrayList<>();
|
||||
if (roundBased || own || closed) {
|
||||
for (GuessRecord g : p.getGuesses()) {
|
||||
boolean revealed = !roundBased || g.turn() <= game.getCompletedRounds() || closed;
|
||||
if (!revealed && !own) continue; // rival's guess of the running round stays hidden
|
||||
history.add(revealed
|
||||
? new GuessView(g.turn(), g.guess(), g.positive(), g.negative())
|
||||
: new GuessView(g.turn(), g.guess(), null, null));
|
||||
}
|
||||
}
|
||||
|
||||
// Score and time: always for yourself once found, for the rival only when the game is over.
|
||||
boolean showResult = closed || (own && p.isFound());
|
||||
return new PlayerView(
|
||||
p.getSlot(),
|
||||
!p.isLeft(),
|
||||
p.getSecretForRival() != null,
|
||||
own ? p.getSecretForRival() : null,
|
||||
p.getAttempts(),
|
||||
p.isFound(),
|
||||
showResult ? p.getTimeMs() : null,
|
||||
showResult ? p.getScore() : null,
|
||||
closed ? p.getSecretToFind() : null,
|
||||
history);
|
||||
}
|
||||
|
||||
private MultiGame find(String gameId) {
|
||||
MultiGame game = gameId == null ? null : games.get(gameId);
|
||||
if (game == null) throw new GameException(HttpStatus.NOT_FOUND, "Game not found!");
|
||||
return game;
|
||||
}
|
||||
|
||||
private Player player(MultiGame game, String token) {
|
||||
Player p = game.byToken(token);
|
||||
if (p == null) throw new GameException(HttpStatus.FORBIDDEN, "You are not a player of this game!");
|
||||
return p;
|
||||
}
|
||||
|
||||
private static GameException bad(String msg) {
|
||||
return new GameException(HttpStatus.BAD_REQUEST, msg);
|
||||
}
|
||||
|
||||
private static GameException conflict(String msg) {
|
||||
return new GameException(HttpStatus.CONFLICT, msg);
|
||||
}
|
||||
|
||||
private static long now() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package com.mmkilic.game.multi.service;
|
||||
|
||||
/**
|
||||
* Score rule (same for every multiplayer game type):
|
||||
*
|
||||
* <pre>
|
||||
* score = max(MIN_SCORE, 1000 x digits - 100 x turns - 2 x seconds) when the number was found
|
||||
* score = 0 when the number was not found
|
||||
* </pre>
|
||||
*
|
||||
* - digits : number length (3-10). Longer numbers are harder so they are worth more.
|
||||
* - turns : guesses the player needed (including the winning guess).
|
||||
* - seconds: thinking time of the player.
|
||||
* TIME_CHALLENGE -> time from game start until the number was found.
|
||||
* round based modes -> sum of each round's time from round start until the player's own guess
|
||||
* (time spent waiting for the rival is NOT counted).
|
||||
*
|
||||
* One turn costs as much as 50 seconds, so fewer turns matter most and time decides close games.
|
||||
* A solved number is always worth at least MIN_SCORE, so finding it always beats not finding it.
|
||||
* The higher score wins; equal scores are a draw.
|
||||
*/
|
||||
public final class ScoreCalculator {
|
||||
public static final int POINTS_PER_DIGIT = 1000;
|
||||
public static final int TURN_PENALTY = 100;
|
||||
public static final int SECOND_PENALTY = 2;
|
||||
public static final int MIN_SCORE = 100;
|
||||
|
||||
private ScoreCalculator() {}
|
||||
|
||||
public static int score(boolean found, int digits, int turns, long timeMs) {
|
||||
if (!found) return 0;
|
||||
long seconds = timeMs / 1000;
|
||||
long raw = (long) POINTS_PER_DIGIT * digits - (long) TURN_PENALTY * turns - SECOND_PENALTY * seconds;
|
||||
return (int) Math.max(MIN_SCORE, raw);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package com.mmkilic.game.service;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* Number selection rules shared by single player and multiplayer:
|
||||
* every digit 0-9 may be used at most once inside a number.
|
||||
*/
|
||||
public final class NumberRules {
|
||||
public static final int MIN_DIGITS = 3;
|
||||
public static final int MAX_DIGITS = 10;
|
||||
|
||||
private NumberRules() {}
|
||||
|
||||
public static boolean isValidDigitCount(int digitCount) {
|
||||
return digitCount >= MIN_DIGITS && digitCount <= MAX_DIGITS;
|
||||
}
|
||||
|
||||
/** Random number with {@code digitCount} distinct digits (a leading 0 is allowed). */
|
||||
public static String generate(int digitCount) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (result.length() < digitCount) {
|
||||
char candidate = (char) ('0' + ThreadLocalRandom.current().nextInt(0, 10));
|
||||
if (result.indexOf(String.valueOf(candidate)) == -1) result.append(candidate);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/** Same length as expected, digits only, and no digit repeated. */
|
||||
public static boolean isValidNumber(String number, int digitCount) {
|
||||
if (number == null || number.length() != digitCount) return false;
|
||||
Set<Character> seen = new HashSet<>();
|
||||
for (char c : number.toCharArray()) {
|
||||
if (c < '0' || c > '9' || !seen.add(c)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Returns {positive, negative}: right digit right place / right digit wrong place. */
|
||||
public static int[] check(String secret, String guess) {
|
||||
int positive = 0;
|
||||
int negative = 0;
|
||||
for (int i = 0; i < guess.length(); i++) {
|
||||
for (int j = 0; j < secret.length(); j++) {
|
||||
if (guess.charAt(i) == secret.charAt(j)) {
|
||||
if (i == j) positive++;
|
||||
else negative++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new int[] { positive, negative };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package com.mmkilic.game.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.mmkilic.game.entity.ResponseGuess;
|
||||
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
@Service
|
||||
public class SingleGameService {
|
||||
private static final String SECRET_ATTR = "secretNumber";
|
||||
private static final String ATTEMPTS_ATTR = "attempts";
|
||||
|
||||
public ResponseGuess start(HttpSession session, int digitCount) {
|
||||
if(digitCount > 10 || digitCount < 3) throw new RuntimeException("Wrong digitCount!");
|
||||
String secret = secretNumberGenerator(digitCount);
|
||||
session.setAttribute(SECRET_ATTR, secret);
|
||||
session.setAttribute(ATTEMPTS_ATTR, 0);
|
||||
return new ResponseGuess(0, "-", false, 0, 0);
|
||||
}
|
||||
|
||||
public ResponseGuess guess(HttpSession session, String guess) {
|
||||
String secret = (String) session.getAttribute(SECRET_ATTR);
|
||||
if (secret == null)
|
||||
throw new RuntimeException("Number cannot generated!");
|
||||
if(!guessVerification(secret, guess))
|
||||
throw new RuntimeException("Guess Number is not valid!");
|
||||
|
||||
var guessResult = guessChecker(secret, guess);
|
||||
|
||||
Integer attempts = (Integer) session.getAttribute(ATTEMPTS_ATTR);
|
||||
session.setAttribute(ATTEMPTS_ATTR, attempts + 1);
|
||||
|
||||
boolean win = secret.length() == guessResult.get("positive");
|
||||
|
||||
if(win) session.invalidate();
|
||||
|
||||
return new ResponseGuess(
|
||||
attempts + 1,
|
||||
guess,
|
||||
win,
|
||||
guessResult.get("positive"),
|
||||
guessResult.get("negative")
|
||||
);
|
||||
}
|
||||
|
||||
private String secretNumberGenerator(int digitCount) {
|
||||
String result = "";
|
||||
|
||||
main:
|
||||
do {
|
||||
String potential = String.valueOf(ThreadLocalRandom.current().nextInt(0, 10));
|
||||
for (char number: result.toCharArray()) {
|
||||
if(potential.equals(String.valueOf(number)))
|
||||
continue main;
|
||||
}
|
||||
result += potential;
|
||||
} while(result.length() != digitCount);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean guessVerification(String secret, String guess) {
|
||||
if(secret.length() != guess.length()) return false;
|
||||
|
||||
List<Character> verifiedNumberList = new ArrayList<>();
|
||||
|
||||
for (char gNumber : guess.toCharArray()) {
|
||||
for (char verifiedNumber : verifiedNumberList) {
|
||||
if(gNumber == verifiedNumber) return false;
|
||||
}
|
||||
verifiedNumberList.add(gNumber);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private Map<String, Integer> guessChecker(String secret, String guess){
|
||||
Map<String, Integer> result = new HashMap<>();
|
||||
|
||||
int positive = 0;
|
||||
int negative = 0;
|
||||
|
||||
for (int i = 0; i < guess.length(); i++) {
|
||||
for (int j = 0; j < secret.length(); j++) {
|
||||
if(guess.charAt(i) == secret.charAt(j)) {
|
||||
if(i == j) positive++;
|
||||
else negative++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.put("positive", positive);
|
||||
result.put("negative", negative);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
spring.application.name=ApiMastermind
|
||||
server.port=8080
|
||||
server.servlet.context-path=/api-mastermind
|
||||
# Multiplayer (in-memory, no database)
|
||||
# A player that has not polled the game for this long is treated as having left.
|
||||
multiplayer.player-timeout-ms=20000
|
||||
# Closed games stay in the lobby list for this long.
|
||||
multiplayer.closed-retention-ms=300000
|
||||
multiplayer.sweep-interval-ms=2000
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.mmkilic.game.ApiNumberFinder;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class ApiNumberFinderApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
NEXT_PUBLIC_BASE_PATH=
|
||||
NEXT_PUBLIC_API_URL=http://localhost:8080/api-mastermind
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
NEXT_PUBLIC_BASE_PATH=/mastermind
|
||||
NEXT_PUBLIC_API_URL=https://api.mmkilic.com/api-mastermind
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
# build stage
|
||||
FROM node:20-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build && npm run export
|
||||
|
||||
# production stage
|
||||
FROM nginx:stable-alpine AS production
|
||||
COPY --from=builder /app/out /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
# mastermind
|
||||
Masterind Online Game
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
|
|
@ -0,0 +1,35 @@
|
|||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* custom tweaks */
|
||||
html,body{
|
||||
@apply h-full bg-neutral-900 text-white;
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import "./globals.css";
|
||||
|
||||
export const metadata = {
|
||||
title: "Number Finder Game",
|
||||
description: "Simple number finder built with Next.js",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="min-h-full flex flex-col items-center justify-center font-sans px-2 sm:px-4 md:px-8">
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
'use client';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
const KEYPAD = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
||||
|
||||
/**
|
||||
* Digit entry with the single-player rule: every digit can be used only once.
|
||||
* Supports clicks and the keyboard (0-9, Backspace, Enter).
|
||||
*/
|
||||
export default function NumberPad({ digitNumber, onSubmit, disabled = false, busy = false, submitLabel = 'Enter' }) {
|
||||
const [digits, setDigits] = useState(() => Array(digitNumber).fill(''));
|
||||
const used = new Set(digits.filter((d) => d !== ''));
|
||||
const complete = digits.every((d) => d !== '');
|
||||
const locked = disabled || busy;
|
||||
|
||||
const append = (val) => {
|
||||
if (locked) return;
|
||||
setDigits((cur) => {
|
||||
const s = String(val);
|
||||
const idx = cur.indexOf('');
|
||||
if (idx === -1 || cur.includes(s)) return cur;
|
||||
const next = [...cur];
|
||||
next[idx] = s;
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const remove = () => {
|
||||
if (locked) return;
|
||||
setDigits((cur) => {
|
||||
const next = [...cur];
|
||||
for (let i = next.length - 1; i >= 0; i--) {
|
||||
if (next[i] !== '') {
|
||||
next[i] = '';
|
||||
break;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
if (locked || !complete) return;
|
||||
const ok = await onSubmit(digits.join(''));
|
||||
if (ok !== false) setDigits(Array(digitNumber).fill(''));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e) => {
|
||||
if (e.target instanceof HTMLInputElement) return;
|
||||
if (/^[0-9]$/.test(e.key)) append(e.key);
|
||||
else if (e.key === 'Backspace') remove();
|
||||
else if (e.key === 'Enter') submit();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-6 w-full">
|
||||
<div className="w-full overflow-x-auto">
|
||||
<div className="flex gap-2 sm:gap-3 justify-center min-w-max px-1">
|
||||
{digits.map((d, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-9 h-12 sm:w-12 sm:h-16 flex items-center justify-center text-xl sm:text-3xl font-bold bg-neutral-800 rounded-lg border border-neutral-700"
|
||||
>
|
||||
{d}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3 w-56">
|
||||
{KEYPAD.map((n) => {
|
||||
const off = used.has(String(n)) || locked;
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => append(n)}
|
||||
disabled={off}
|
||||
className={`py-3 rounded-lg text-xl font-semibold transition ${
|
||||
off ? 'bg-neutral-700 opacity-40 cursor-not-allowed' : 'bg-neutral-600 hover:bg-neutral-500'
|
||||
}`}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
onClick={remove}
|
||||
disabled={used.size === 0 || locked}
|
||||
className="py-3 rounded-lg text-xl font-semibold bg-rose-600 hover:bg-rose-700 transition disabled:opacity-40"
|
||||
>
|
||||
⌫
|
||||
</button>
|
||||
<button
|
||||
onClick={submit}
|
||||
disabled={!complete || locked}
|
||||
className="col-span-2 py-3 rounded-lg text-xl font-semibold bg-emerald-600 hover:bg-emerald-700 transition disabled:opacity-40"
|
||||
>
|
||||
{busy ? '...' : submitLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
'use client';
|
||||
|
||||
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
|
||||
const GAMES = `${apiURL}/multi/games`;
|
||||
const SESSION_KEY = 'mastermind.multi';
|
||||
|
||||
export const GAME_TYPES = {
|
||||
AUTO_GUESSTURES: {
|
||||
label: 'Auto Guesstures',
|
||||
short: 'Auto',
|
||||
description:
|
||||
'The game picks a different number for each player. Rounds are played together and you see both results after every round.',
|
||||
},
|
||||
PLAYER_GUESSTURES: {
|
||||
label: 'Player Guesstures',
|
||||
short: 'Player',
|
||||
description:
|
||||
'Each player chooses the number the rival has to find. Then rounds are played together like Auto Guesstures.',
|
||||
},
|
||||
TIME_CHALLENGE: {
|
||||
label: 'Time Challenge',
|
||||
short: 'Time',
|
||||
description:
|
||||
'Both players find the same number, independently and against the clock. Rival guesses stay hidden. Best score wins.',
|
||||
},
|
||||
};
|
||||
|
||||
async function call(path, { method = 'GET', token, body } = {}) {
|
||||
const headers = {};
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (token) headers['X-Player-Token'] = token;
|
||||
|
||||
const res = await fetch(`${GAMES}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let message = '';
|
||||
try {
|
||||
message = (await res.json()).message;
|
||||
} catch {}
|
||||
const err = new Error(message || `Server error (HTTP ${res.status})`);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const listGames = () => call('');
|
||||
export const createGame = (name, digits, type) =>
|
||||
call('', { method: 'POST', body: { name, digits, type } });
|
||||
export const joinGame = (id) => call(`/${id}/join`, { method: 'POST' });
|
||||
export const getState = (id, token) => call(`/${id}/state`, { token });
|
||||
export const sendGuess = (id, token, number) =>
|
||||
call(`/${id}/guess`, { method: 'POST', token, body: { number } });
|
||||
export const chooseSecret = (id, token, number) =>
|
||||
call(`/${id}/secret`, { method: 'POST', token, body: { number } });
|
||||
export const leaveGame = (id, token) =>
|
||||
call(`/${id}/leave`, { method: 'POST', token }).catch(() => {});
|
||||
|
||||
/** Fire-and-forget leave that survives page close/refresh. */
|
||||
export function leaveGameBeacon(id, token) {
|
||||
const url = `${GAMES}/${id}/leave?token=${encodeURIComponent(token)}`;
|
||||
try {
|
||||
if (navigator.sendBeacon && navigator.sendBeacon(url)) return;
|
||||
} catch {}
|
||||
fetch(url, { method: 'POST', keepalive: true }).catch(() => {});
|
||||
}
|
||||
|
||||
// The player token lives in sessionStorage so every browser tab is a separate player.
|
||||
export function saveSession(gameId, token) {
|
||||
try {
|
||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadSession() {
|
||||
try {
|
||||
return JSON.parse(sessionStorage.getItem(SESSION_KEY)) || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
try {
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function formatTime(ms) {
|
||||
if (ms == null) return '-';
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const m = Math.floor(total / 60);
|
||||
const s = total % 60;
|
||||
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
|
||||
}
|
||||
|
|
@ -0,0 +1,207 @@
|
|||
'use client';
|
||||
import { useCallback, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { GAME_TYPES, createGame, joinGame, listGames, saveSession } from './api';
|
||||
import useTicker from './useTicker';
|
||||
|
||||
const STATUS_STYLE = {
|
||||
WAITING: 'bg-amber-500/20 text-amber-300 border-amber-500/40',
|
||||
PLAYING: 'bg-blue-500/20 text-blue-300 border-blue-500/40',
|
||||
CLOSED: 'bg-neutral-700/40 text-neutral-400 border-neutral-600',
|
||||
};
|
||||
|
||||
export default function MultiplayerLobby() {
|
||||
const router = useRouter();
|
||||
const [games, setGames] = useState(null);
|
||||
const [listError, setListError] = useState('');
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [joining, setJoining] = useState(null);
|
||||
const [joinError, setJoinError] = useState('');
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setGames(await listGames());
|
||||
setListError('');
|
||||
} catch (err) {
|
||||
setListError(err.message || 'Cannot reach the server');
|
||||
}
|
||||
}, []);
|
||||
|
||||
useTicker(refresh, 3000);
|
||||
|
||||
const enterGame = (res) => {
|
||||
saveSession(res.gameId, res.playerToken);
|
||||
router.push('/multiplayer/play');
|
||||
};
|
||||
|
||||
const handleJoin = async (id) => {
|
||||
setJoining(id);
|
||||
setJoinError('');
|
||||
try {
|
||||
enterGame(await joinGame(id));
|
||||
} catch (err) {
|
||||
setJoinError(err.message);
|
||||
refresh();
|
||||
} finally {
|
||||
setJoining(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="h-screen w-full flex flex-col">
|
||||
<header className="p-3 sm:p-4 text-center text-2xl sm:text-3xl font-bold bg-neutral-800 shadow-lg relative">
|
||||
<Link href="/" className="absolute left-3 top-1/2 -translate-y-1/2 text-sm font-normal text-blue-400 hover:text-blue-200">
|
||||
← Home
|
||||
</Link>
|
||||
Multiplayer
|
||||
</header>
|
||||
|
||||
<section className="flex-grow w-full max-w-3xl mx-auto p-4 sm:p-6 flex flex-col gap-4 overflow-y-auto">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<h2 className="text-xl font-semibold">Games</h2>
|
||||
<button
|
||||
onClick={() => setShowCreate(true)}
|
||||
className="px-4 py-2 rounded-lg bg-purple-600 hover:bg-purple-700 transition font-semibold"
|
||||
>
|
||||
+ Create New Game
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{listError && <p className="text-rose-400 text-sm">{listError}</p>}
|
||||
{joinError && <p className="text-rose-400 text-sm">{joinError}</p>}
|
||||
|
||||
{games === null && !listError && <p className="opacity-60">Loading…</p>}
|
||||
{games?.length === 0 && (
|
||||
<p className="opacity-60 text-center py-10">No games yet. Create one and invite a friend!</p>
|
||||
)}
|
||||
|
||||
<ul className="flex flex-col gap-2">
|
||||
{games?.map((g) => (
|
||||
<li
|
||||
key={g.id}
|
||||
className={`flex items-center gap-3 p-3 sm:p-4 rounded-lg bg-neutral-800 border border-neutral-700 ${
|
||||
g.status === 'CLOSED' ? 'opacity-60' : ''
|
||||
}`}
|
||||
>
|
||||
<div className="flex-grow min-w-0">
|
||||
<p className="font-semibold truncate">{g.name}</p>
|
||||
<p className="text-sm opacity-70">
|
||||
{GAME_TYPES[g.type]?.label} · {g.digits} digits · {g.players}/2 players
|
||||
</p>
|
||||
</div>
|
||||
<span className={`text-xs px-2 py-1 rounded-full border ${STATUS_STYLE[g.status]}`}>
|
||||
{g.status.toLowerCase()}
|
||||
</span>
|
||||
{g.status === 'WAITING' && (
|
||||
<button
|
||||
onClick={() => handleJoin(g.id)}
|
||||
disabled={joining !== null}
|
||||
className="px-4 py-2 rounded bg-emerald-600 hover:bg-emerald-700 disabled:opacity-40 text-sm font-semibold"
|
||||
>
|
||||
{joining === g.id ? '...' : 'Join'}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{showCreate && <CreateGameModal onClose={() => setShowCreate(false)} onCreated={enterGame} />}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateGameModal({ onClose, onCreated }) {
|
||||
const [name, setName] = useState('');
|
||||
const [digits, setDigits] = useState('4');
|
||||
const [type, setType] = useState('AUTO_GUESSTURES');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const digitNum = parseInt(digits, 10);
|
||||
const digitsValid = !isNaN(digitNum) && digitNum >= 3 && digitNum <= 10;
|
||||
const valid = name.trim() !== '' && digitsValid;
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!valid) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
onCreated(await createGame(name.trim(), digitNum, type));
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 px-2" onClick={onClose}>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-neutral-800 rounded-xl p-4 sm:p-6 w-full max-w-md flex flex-col gap-4"
|
||||
>
|
||||
<h2 className="text-xl font-semibold text-center">Create New Game</h2>
|
||||
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-sm opacity-80">Game Name (unique)</span>
|
||||
<input
|
||||
autoFocus
|
||||
maxLength={30}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="rounded p-2 bg-neutral-700 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="flex flex-col gap-1">
|
||||
<span className="text-sm opacity-80">Number Limit [3-10 digits]</span>
|
||||
<input
|
||||
type="number"
|
||||
min={3}
|
||||
max={10}
|
||||
value={digits}
|
||||
onChange={(e) => setDigits(e.target.value)}
|
||||
className="rounded p-2 bg-neutral-700 focus:outline-none"
|
||||
/>
|
||||
{!digitsValid && digits !== '' && <span className="text-xs text-rose-400">Choose between 3 and 10.</span>}
|
||||
</label>
|
||||
|
||||
<fieldset className="flex flex-col gap-2">
|
||||
<legend className="text-sm opacity-80 mb-1">Game Type</legend>
|
||||
{Object.entries(GAME_TYPES).map(([key, t]) => (
|
||||
<label
|
||||
key={key}
|
||||
className={`flex gap-3 p-3 rounded-lg border cursor-pointer ${
|
||||
type === key ? 'border-purple-500 bg-purple-500/10' : 'border-neutral-700'
|
||||
}`}
|
||||
>
|
||||
<input type="radio" name="type" value={key} checked={type === key} onChange={() => setType(key)} />
|
||||
<span>
|
||||
<span className="font-semibold">{t.label}</span>
|
||||
<span className="block text-xs opacity-70">{t.description}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
{error && <p className="text-rose-400 text-sm">{error}</p>}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button type="button" onClick={onClose} className="flex-1 py-2 rounded bg-neutral-600 hover:bg-neutral-500">
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!valid || loading}
|
||||
className="flex-1 py-2 rounded bg-purple-600 hover:bg-purple-700 disabled:opacity-40 font-semibold"
|
||||
>
|
||||
{loading ? '...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,358 @@
|
|||
'use client';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
GAME_TYPES,
|
||||
chooseSecret,
|
||||
clearSession,
|
||||
formatTime,
|
||||
getState,
|
||||
leaveGame,
|
||||
leaveGameBeacon,
|
||||
loadSession,
|
||||
sendGuess,
|
||||
} from '../api';
|
||||
import NumberPad from '../NumberPad';
|
||||
import useTicker from '../useTicker';
|
||||
|
||||
// Leaving on unmount is deferred so React StrictMode's mount → unmount → mount (dev) does not end the game.
|
||||
let pendingLeave = null;
|
||||
|
||||
export default function MultiplayerPlayPage() {
|
||||
const router = useRouter();
|
||||
const [session, setSession] = useState(null);
|
||||
const [state, setState] = useState(null);
|
||||
const [receivedAt, setReceivedAt] = useState(0);
|
||||
const [fatal, setFatal] = useState('');
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [, setClock] = useState(0);
|
||||
|
||||
const seq = useRef(0);
|
||||
const applied = useRef(0);
|
||||
const activeRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const s = loadSession();
|
||||
if (!s) router.replace('/multiplayer');
|
||||
else setSession(s);
|
||||
}, [router]);
|
||||
|
||||
// Ignore responses that are older than the latest applied one (poll vs. guess races).
|
||||
const apply = (id, data) => {
|
||||
if (id < applied.current) return;
|
||||
applied.current = id;
|
||||
setState(data);
|
||||
setReceivedAt(Date.now());
|
||||
activeRef.current = data.stage !== 'FINISHED';
|
||||
};
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
if (!session) return;
|
||||
const id = ++seq.current;
|
||||
try {
|
||||
apply(id, await getState(session.gameId, session.token));
|
||||
} catch (err) {
|
||||
if (err.status === 404 || err.status === 403) {
|
||||
activeRef.current = false;
|
||||
clearSession();
|
||||
setFatal('This game is no longer available.');
|
||||
}
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const finished = state?.stage === 'FINISHED';
|
||||
useTicker(poll, 1000, !!session && !finished && !fatal);
|
||||
|
||||
// Local clock for the timer display.
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setClock((c) => c + 1), 500);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
|
||||
// Closing / refreshing the tab or navigating away leaves the game.
|
||||
useEffect(() => {
|
||||
if (!session) return;
|
||||
clearTimeout(pendingLeave);
|
||||
const onPageHide = () => {
|
||||
if (activeRef.current) leaveGameBeacon(session.gameId, session.token);
|
||||
};
|
||||
const onBeforeUnload = (e) => {
|
||||
if (activeRef.current) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('pagehide', onPageHide);
|
||||
window.addEventListener('beforeunload', onBeforeUnload);
|
||||
return () => {
|
||||
window.removeEventListener('pagehide', onPageHide);
|
||||
window.removeEventListener('beforeunload', onBeforeUnload);
|
||||
if (activeRef.current) {
|
||||
pendingLeave = setTimeout(() => leaveGameBeacon(session.gameId, session.token), 300);
|
||||
}
|
||||
};
|
||||
}, [session]);
|
||||
|
||||
const runAction = async (fn) => {
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
const id = ++seq.current;
|
||||
try {
|
||||
apply(id, await fn());
|
||||
return true;
|
||||
} catch (err) {
|
||||
setActionError(err.message);
|
||||
poll();
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
|
||||
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
|
||||
|
||||
const handleLeave = async () => {
|
||||
if (activeRef.current) {
|
||||
if (!window.confirm('Leaving ends the game for both players. Leave?')) return;
|
||||
activeRef.current = false;
|
||||
await leaveGame(session.gameId, session.token);
|
||||
}
|
||||
clearSession();
|
||||
router.push('/multiplayer');
|
||||
};
|
||||
|
||||
if (fatal) {
|
||||
return (
|
||||
<CenterMessage>
|
||||
<p className="text-xl">{fatal}</p>
|
||||
<button onClick={() => router.push('/multiplayer')} className="px-4 py-2 rounded bg-purple-600 hover:bg-purple-700">
|
||||
Back to lobby
|
||||
</button>
|
||||
</CenterMessage>
|
||||
);
|
||||
}
|
||||
if (!state) return <CenterMessage><p className="opacity-70">Loading game…</p></CenterMessage>;
|
||||
|
||||
const type = GAME_TYPES[state.type];
|
||||
const roundBased = state.type !== 'TIME_CHALLENGE';
|
||||
const elapsed = state.stage === 'PLAYING' ? state.elapsedMs + (Date.now() - receivedAt) : state.elapsedMs;
|
||||
|
||||
return (
|
||||
<main className="h-screen w-full flex flex-col">
|
||||
<header className="p-3 sm:p-4 bg-neutral-800 shadow-lg flex items-center gap-3">
|
||||
<button onClick={handleLeave} className="px-3 py-2 bg-rose-700 hover:bg-rose-800 rounded text-sm shrink-0">
|
||||
{finished ? '← Lobby' : 'Leave Game'}
|
||||
</button>
|
||||
<div className="flex-grow text-center min-w-0">
|
||||
<h1 className="text-xl sm:text-2xl font-bold truncate">{state.name}</h1>
|
||||
<p className="text-xs sm:text-sm opacity-70">
|
||||
{type?.label} · {state.digits} digits
|
||||
</p>
|
||||
</div>
|
||||
<div className="shrink-0 flex flex-col items-end gap-1 text-sm">
|
||||
{(state.stage === 'PLAYING' || finished) && state.elapsedMs > 0 && (
|
||||
<span className="bg-neutral-900 px-3 py-1 rounded-full border border-neutral-700 font-mono">
|
||||
⏱ {formatTime(elapsed)}
|
||||
</span>
|
||||
)}
|
||||
{roundBased && state.stage === 'PLAYING' && (
|
||||
<span className="bg-neutral-900 px-3 py-1 rounded-full border border-neutral-700">Round {state.round}</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="flex-grow flex flex-col md:flex-row min-h-0">
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-6 gap-6 overflow-y-auto">
|
||||
{state.stage === 'WAITING' && <WaitingPanel state={state} />}
|
||||
{state.stage === 'SETUP' && (
|
||||
<SetupPanel state={state} busy={busy} onSubmit={handleSecret} />
|
||||
)}
|
||||
{state.stage === 'PLAYING' && (
|
||||
<PlayingPanel state={state} busy={busy} onSubmit={handleGuess} />
|
||||
)}
|
||||
{finished && <ResultPanel state={state} onBack={handleLeave} />}
|
||||
{actionError && <p className="text-rose-400 text-sm">{actionError}</p>}
|
||||
</div>
|
||||
|
||||
{(state.stage === 'PLAYING' || finished) && (
|
||||
<aside className="md:w-[28rem] grid grid-cols-2 gap-4 p-4 sm:p-6 border-t md:border-t-0 md:border-l border-neutral-800 overflow-y-auto max-h-[35vh] md:max-h-none">
|
||||
<History title="Your guesses" history={state.you.history} />
|
||||
{roundBased || finished ? (
|
||||
<History title="Rival's guesses" history={state.rival?.history || []} />
|
||||
) : (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3">Rival</h3>
|
||||
<p className="text-sm opacity-70 mb-2">Rival guesses are hidden in Time Challenge.</p>
|
||||
<p>Attempts: {state.rival?.attempts ?? 0}</p>
|
||||
<p className={state.rival?.found ? 'text-emerald-400' : 'opacity-70'}>
|
||||
{state.rival?.found ? 'Found the number!' : 'Still searching…'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function CenterMessage({ children }) {
|
||||
return <main className="h-screen w-full flex flex-col items-center justify-center gap-4 p-6 text-center">{children}</main>;
|
||||
}
|
||||
|
||||
function WaitingPanel({ state }) {
|
||||
return (
|
||||
<div className="text-center flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-full border-4 border-purple-500 border-t-transparent animate-spin" />
|
||||
<p className="text-xl font-semibold">Waiting for a rival to join…</p>
|
||||
<p className="opacity-70 max-w-sm">
|
||||
Your friend can join <span className="font-semibold">“{state.name}”</span> from the Multiplayer lobby. Keep this
|
||||
page open: leaving closes the game.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupPanel({ state, busy, onSubmit }) {
|
||||
const { you, rival } = state;
|
||||
return (
|
||||
<>
|
||||
<div className="text-center">
|
||||
<p className="text-xl font-semibold">Choose a {state.digits}-digit number for your rival</p>
|
||||
<p className="text-sm opacity-70">Each digit can be used only once.</p>
|
||||
</div>
|
||||
<NumberPad
|
||||
digitNumber={state.digits}
|
||||
onSubmit={onSubmit}
|
||||
busy={busy}
|
||||
submitLabel={you.secretChosen ? 'Change Number' : 'Set Number'}
|
||||
/>
|
||||
<div className="text-center text-sm">
|
||||
{you.secretChosen && (
|
||||
<p>
|
||||
Your rival will search for <span className="font-mono font-bold text-purple-300">{you.secretForRival}</span>
|
||||
</p>
|
||||
)}
|
||||
<p className={rival?.secretChosen ? 'text-emerald-400' : 'opacity-70 animate-pulse'}>
|
||||
{rival?.secretChosen ? 'Rival has chosen your number.' : 'Rival is choosing your number…'}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function PlayingPanel({ state, busy, onSubmit }) {
|
||||
const { you, rival } = state;
|
||||
const roundBased = state.type !== 'TIME_CHALLENGE';
|
||||
|
||||
let status;
|
||||
if (roundBased) {
|
||||
if (state.waitingForRival) status = <span className="animate-pulse">Waiting for your rival's guess…</span>;
|
||||
else if (rival && rival.attempts >= state.round) status = <span className="text-amber-300">Your rival has guessed. Your turn!</span>;
|
||||
else status = 'Make your guess.';
|
||||
} else if (you.found) {
|
||||
status = (
|
||||
<span className="text-emerald-400">
|
||||
You found it in {you.attempts} turns ({formatTime(you.timeMs)}), score {you.score}. Waiting for your rival to
|
||||
finish…
|
||||
</span>
|
||||
);
|
||||
} else {
|
||||
status = 'Find the number as fast as you can!';
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-center text-lg">{status}</p>
|
||||
{!(state.type === 'TIME_CHALLENGE' && you.found) && (
|
||||
<NumberPad digitNumber={state.digits} onSubmit={onSubmit} busy={busy} disabled={!state.canGuess} />
|
||||
)}
|
||||
{state.type === 'PLAYER_GUESSTURES' && you.secretForRival && (
|
||||
<p className="text-sm opacity-70">
|
||||
Your rival is searching for <span className="font-mono">{you.secretForRival}</span>
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultPanel({ state, onBack }) {
|
||||
const { you, rival, outcome, endReason, youLeft } = state;
|
||||
const banner = {
|
||||
WIN: ['You Won!', 'text-emerald-400'],
|
||||
LOSE: ['You Lost', 'text-rose-400'],
|
||||
DRAW: ['Draw', 'text-amber-300'],
|
||||
}[outcome] || ['Game Closed', 'text-neutral-300'];
|
||||
|
||||
let reason = '';
|
||||
if (endReason === 'PLAYER_LEFT') reason = youLeft ? 'You left the game.' : 'Your rival left the game.';
|
||||
else if (state.type === 'TIME_CHALLENGE') reason = 'Both players found the number.';
|
||||
else reason = you.found && rival?.found ? 'Both players found their number in the same round.' : 'A number was found.';
|
||||
|
||||
const rows = [
|
||||
['Number to find', (p) => <span className="font-mono">{p?.numberToFind ?? '-'}</span>],
|
||||
['Found', (p) => (p?.found ? '✔' : '✘')],
|
||||
['Turns', (p) => p?.attempts ?? '-'],
|
||||
['Time', (p) => formatTime(p?.timeMs)],
|
||||
['Score', (p) => <span className="font-bold">{p?.score ?? '-'}</span>],
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 w-full max-w-md">
|
||||
<p className={`text-3xl font-bold ${banner[1]}`}>{banner[0]}</p>
|
||||
<p className="opacity-80">{reason}</p>
|
||||
{rival && (
|
||||
<table className="w-full text-center border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-neutral-700">
|
||||
<th />
|
||||
<th className="py-2">You</th>
|
||||
<th className="py-2">Rival</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(([label, render]) => (
|
||||
<tr key={label} className="border-b border-neutral-800">
|
||||
<td className="py-2 text-left opacity-70">{label}</td>
|
||||
<td>{render(you)}</td>
|
||||
<td>{render(rival)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<p className="text-xs opacity-60 text-center">
|
||||
Score = 1000 × digits − 100 × turns − 2 × seconds (min 100 if found, 0 if not found).
|
||||
</p>
|
||||
<button onClick={onBack} className="px-6 py-2 rounded bg-purple-600 hover:bg-purple-700 font-semibold">
|
||||
Back to lobby
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function History({ title, history }) {
|
||||
const items = [...history].reverse();
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
||||
{items.length === 0 && <p className="opacity-60 text-sm">No guesses yet.</p>}
|
||||
{items.map((h) => (
|
||||
<div key={h.turn} className="py-2 px-3 mb-2 bg-neutral-800 rounded border border-neutral-700 font-mono text-sm sm:text-base">
|
||||
<span className="opacity-50 mr-2">{h.turn}.</span>
|
||||
{h.guess}
|
||||
{h.positive === null ? (
|
||||
<span className="opacity-60"> …</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-emerald-400"> +{h.positive}</span>
|
||||
<span className="text-rose-400"> -{h.negative}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
'use client';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
/**
|
||||
* Calls `callback` every `intervalMs`. The timer runs in a Web Worker because browsers
|
||||
* heavily throttle timers of background tabs; the poll doubles as the server heartbeat,
|
||||
* so a throttled tab would otherwise be treated as "left".
|
||||
*/
|
||||
export default function useTicker(callback, intervalMs, enabled = true) {
|
||||
const saved = useRef(callback);
|
||||
useEffect(() => {
|
||||
saved.current = callback;
|
||||
}, [callback]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const tick = () => saved.current();
|
||||
tick();
|
||||
|
||||
let worker = null;
|
||||
let url = null;
|
||||
let timer = null;
|
||||
try {
|
||||
const src = `setInterval(() => postMessage(0), ${intervalMs});`;
|
||||
url = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
|
||||
worker = new Worker(url);
|
||||
worker.onmessage = tick;
|
||||
} catch {
|
||||
timer = setInterval(tick, intervalMs);
|
||||
}
|
||||
return () => {
|
||||
if (worker) worker.terminate();
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
if (timer) clearInterval(timer);
|
||||
};
|
||||
}, [intervalMs, enabled]);
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import Link from 'next/link';
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<main className="flex flex-col items-center gap-8 sm:gap-10 p-4 sm:p-8 h-screen w-full max-w-2xl text-center justify-center">
|
||||
<h1 className="text-3xl sm:text-4xl font-bold mt-4">Welcome to Mastermind Game</h1>
|
||||
|
||||
<div className="flex flex-col gap-4 sm:gap-6 w-full text-lg sm:text-2xl">
|
||||
<Link
|
||||
href="/single-player"
|
||||
className="block py-3 sm:py-4 rounded-lg bg-blue-600 hover:bg-blue-700 transition"
|
||||
>
|
||||
Single Player
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
href="/multiplayer"
|
||||
className="block py-3 sm:py-4 rounded-lg bg-purple-600 hover:bg-purple-700 transition"
|
||||
>
|
||||
Multiplayer
|
||||
</Link>
|
||||
</div>
|
||||
<footer className="absolute bottom-4 left-0 w-full text-center text-sm text-neutral-500">
|
||||
© 2025 Mehmet Kılıç. All rights reserved. V0.2
|
||||
</footer>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
|
||||
|
||||
export default function NumberFinder({ digitNumber, initialAttempts = 0 }) {
|
||||
const router = useRouter();
|
||||
const emptyArray = () => Array(digitNumber).fill('');
|
||||
|
||||
const [digits, setDigits] = useState(emptyArray());
|
||||
const [disabledDigits, setDisabledDigits] = useState(new Set());
|
||||
const [history, setHistory] = useState([]);
|
||||
const [attempts, setAttempts] = useState(initialAttempts);
|
||||
const [win, setWin] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const appendDigit = (val) => {
|
||||
if (disabledDigits.has(val) || win) return;
|
||||
const firstEmpty = digits.indexOf('');
|
||||
if (firstEmpty !== -1) {
|
||||
const next = [...digits];
|
||||
next[firstEmpty] = val;
|
||||
setDigits(next);
|
||||
setDisabledDigits(new Set(disabledDigits).add(val));
|
||||
}
|
||||
};
|
||||
|
||||
const deleteDigit = () => {
|
||||
if (win) return;
|
||||
const index = [...digits].lastIndexOf(digits.findLast((d) => d !== ''));
|
||||
if (index === -1) return;
|
||||
const next = [...digits];
|
||||
const removed = next[index];
|
||||
next[index] = '';
|
||||
setDigits(next);
|
||||
|
||||
const nextDisabled = new Set(disabledDigits);
|
||||
nextDisabled.delete(removed);
|
||||
setDisabledDigits(nextDisabled);
|
||||
};
|
||||
|
||||
const resetForNewGuess = () => {
|
||||
setDigits(emptyArray());
|
||||
setDisabledDigits(new Set());
|
||||
};
|
||||
|
||||
const handleEnter = async () => {
|
||||
if (digits.some((d) => d === '') || win) return;
|
||||
const guess = digits.join('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`${apiURL}/guess?guess=${guess}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
//body: JSON.stringify({ guess }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
setAttempts(data.attempts);
|
||||
setWin(data.win);
|
||||
setHistory([
|
||||
{ guess, positive: data.positive, negative: data.negative },
|
||||
...history,
|
||||
]);
|
||||
resetForNewGuess();
|
||||
} catch (err) {
|
||||
console.error('Guess error', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const keypad = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
||||
|
||||
return (
|
||||
<section className="flex-grow flex flex-col md:flex-row h-full">
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-6 gap-8 border-b md:border-b-0 md:border-r border-neutral-800 relative">
|
||||
<div className="absolute top-4 left-4">
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="px-4 py-2 bg-rose-700 hover:bg-rose-800 rounded text-sm"
|
||||
>
|
||||
Abort Game
|
||||
</button>
|
||||
</div>
|
||||
<span className="absolute top-4 right-4 text-sm bg-neutral-800 px-3 py-1 rounded-full border border-neutral-700">
|
||||
Attempt: {attempts}
|
||||
</span>
|
||||
|
||||
<div className="w-full overflow-x-auto">
|
||||
<div className="flex gap-2 sm:gap-4 justify-center min-w-max px-1">
|
||||
{digits.map((d, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="w-9 h-12 sm:w-14 sm:h-20 flex items-center justify-center text-xl sm:text-3xl font-bold bg-neutral-800 rounded-lg border border-neutral-700"
|
||||
>
|
||||
{d}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 w-60">
|
||||
{keypad.map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => appendDigit(n)}
|
||||
disabled={disabledDigits.has(n) || win}
|
||||
className={`py-4 rounded-lg text-xl font-semibold transition ${
|
||||
disabledDigits.has(n) || win
|
||||
? 'bg-neutral-700 opacity-40 cursor-not-allowed'
|
||||
: 'bg-neutral-600 hover:bg-neutral-500'
|
||||
}`}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
onClick={deleteDigit}
|
||||
disabled={digits.every((d) => d === '') || win}
|
||||
className="py-4 rounded-lg text-xl font-semibold bg-rose-600 hover:bg-rose-700 transition"
|
||||
>
|
||||
⌫
|
||||
</button>
|
||||
<button
|
||||
onClick={handleEnter}
|
||||
disabled={digits.some((d) => d === '') || win || loading}
|
||||
className="col-span-2 py-4 rounded-lg text-xl font-semibold bg-emerald-600 hover:bg-emerald-700 transition disabled:opacity-40"
|
||||
>
|
||||
{loading ? '...' : 'Enter'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{win && (
|
||||
<p className="mt-6 text-2xl font-bold text-emerald-400 animate-bounce">
|
||||
Congratulations You Won!
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="md:w-96 p-6 overflow-y-auto border-t md:border-t-0 md:border-l border-neutral-800 max-h-[25vh] md:max-h-none">
|
||||
<h3 className="text-xl font-semibold mb-4">History</h3>
|
||||
{history.length === 0 && <p className="opacity-60">No guesses yet.</p>}
|
||||
{history.map((h, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="py-2 px-4 mb-2 bg-neutral-800 rounded border border-neutral-700"
|
||||
>
|
||||
{h.guess}
|
||||
<span className="text-emerald-400"> +{h.positive}</span>
|
||||
<span className="text-rose-400"> -{h.negative}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import NumberFinder from './NumberFinder';
|
||||
|
||||
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
|
||||
|
||||
export default function SinglePlayerPage() {
|
||||
const router = useRouter();
|
||||
const [digitInput, setDigitInput] = useState('');
|
||||
const [game, setGame] = useState(null); // {digitNumber, attempts}
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleStart = async () => {
|
||||
const num = parseInt(digitInput, 10);
|
||||
if (isNaN(num) || num <= 0) return;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${apiURL}/start?digitNumber=${num}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) throw new Error(`Sunucu hatası (HTTP ${res.status})`);
|
||||
const data = await res.json();
|
||||
if (typeof data.attempts !== 'number') throw new Error('Geçersiz yanıt');
|
||||
|
||||
setGame({ digitNumber: num, attempts: data.attempts });
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
console.error(err);
|
||||
setTimeout(() => router.push('/'), 2500);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="h-screen w-full flex flex-col relative">
|
||||
<header className="p-3 sm:p-4 text-center text-2xl sm:text-3xl font-bold bg-neutral-800 shadow-lg">
|
||||
Single Player Mode
|
||||
</header>
|
||||
|
||||
{game ? (
|
||||
<NumberFinder digitNumber={game.digitNumber} initialAttempts={game.attempts} />
|
||||
) : (
|
||||
<div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 px-2">
|
||||
<div className="bg-neutral-800 rounded-xl p-4 sm:p-8 w-full max-w-xs sm:max-w-sm text-center">
|
||||
<h2 className="text-lg sm:text-xl font-semibold mb-4">Digit Number [3-10]</h2>
|
||||
<input
|
||||
type="number"
|
||||
className="w-full rounded p-2 bg-neutral-700 mb-4 focus:outline-none text-base sm:text-lg"
|
||||
value={digitInput}
|
||||
min={1}
|
||||
onChange={(e) => setDigitInput(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
onClick={handleStart}
|
||||
disabled={!digitInput || loading}
|
||||
className="w-full py-2 rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-40 text-base sm:text-lg"
|
||||
>
|
||||
{loading ? '...' : 'OK'}
|
||||
</button>
|
||||
{error && (
|
||||
<p className="mt-4 text-rose-400 text-sm animate-pulse">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
version: '3.3'
|
||||
|
||||
services:
|
||||
s_docker_vue_npm:
|
||||
container_name: c_docker_react
|
||||
image: docker_react
|
||||
restart: always
|
||||
ports:
|
||||
- 8017:80
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
});
|
||||
|
||||
const eslintConfig = [...compat.extends("next/core-web-vitals")];
|
||||
|
||||
export default eslintConfig;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
basePath,
|
||||
assetPrefix: basePath,
|
||||
output: 'export',
|
||||
images: {
|
||||
domains: [
|
||||
't4.ftcdn.net'
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
|
||||
# Asset'ler için gzip (opsiyonel)
|
||||
gzip on;
|
||||
gzip_types text/plain application/javascript text/css application/json;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"name": "number-finder",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"build:prod": "cross-env NODE_ENV=production next build"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "15.3.4",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@tailwindcss/postcss": "^4.1.10",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"cross-env": "^7.0.3",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "15.3.4",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.1.10"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
module.exports = {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
|
|
@ -0,0 +1,11 @@
|
|||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
"./app/**/*.{js,jsx}",
|
||||
"./components/**/*.{js,jsx}"
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
Loading…
Reference in New Issue