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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions guessing-game-v2/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa");
implementation("org.hibernate.orm:hibernate-community-dialects:6.6.3.Final");
implementation("org.xerial:sqlite-jdbc:3.36.0.3");
compileOnly("org.projectlombok:lombok:1.18.32");
}

application {
Expand Down
1 change: 1 addition & 0 deletions guessing-game-v2/frontend/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ color: black;
text-align: center;
font-size: 25px;
height: 16em;
white-space: pre-wrap;
}

.submit {
Expand Down
47 changes: 34 additions & 13 deletions guessing-game-v2/frontend/src/pages/Play/Play.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
import React, {useState} from "react";
import React, {useEffect, useState} from "react";
import './Play.css';
import numMeCrazyDude from '../../assets/numMeCrazyDude.png';

export const Play: React.FC = () => {
const [inputText, setInputText] = useState('');
const [response, setResponse] = useState('');
const [gameId, setGameId] = useState('');

useEffect(() => {
const startGame = async () => {
const res = await fetch(`http://localhost:8081/games`, {
method: "POST",
headers: {
"Content-Type": "application.json",
},
body: JSON.stringify({}),
});
};
startGame();
}, []);

const handleInputChange = (event:any) => {
setInputText(event.target.value);
};

const sendGuess = async (guess:string) => {
try {
const res = await fetch(`http://localhost:8081/guess`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(({ text: inputText })),
});

if (isNaN(parseInt(guess))) {
setResponse("Please enter a valid number");
return;
}
if (parseInt(guess) === targetNumber) {
setResponse("You Win!!!");

const res = await fetch(`http://localhost:8081/guess`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(({ text: inputText, gameId })),
});
}
const data = await res.text();
setResponse(data);
} catch (error) {
Expand Down Expand Up @@ -47,10 +68,10 @@ export const Play: React.FC = () => {
<p className="response">{response}</p>
</div> */}
</div>
<div className="buttons">
{/* <input className="input-section"></input> */}
<input
className="input-section"
<div className="buttons">
{/* <input className="input-section"></input> */}
<input
className="input-section"
type="text"
value={inputText}
onChange={handleInputChange}
Expand Down
124 changes: 124 additions & 0 deletions guessing-game-v2/src/main/controller/GameControllers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.codedifferently.q4.team2.controller;

import com.codedifferently.q4.team2.model.Difficulty;
import com.codedifferently.q4.team2.service.GameEngine;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/game")
@CrossOrigin(origins = "http://localhost:8081")
public class GameControllers {

private GameEngine gameEngine;


public GameControllers() {
this.gameEngine = new GameEngine();
}

@PostMapping
public ResponseEntity<GameStartResponse> startGame(
@Valid @RequestBody GameStartRequest request
) {
GameStartResponse response = gameService.startGame(request);
return ResponseEntity.ok(response);
}


@PostMapping("/start")
public ResponseEntity<Map<String, Object>> startGame(@RequestBody Map<String, String> payload) {

String difficultyStr = payload.get("difficulty");
String playerName = payload.get("playerName");




Difficulty difficulty = Difficulty.valueOf(difficultyStr.toUpperCase());


gameEngine.level = difficulty;
gameEngine.playerName = playerName;
gameEngine.secretNumber = gameEngine.generateNumberToGuess(difficulty);
gameEngine.attempts = 0;


Map<String, Object> response = new HashMap<>();
response.put("message", "Game started for " + playerName + " at " + difficulty + " level");
response.put("maxRange", difficulty.value);

return ResponseEntity.ok(response);
}


@PostMapping("/guess")
public ResponseEntity<Map<String, Object>> processGuess(@RequestBody Map<String, String> payload) {
int guessedNumber = Integer.parseInt(payload.get("text"));


boolean isCorrect = gameEngine.validateGuess(guessedNumber);


Map<String, Object> response = new HashMap<>();
response.put("correct", isCorrect);
response.put("attempts", gameEngine.attempts + 1);

String message;
if (isCorrect) {
message = "Congratulations! You guessed the number in " + (gameEngine.attempts + 1) + " attempts.";

gameEngine.secretNumber = gameEngine.generateNumberToGuess(gameEngine.level);
gameEngine.attempts = 0;
} else {
String hint = (gameEngine.secretNumber > guessedNumber) ? "higher" : "lower";
message = "Incorrect! Try a " + hint + " number.";
gameEngine.attempts++;
}

response.put("message", message);

return ResponseEntity.ok(response);
}

@PostMapping("/games")
public ResponseEntity<StartGameResponse> startGame(@RequestBody StartGameRequest request) {
// Validate input
if (request.getPlayerName() == null || request.getDifficulty() == null) {
return ResponseEntity.badRequest().body(
StartGameResponse.builder()
.error("Player name and difficulty are required")
.build()
);
}


String gameId = gameEngine.startGame(
request.getPlayerName(),
Difficulty.valueOf(request.getDifficulty().toUpperCase())
);

return ResponseEntity.ok(
StartGameResponse.builder()
.gameId(gameId)
.maxRange(Difficulty.valueOf(request.getDifficulty().toUpperCase()).value)
.build()
);
}

@GetMapping("/leaderboard")
public ResponseEntity<Map<String, Object>> getLeaderboard(@RequestParam("difficulty") String difficultyStr) {
Difficulty difficulty = Difficulty.valueOf(difficultyStr.toUpperCase());


Map<String, Object> response = new HashMap<>();
response.put("difficulty", difficulty);


return ResponseEntity.ok(response);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.codedifferently.q4.team2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadTerminalOutput {

public static void main(String[] args) throws IOException, InterruptedException {
// Create a ProcessBuilder to run the command
ProcessBuilder pb = new ProcessBuilder("ls", "-l");

// Start the process
Process process = pb.start();

// Get the input stream of the process (standard output)
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

// Read the output line by line and store in a StringBuilder
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}

// Wait for the process to finish
int exitCode = process.waitFor();

// Print the output
System.out.println("Output:\n" + output);
System.out.println("Exit code: " + exitCode);
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
package com.codedifferently.q4.team2.controller;

import com.codedifferently.q4.team2.model.InputData;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.codedifferently.q4.team2.model.Difficulty;
import com.codedifferently.q4.team2.model.InputData;
import com.codedifferently.q4.team2.service.GameEngine;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
@CrossOrigin(origins = "http//localhost:5173")
public class GameController {
private GameEngine gameEngine = new GameEngine();


@GetMapping("/hello")
public String helloWorld() {
return "Hello World";
}
Expand All @@ -23,8 +28,25 @@ public String Home() {

@PostMapping("/guess")
public String handleGuess(@RequestBody InputData inputData) {
String gameId = inputData.getGameId();
String receivedText = inputData.getText();
String message = gameEngine.makeGuess(gameId, receivedText);
System.out.println("Received entry: NILE " + receivedText);
return ("Received message: NILE ......... " + receivedText);
return ("""
**************************************************
************** **************
************* Welcome to numMeCrazy! *************
************** **************
**************************************************
****** Please select Game difficulty level: ******
{1}. \t Easy (1-10)
""" + receivedText);
}

@PostMapping("/games")
public ResponseEntity<StartGameResponse> startGame() {
String gameId = gameEngine.startGame();
return ResponseEntity.ok(StartGameResponse.builder().gameId(gameId).build();
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.codedifferently.q4.team2.model.DTO;

import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GameStartRequest {
private String playerName;
private String difficulty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.codedifferently.q4.team2.model.DTO;

import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GameStartResponse {
private String gameId;
private Integer maxRange;
private String errorMessage;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.codedifferently.q4.team2.model;

import lombok.Data;

@Data
public class GameState {
private int secretNumber;
private int attempts;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.codedifferently.q4.team2.model;

import lombok.Data;

@Data
public class InputData {
private String text;
private String gameId;

// Getter and Setter for text
public String getText() {
Expand Down
Loading