Skip to content

Feat Adds: working controller, small change to play.tsx file #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
72 changes: 72 additions & 0 deletions guessing-game-v1/src/controller/GameController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@

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.*;

@RestController
@CrossOrigin(origins = "http://localhost:8081")
public class GameController {

private final GameEngine gameEngine;

public GameController(GameEngine gameEngine) {
this.gameEngine = gameEngine;
}

@PostMapping("/start")
public ResponseEntity<String> startGame(
@RequestParam(defaultValue = "EASY") Difficulty difficulty,
@RequestParam(defaultValue = "Anonymous") String playerName
) {
String gameId = gameEngine.startGame(playerName, difficulty);
return ResponseEntity.ok(gameId);
}

@PostMapping("/guess")
public ResponseEntity<String> makeGuess(
@RequestBody GuessRequest guessRequest
) {

GameEngine.GameSession session = gameEngine.getActiveSession(guessRequest.getGameId());

if (session == null) {
return ResponseEntity.badRequest().body("Invalid game session");
}

int guess = Integer.parseInt(guessRequest.getText());


boolean isCorrect = gameEngine.validateGuess(guess);


String message = prepareGuessResponse(guess, isCorrect, session);

return ResponseEntity.ok(message);
}


private String prepareGuessResponse(int guess, boolean isCorrect, GameEngine.GameSession session) {
if (isCorrect) {
return String.format("Congratulations %s! You guessed the correct number %d in %d attempts!",
session.playerName, guess, session.attempts + 1);
} else {
String hint = (guess < session.secretNumber) ? "higher" : "lower";
return String.format("Incorrect! Try a %s number. Attempt %d", hint, session.attempts + 1);
}
}


public static class GuessRequest {
private String text;
private String gameId;


public String getText() { return text; }
public void setText(String text) { this.text = text; }
public String getGameId() { return gameId; }
public void setGameId(String gameId) { this.gameId = gameId; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,53 @@
import com.codedifferently.q4.team2.model.Difficulty;
import com.codedifferently.q4.team2.model.LeaderboardEntry;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class GameEngine {

protected Scanner console;
protected int secretNumber;
public int secretNumber;
boolean isGameOn;
String playerName;
protected int attempts;
Difficulty level = Difficulty.EASY;
public String playerName;
public int attempts;
public Difficulty level = Difficulty.EASY;


private Map<Difficulty, List<LeaderboardEntry>> leaderboard;

private Map<String, GameSession> activeSessions = new ConcurrentHashMap<>();

public String startGame(String playerName, Difficulty difficulty) {
// Generate unique game ID
String gameId = UUID.randomUUID().toString();



// Create a new game session
GameSession session = new GameSession(playerName, difficulty);
activeSessions.put(gameId, session);

return gameId;
}

// Inner class to track game state
private class GameSession {
String playerName;
Difficulty difficulty;
int secretNumber;
int attempts;

public GameSession(String playerName, Difficulty difficulty) {
this.playerName = playerName;
this.difficulty = difficulty;
this.secretNumber = generateNumberToGuess(difficulty);
this.attempts = 0;
}
}




private Map<Difficulty, List<LeaderboardEntry>> leaderboard;

public GameEngine() {
this.console = new Scanner(System.in);
Expand Down Expand Up @@ -124,7 +160,7 @@ protected int playerGuess(String playerName) {
return response;
}

boolean validateGuess(int guess) {
public boolean validateGuess(int guess) {
return guess == secretNumber;
}

Expand Down
138 changes: 73 additions & 65 deletions guessing-game-v2/frontend/src/pages/Play/Play.tsx
Original file line number Diff line number Diff line change
@@ -1,76 +1,84 @@
import React, {useState} from "react";
import React, { useState, useEffect } 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 [inputText, setInputText] = useState('');
const [response, setResponse] = useState('');
const [gameId, setGameId] = useState('');
const [targetNumber, setTargetNumber] = useState<number | null>(null);

const handleInputChange = (event:any) => {
setInputText(event.target.value);
};
useEffect(() => {
const initializeGame = async () => {
try {
const res = await fetch('http://localhost:5137/start', {
method: 'POST'
});
const data = await res.text();
setGameId(data);
const targetNum = parseInt(data); // Adjust this based on actual response
if (!isNaN(targetNum)) {
setTargetNumber(targetNum);
}
} catch (error) {
console.error("Error starting game:", error);
}
};


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

const data = await res.text();
setResponse(data);
} catch (error) {
console.error("Error:", error);
}
};

return (
<body>
<div className="background-2">
<div className="paper-background">
<span>
<div className= "screen-area">
<h1 className="Output">{response}</h1>
</div>
<div>
{/* <input
type="text"
value={inputText}
onChange={handleInputChange}
placeholder="Enter some text"
/> */}
{/* <button onClick={() => sendGuess("guess")}>submitGuess</button> */}
{/* <div>
<p className="response">{response}</p>
</div> */}
</div>
<div className="buttons">
{/* <input className="input-section"></input> */}
<input
className="input-section"
type="text"
value={inputText}
onChange={handleInputChange}
placeholder="Enter Response Here"
/>

{/* <button className="submit">
<a href="">Submit</a>
</button> */}
<button className="submit" onClick={() => sendGuess("guess")}>Submit</button>
<button className="title-button">
<a href="/">Title Screen</a>
</button>
</div>
<img className="nMCDude" src={numMeCrazyDude} alt="numMeCrazyBoy" width="500" />
</span>
</div>
</div>
</body>
);
initializeGame();
}, []); // Removed nested useEffect, corrected single useEffect

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputText(event.target.value);
};

const sendGuess = async (guess: string) => {
try {
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: gameId }), // Corrected JSON stringify
});
const data = await res.text();
setResponse(prevresponse => prevresponse + "\n" + data);
} catch (error) {
console.error("Error:", error);
}
};

return (
<div className="background-2"> {/* Replaced <body> with <div> */}
<div className="paper-background">
<span>
<div className="screen-area">
<h1 className="Output">{response}</h1>
</div>
<div className="buttons">
<input
className="input-section"
type="text"
value={inputText}
onChange={handleInputChange}
placeholder="Enter Response Here"
/>
<button className="submit" onClick={() => sendGuess("guess")}>Submit</button>
<button className="title-button">
<a href="/">Title Screen</a>
</button>
</div>
<img className="nMCDude" src={numMeCrazyDude} alt="numMeCrazyBoy" width="500" />
</span>
</div>
</div>
);
}

export default Play;