Skip to content
Draft
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
5 changes: 3 additions & 2 deletions examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<title>C4C Multiplayer API Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script defer src="./lobbyPackage.js"></script>
<script defer src="./index.js"></script>
<style type="text/css">
@import url('https://fonts.googleapis.com/css2?family=Ubuntu&display=swap');
Expand Down Expand Up @@ -69,7 +70,7 @@
<div id="canvasContainer">

<div id="before">
<button class="btn btn-primary btn-lg" onclick="hostGame();">Host a game</button>
<button class="btn btn-primary btn-lg" onclick="hostLobby(hostCallback);">Host a game</button>
<button class="btn btn-success btn-lg" onclick="switchScreen('before','join')">Join a game</button>
</div>

Expand All @@ -83,7 +84,7 @@
<p>Type in code: </p>
<div class="input-group mb-3">
<input type="text" id="code-input" maxlength="6" class="form-control" placeholder="Code" />
<button class="btn btn-outline-success" type="button" onClick="joinGame()">Enter</button>
<button class="btn btn-outline-success" type="button" onclick="joinLobby(joinCallback)">Enter</button>
</div>
</div>

Expand Down
231 changes: 131 additions & 100 deletions examples/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ let winState = WIN_STATES.NO_WINNER;

// This is the official starting state of the game. Everything is blank.
function getStartingState() {
return JSON.parse(JSON.stringify([
return [
// Column 0 Column 1 Column 2
[SQUARE_STATES.BLANK, SQUARE_STATES.BLANK, SQUARE_STATES.BLANK], // Horizontal row 0
[SQUARE_STATES.BLANK, SQUARE_STATES.BLANK, SQUARE_STATES.BLANK], // Horizontal row 1
[SQUARE_STATES.BLANK, SQUARE_STATES.BLANK, SQUARE_STATES.BLANK], // Horizontal row 2
]));
];
}

let gameState = getStartingState();
Expand Down Expand Up @@ -230,11 +230,11 @@ function checkHandleWin() {
if (winState === WIN_STATES.O_WIN || winState === WIN_STATES.X_WIN) {
winningPlayer = getWinningPlayer();
alert("Player " + winningPlayer.id + " has won!");
deleteGame();
deleteLobby();
}
else if (winState === WIN_STATES.DRAW) {
alert("The match is a draw!");
deleteGame();
deleteLobby();
}
}

Expand Down Expand Up @@ -311,10 +311,77 @@ function compareStates(gameState, boardFromServer) {
}



// ------------------------------------------------------------------------------------------
// ---------------------------------- MULTIPLAYER LOGIC -------------------------------------
// ------------------------------------------------------------------------------------------

const hostCallback = function () {
setUpBoard();
makePlayers();
renderState();
gameState = getStartingState();
saveGameState();
};

const joinCallback = function () {
setUpBoard();
makePlayers();
renderState();
checkUpdateGameState();
};


function saveGameState() {
ajax(POST, JSON.stringify({ ingame: true, state: gameState }), checkUpdateGameState);
}


// Sets up the options and calls the function to check for and update the game state
function checkUpdateGameState() {
ajax(GET, null, (responseAsJson) => {
boardString = responseAsJson.Item.Board.S;
boardFromServer = JSON.parse(boardString);
if (boardFromServer.ingame == true)
boardFromServer = boardFromServer.state;
else {
setTimeout(checkUpdateGameState, 200);
return;
}

console.log("Fetched board");
console.log(boardFromServer);

// Process the response
if (compareStates(gameState, boardFromServer)) {
setTimeout(checkUpdateGameState, 200);
console.log("board was the same");
}
else {
console.log("board was different");

// Update and rerender the board
gameState = boardFromServer;
renderState();
checkHandleWin();
// player switch to be your turn
switchPlayers();

if (!isMyTurn()) {
setTimeout(checkUpdateGameState, 200);
}

}
});
}



// ------------------------------------------------------------------------------------
// --------------------------- Lobby Hosting Package Logic ----------------------------
// ------------------------------------------------------------------------------------


const MULTIPLAYER_API_URL = "https://6f6qdmvc88.execute-api.us-east-2.amazonaws.com";
const STAGE = "dev";
const POST = 'POST';
Expand Down Expand Up @@ -365,75 +432,85 @@ function ajax(methodString, stringBody, callback) {
}


