Skip to content

Commit

Permalink
fixed ship placing logic
Browse files Browse the repository at this point in the history
win lose logic implemented
  • Loading branch information
Koltheguy committed May 7, 2024
1 parent f42060f commit 3686c6e
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 45 deletions.
2 changes: 1 addition & 1 deletion firestore.rules
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ service cloud.firestore {
}

match /User/{userId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
allow read, write: if request.auth != null;
}

match /Game/{gameId}/{document=**} {
Expand Down
59 changes: 46 additions & 13 deletions src/Game/Game.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from "react";
import React from "react";
import { doc } from "firebase/firestore";
import { useDocumentData } from "react-firebase-hooks/firestore";
import { db, leaveGame } from "../firebase";
import { db, leaveGame, startGame, endGame } from "../firebase";
import LeaveButton from "./LeaveButton";

// import Grid from "./Grid/Grid";
Expand All @@ -16,25 +16,51 @@ const Game = ({ user, gameId }) => {
doc(db, "Game", gameId)
);

const [playerNum, setPlayerNum] = useState(-1);
//const [isCurrent, setIsCurrent] = useState(false);

useEffect(() => {
if (isGameDocLoading) return;
const newPlayerNum = gameDoc.players[0] === user.uid ? 0 : 1;
setPlayerNum(newPlayerNum);
//setIsCurrent(gameDoc.currentPlayer === newPlayerNum);
}, [user.uid, gameDoc, isGameDocLoading, setPlayerNum]);

if (isGameDocLoading) return <>Loading</>;

if (!gameDoc) leaveGame({ user, gameId, isLose: false });

let gameState = false;
let isPlayer = null;
let gameName = "";
let playerNum = -1;
let isCurrent = false;
let isReady = false;
let isResigned = false;
let isWinner = false;
let gameOverMessage = "";
if (gameDoc.gameState !== "") {
gameState = gameDoc.gameState;
isPlayer = gameDoc.players.includes(user.uid);
gameName = gameDoc.gameName;
playerNum = gameDoc.players[0] === user.uid ? 0 : 1;
isCurrent = gameDoc.currentPlayer === playerNum;
if (gameDoc.currentPlayer === 0) {
isReady = gameDoc.gameState === 0 && gameDoc.ready === "11";
if (gameDoc.gameState === 1) {
isResigned = gameDoc.players.length < 2;
isWinner = gameDoc.lives1 < 1 || gameDoc.lives2 < 1;
}
}
gameOverMessage = gameDoc.gameOverMessage;
}

if (isReady) startGame({ gameId, players: gameDoc.players });
if (isResigned)
endGame({
gameId,
gameOverMessage: "Player Resigned",
winner: 0,
players: gameDoc.players,
});
if (isWinner) {
const winner = gameDoc.lives1 < 1 ? 1 : 0;
endGame({
gameId,
gameOverMessage: `Player ${winner} Wins!`,
winner,
players: gameDoc.players,
});
}

let renderGame = null;
Expand All @@ -46,6 +72,7 @@ const Game = ({ user, gameId }) => {
user={user}
gameId={gameId}
playerNum={playerNum}
gameName={gameName}
/>
);
break;
Expand All @@ -55,6 +82,7 @@ const Game = ({ user, gameId }) => {
{/* <Grid />
<ChatBox />
<UsersConnectedBox /> */}
{isCurrent}
<LeaveButton
user={user}
gameId={gameId}
Expand All @@ -66,7 +94,12 @@ const Game = ({ user, gameId }) => {
break;
case 2:
renderGame = (
<GameOver user={user} gameId={gameId} isPlayer={isPlayer} />
<GameOver
user={user}
gameId={gameId}
isPlayer={isPlayer}
gameOverMessage={gameOverMessage}
/>
);
break;
default:
Expand Down
6 changes: 3 additions & 3 deletions src/Game/GameState/GameOver.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import React from "react";
import { Button } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import styles from "./GameOver.module.css";
import LeaveButton from "../LeaveButton";

function GameOver({ user, gameId, isPlayer }) {
function GameOver({ user, gameId, gameOverMessage }) {
return (
<div className={styles.gameOver}>
<h1>Game Over</h1>
<h2>{gameOverMessage}</h2>
<LeaveButton
user={user}
gameId={gameId}
player={isPlayer}
isLose={false}
buttonText="Back to Lobby"
/>
</div>
Expand Down
58 changes: 35 additions & 23 deletions src/Game/GameState/ShipPlacement.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import React, { useState, useEffect } from "react";
import { doc } from "firebase/firestore";
import { useDocumentData } from "react-firebase-hooks/firestore";
import { db, SHIP_TYPES, placeShip } from "../../firebase";
import { db, SHIP_TYPES, placeShip, setReady } from "../../firebase";

import Grid from "../Grid/Grid";
import LeaveButton from "../LeaveButton";
import styles from "./ShipPlacement.module.css";

const shipTypes = Object.keys(SHIP_TYPES);

const ShipPlacement = ({ user, gameId, playerNum }) => {
const ShipPlacement = ({ user, gameId, playerNum, gameName }) => {
const [orientation, setOrientation] = useState("horizontal");
const [shipsLeft, setShipsLeft] = useState([0, 1, 2, 3, 4]);
const [shipsLeft, setShipsLeft] = useState([0, 1, 2, 3, 4, 5]);
const [gridData, setGridData] = useState({});
const [gameDoc, isGameDocLoading] = useDocumentData(
doc(db, "Game", gameId)
);

let ready = "";
if (!isGameDocLoading) ready = gameDoc.ready;

const shipString = isGameDocLoading
? ""
: playerNum === 0
Expand Down Expand Up @@ -68,38 +72,46 @@ const ShipPlacement = ({ user, gameId, playerNum }) => {
};

let shipName = null;

console.log(playerNum === 0 ? "1" + ready.at(1) : ready.at(0) + 1);
if (shipsLeft.length > 0) {
shipName = shipTypes[shipsLeft[0]];
shipName = shipName.charAt(0).toUpperCase() + shipName.slice(1);
} else {
setReady({
gameId,
ready: playerNum === 0 ? "1" + ready.at(1) : ready.at(0) + 1,
});
}

return (
<div className={styles.shipPlacement}>
<div style={{ flex: 2 }}>
<div className={styles.shipDisplay}>
{shipsLeft.length > 0 ? (
<>
<h2>Place Your Ships</h2>
<h3>Ship: {shipName}</h3>
<h4>
Size: {SHIP_TYPES[shipTypes[shipsLeft[0]]]}{" "}
units
</h4>
<h5>Orientation: {orientation}</h5>
<button onClick={toggleOrientation}>
Toggle Orientation
</button>
<button onClick={handleNextShip}>Next Ship</button>
</>
) : (
<h2>All Ships Placed, Waiting for opponent</h2>
)}
</div>
<h1>{gameName}</h1>
<Grid handleGridClick={handleCellClick} gridData={gridData} />
</div>
<div style={{ flex: 1 }}>
<div style={{ flex: 1 }}>
<div className={styles.shipDisplay}>
{shipsLeft.length > 0 ? (
<>
<h2>Place Your Ships</h2>
<h3>Ship: {shipName}</h3>
<h4>
Size: {SHIP_TYPES[shipTypes[shipsLeft[0]]]}{" "}
units
</h4>
<h5>Orientation: {orientation}</h5>
<button onClick={toggleOrientation}>
Toggle Orientation
</button>
<button onClick={handleNextShip}>
Next Ship
</button>
</>
) : (
<h2>All Ships Placed, Waiting for opponent...</h2>
)}
</div>
<LeaveButton
user={user}
gameId={gameId}
Expand Down
2 changes: 1 addition & 1 deletion src/Game/GameState/ShipPlacement.module.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.container {
.shipPlacement {
display: flex;
height: 100vh;
width: 100vw;
Expand Down
14 changes: 14 additions & 0 deletions src/Lobby/Lobby.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ const Lobby = () => {
// allows only alphanumeric inputs
await setUsername(event.target.value.replace(/[^0-9a-zA-Z]+/gi, ""));
};
let wins = null;
let losses = null;

if (!isUserDocLoading && userDoc) {
wins = userDoc.wins;
losses = userDoc.losses;
}
if (!isUserDocLoading && userDoc && userDoc.currentGame !== "") {
return <Game user={user} gameId={userDoc.currentGame} />;
} else if (isNewGame) {
Expand All @@ -79,6 +85,9 @@ const Lobby = () => {
return (
<div className={`${styles.body} ${styles.lobby}`}>
<h1 className={styles.header}>Battleship</h1>
<div className={styles.stats}>
Wins: {wins} Losses: {losses}
</div>
<div className={styles.inputs}>
Username:{" "}
<input
Expand Down Expand Up @@ -113,6 +122,7 @@ const Lobby = () => {
</thead>
<tbody>
{!isGameCollectionLoading &&
gameCollection.length > 0 &&
gameCollection.map((item) => (
<tr key={item.gameName + item.createdBy}>
<td>{item.gameName}</td>
Expand All @@ -134,6 +144,10 @@ const Lobby = () => {
</td>
</tr>
))}
{!isGameCollectionLoading &&
gameCollection.length < 1 && (
<>No Games Found, Make a new one!</>
)}
</tbody>
</table>
</div>
Expand Down
4 changes: 4 additions & 0 deletions src/Lobby/Lobby.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ body {
overflow-x: hidden;
}

.stats {
text-align: center;
}

.header {
margin: 2rem;
text-align: center;
Expand Down
51 changes: 47 additions & 4 deletions src/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const initializeUser = async (user) => {
if (!snap.data().count) {
setDoc(doc(db, "User", user.uid), {
wins: 0,
loses: 0,
losses: 0,
gamesPlayed: 0,
currentGame: "",
isChatBanned: false,
Expand Down Expand Up @@ -140,11 +140,13 @@ const newGame = async ({ user, gameName, timer }) => {
timer: timer,
players: [user.uid],
spectate: [],
ready: "00",
gameState: 0,
turn: 0,
currentPlayer: 0,
timeStarted: serverTimestamp(),
winner: "",
gameOverMessage: "",

lives1: LIVES_TOTAL,
visible1: "",
Expand Down Expand Up @@ -191,14 +193,45 @@ const leaveGame = async ({ user, gameId, isLose }) => {
if (isLose)
updateDoc(doc(db, "User", user.uid), {
currentGame: "",
loses: increment(1),
losses: increment(1),
gamesPlayed: 0,
});
else
updateDoc(doc(db, "User", user.uid), {
currentGame: "",
});
};
const startGame = async ({ gameId, players }) => {
await updateDoc(doc(db, "Game", gameId), {
gameState: 1,
});
updateDoc(doc(db, "User", players[0]), {
gamesPlayed: increment(1),
});

updateDoc(doc(db, "User", players[1]), {
gamesPlayed: increment(1),
});
};

const endGame = async ({ gameId, gameOverMessage, winner, players }) => {
updateDoc(doc(db, "Game", gameId), {
gameState: 2,
gameOverMessage,
winner: players[winner],
});

const loser = winner === 0 ? 1 : 0;

updateDoc(doc(db, "User", players[winner]), {
wins: increment(1),
});

if (players.length > 1)
updateDoc(doc(db, "User", players[loser]), {
losses: increment(1),
});
};
//#endregion

//#region game setup
Expand Down Expand Up @@ -238,10 +271,11 @@ const placeShip = async ({ user, gameId, shipType, position, orientation }) => {
if (orientation !== "horizontal" && orientation !== "vertical") return -1;
if (position[0] < 0 || position[1] < 0) return -1;
const shipSize = SHIP_TYPES[shipType];
console.log(position);
if (orientation === "horizontal") {
if (position[0] + shipSize >= GRID_SIZE) return -1;
if (position[0] + shipSize > GRID_SIZE) return -1;
} else {
if (position[1] + shipSize >= GRID_SIZE) return -1;
if (position[1] + shipSize > GRID_SIZE) return -1;
}
const { playerNum } = await checkTurn({ user, gameId });
const oldShips = await getShips({ gameId, playerNum });
Expand Down Expand Up @@ -290,6 +324,12 @@ const placeShip = async ({ user, gameId, shipType, position, orientation }) => {

return -1;
};

const setReady = ({ gameId, ready }) => {
updateDoc(doc(db, "Game", gameId), {
ready,
});
};
//#endregion

//#region gameplay
Expand Down Expand Up @@ -409,9 +449,12 @@ export {
changeUserName,
newGame,
joinGame,
startGame,
endGame,
leaveGame,
getShips,
placeShip,
setReady,
checkTurn,
attack,
view,
Expand Down

0 comments on commit 3686c6e

Please sign in to comment.