function saveGameState() {
ajax(POST, JSON.stringify({ ingame: true, state: gameState }), checkUpdateGameState);
// General Host lobby function
// Callback is function to run once game has started
function hostLobby (callback) {
switchScreen('before', 'host');
const highestID = 1000000;
gameId = Math.floor(Math.random() * highestID);
document.getElementById("code").value = gameId;
beginGame(callback);
}


// Delete game
function deleteGame() {
// TODO: add game deletion logic (only one player should delete the game)
// ajax(DELETE, null, () => {});
location.reload();
}
// Join a lobby, given a callback function to run once done
function joinLobby(callback) {



// Check if there is a game
gameId = document.getElementById("code-input").value;


// Sets up the options and calls the function to check for and update the game state
function checkUpdateGameState() {
ajax(GET, null, (responseAsJson) => {
boardString = responseAsJson.Item.Board.S;
boardFromServer = JSON.parse(boardString);
if (boardFromServer.ingame == true)
boardFromServer = boardFromServer.state;
else {
setTimeout(checkUpdateGameState, 1000);

if (responseAsJson == "" || responseAsJson == {} || responseAsJson == "{}") {
alert("Sorry, game does not exist");
location.reload();
return;
}

console.log("Fetched board");
console.log(boardFromServer);
boardString = responseAsJson.Item.Board.S;
boardFromServer = JSON.parse(boardString);

// Process the response
if (compareStates(gameState, boardFromServer)) {
setTimeout(checkUpdateGameState, 1000);
console.log("board was the same");
}
else {
console.log("board was different");
console.log("Fetched players");
console.log(boardFromServer);

// Update and rerender the board
gameState = boardFromServer;
renderState();
checkHandleWin();
// player switch to be your turn
switchPlayers();

if (!isMyTurn()) {
setTimeout(checkUpdateGameState, 1000);
if (boardFromServer.ingame) {
alert("Sorry, game is already full");
} else {
// Process the response
if (boardFromServer.numPlayers == 2) {
alert("Sorry, game is already full");
} else {
player = 1;
if (boardFromServer.curPlayer == 1) {
player = 2;
}
// TODO: POST THE NEW THING TELLING THE HOST TO START THE GAME -------------------------------------------------
ajax(POST, JSON.stringify({ ingame: false, curPlayer: player, numPlayers: 2 }), () => { console.log("Told host to start gameGame"); });
callback();
}

}
});
// -----------------------------------------------------------
switchScreen('join', 'after');
}

// Delete game
function deleteLobby() {
// TODO: add game deletion logic (only one player should delete the game)
// TODO: reopen game hosting area??
ajax(DELETE, null, () => {});
}



// ------------------------------------------------------------------------------------
// ---------- Package helper functions (not used directly by client) ------------------
// ------------------------------------------------------------------------------------

// Switch the screen
function switchScreen(oldLocation, newLocation) {
document.getElementById(oldLocation).style = "display:none";
document.getElementById(newLocation).style = "";
}

function hostGame() {
switchScreen('before', 'host');
gameId = Math.floor(Math.random() * 1000000);
document.getElementById("code").value = gameId;
beginGame();
}

function beginGame() {
setUpBoard();
makePlayers();
// TODO: Decide if the state really needs to be rendered here
renderState();
function beginGame(callback) {


// Figure out which player
player = Math.floor(Math.random() * 2 + 1);
Expand All @@ -442,13 +519,13 @@ function beginGame() {
// Post the game
ajax(POST, JSON.stringify({ ingame: false, curPlayer: player, numPlayers: 1 }), () => {
hasLoaded = true;
setTimeout(waitForPlayer, 1000);
setTimeout(()=>{waitForPlayer(callback)}, 200);
});
}


// Sets up the options and calls the function to check for and update the game state
function waitForPlayer() {
function waitForPlayer(callback) {
ajax(GET, null, (responseAsJson) => {
boardString = responseAsJson.Item.Board.S;
boardFromServer = JSON.parse(boardString);
Expand All @@ -460,59 +537,13 @@ function waitForPlayer() {
if (boardFromServer.numPlayers == 2) {
// Start the game
switchScreen('host', 'after');
gameState = getStartingState();
saveGameState();
console.log(callback);
callback();

} else {
setTimeout(waitForPlayer, 1000);
setTimeout(()=>{waitForPlayer(callback)}, 200);
}
});
}


function joinGame() {
setUpBoard();
makePlayers();
// TODO: Decide if the state really needs to be rendered here
renderState();


// Check if there is a game
gameId = document.getElementById("code-input").value;


ajax(GET, null, (responseAsJson) => {

if (responseAsJson == "" || responseAsJson == {} || responseAsJson == "{}") {
alert("Sorry, game does not exist");
location.reload();
return;
}

boardString = responseAsJson.Item.Board.S;
boardFromServer = JSON.parse(boardString);

console.log("Fetched players");
console.log(boardFromServer);


if (boardFromServer.ingame) {
alert("Sorry, game is already full");
} else {
// Process the response
if (boardFromServer.numPlayers == 2) {
alert("Sorry, game is already full");
} else {
player = 1;
if (boardFromServer.curPlayer == 1) {
player = 2;
}
// TODO: POST THE NEW THING TELLING THE HOST TO START THE GAME -------------------------------------------------
ajax(POST, JSON.stringify({ ingame: false, curPlayer: player, numPlayers: 2 }), () => { console.log("Told host to start gameGame"); });
checkUpdateGameState();
}

}
});
// -----------------------------------------------------------
switchScreen('join', 'after');
}
Empty file added examples/lobbyPackage.js
Empty file.