diff --git a/cardGen.js b/cardGen.js index 0b9b92d..3c6468a 100644 --- a/cardGen.js +++ b/cardGen.js @@ -14,7 +14,7 @@ const database = require('./database'); // then will rejig when needed. // Should all cards, effects, classes etc. be loaded in on server start // then just load decks and decklists when needed? -function getDecks(deckId, playerId, item = [], deckItem = {}){ +function getDecks(deckIds = false){ // Await promise, once it's done get the data, if errors send err const dPromise = new Promise((resolve, reject) => { @@ -157,6 +157,8 @@ function getCardColourRequirement(){ // https://www.geeksforgeeks.org/how-to-wait-for-multiple-promises-in-javascript/ // https://medium.com/@nikolozz/using-socket-io-with-async-await-13fa8c2dc9d9 // using last example +// TODO: When this is functionally working, need to split up into other func/modules +// such as: playerMod, cardMod, deckMod, miscMod ? function requestDeck(socket, playerId, deckId){ return new Promise((resolve, reject) => { (async () => { @@ -168,15 +170,6 @@ function requestDeck(socket, playerId, deckId){ await Promise.all([ getDecks(), getDeckList() - // Don't need to do this for each when awaiting all - // Instead it'll wait until each is done, set the data to the const - // Then do the stuff after the variable's are set!! - /* - getDecks().then(data => { - //console.log(data); - }).catch(err => { throw err; }), - */ - ]); //console.log(decks); @@ -229,7 +222,7 @@ function requestDeck(socket, playerId, deckId){ // send and play with // BUILD THE DATA TO SEND TO CLIENTS! (Kinda) let item = []; - let itemCount = 0; + let itemCount = 0; // TODO: Have this continue from last function (ie. getPlayers?) let deckData = {}; // New but may be useful let deckIn = {}; // Which deck the item is in? Kinda the player/boardelement thing? let cardData = {}; diff --git a/database.js b/database.js index 5f5d6a7..723dba7 100644 --- a/database.js +++ b/database.js @@ -16,162 +16,7 @@ function disconnect(){ con.end(); } -// Is calling a promise in a promise the best way to do this? -// Keeping because this is how I've figured to call other funcs from database -function getCardById(cardId){ - - const dPromise = new Promise((resolve, reject) => { - - getCards(' card.id = '+cardId).then(cards => { - resolve(cards); - }) - .catch(err => { - throw err; reject(new Error(err)); - }); - - }); - return dPromise; -} - -function getCards(whereClause){ - const cPromise = new Promise((resolve, reject) => { - // Get main card info - let cards = []; - let sql = `SELECT - card.id AS cardId -- TEMP UNTIL UID - ,cardName - ,cardCost - ,typeName - ,cardAttack - ,rarityName - FROM card - LEFT JOIN type ON type.id = card.id - LEFT JOIN rarity ON rarity.id = card.cardRarity - `; - // TODO: Rewrite this so it's not so insecure!!!! - if(whereClause){ sql = sql + " WHERE "+whereClause; } - - con.query(sql, function (err, result, fields) { - if (err) { throw err; reject(new Error(err)); } - cards = dbResultToCards(result); - //console.log(cards); - resolve(cards); - }); - - // Now get the - // class - // colour requirements - // card effects - }); - return cPromise; -} - -// May want a FromDecks to get the SQL done in one blast -// then filter the results according? -function getCardsFromDeck(playerId, deckId){ - const cPromise = new Promise((resolve, reject) => { - if(playerId == null || deckId == null){ reject(new Error('Player/Deck Id not provided')); } - let cards = []; - // TODO: Change rarity, and maybe cardName to be the id (prolly card name for fancy effects) - // Then have a SQL loop at start of game that adds [name, id], [rariry, id] etc. - let sql = `SELECT - cardName - ,cardCost - ,typeName - ,cardAttack - ,rarityName - ,cardCount - FROM deck - INNER JOIN deck_cards ON deck_cards.deckId = deck.deckId AND deck_cards.playerId = deck.playerId - INNER JOIN card ON card.id = deck_cards.cardId - LEFT JOIN type ON type.id = card.id - LEFT JOIN rarity ON rarity.id = card.cardRarity`; - // TODO: Make more secure!! - sql += ' WHERE deck.deckId ='+deckId+' AND deck.playerId = '+playerId; - sql += ';'; - - con.query(sql, function (err, result, fields) { - if (err) { throw err; reject(new Error(err)); } - cards = dbResultToCards(result); - resolve(cards); - }); - - // Card list has been built - // Resolve/return the data of the cards Array/deck - - }); - return cPromise; -} - -// This may be more jank than I'd like. Was going procedure route, or JOINs -// but thinking of future effects that could have 4-5 effects, that check 2-3 colours -// and X amounts of cards/classes, to finally trigger something, those feel like they -// wouldn't work. So this is it for now, and when I think of something better I'll rewrite -function dbGetCardClasses(cardId){ - // Maybe this isn't too bad as async? - // But I imagine for lets say 100 1v1s 200 loops of 35cards each, eekers - - const cPromise = new Promise((resolve, reject) => { - if(cardId == null){ reject(new Error('cardId not provided')); } - let classes = []; - // Just getting the class IDs, as intend to load all the class data [id, name] into - // an array or file on game load. This way just the ID is needed, and no text compares - let sql = `SELECT classId - FROM card_class - WHERE cardId = `+cardId - ; // TODO: As all these SQL, need to make more secure - - con.query(sql, function (err, result, fields) { - if (err) { throw err; reject(new Error(err)); } - result.forEach((card) => { - // Add the classId to array to be used in card buildery doodad - classes.push(result[0]); - }); - }); - - // Card list has been built - // Resolve/return the data of the cards Array/deck - resolve(classes); - - }); - return cPromise; -} - -// Don't really want this in DB layer, but it wouldn't play -// in the main server file, so it's here until I figure out why -function dbResultToCards(result){ - let cards = []; - result.forEach((card) => { - let tempCard = {}; - tempCard.id = card.cardId; - tempCard.name = card.cardName; - tempCard.colour = null; - tempCard.cost = card.cardCost; - tempCard.type = card.typeName; - tempCard.atk = card.cardAttack; - tempCard.rarity = card.rarityName; - tempCard.effect = null; - // TODO: Will need more SQL statements, or some function/procedure - // class - // colour requirements - // card effects - - // Add the 'completed' cards into the deck - if(card.cardCount){ - // Add as many cards into the deck as is in cardCount - for(let i = 0; i < card.cardCount; i++){ - cards.push(tempCard); - } - }else{ - // Or just one - cards.push(tempCard); - } - }); - return cards; -} - - -// Testing, and trialing rewrites +// My DB stuffs function dbGetDecks(){ const dPromise = new Promise((resolve, reject) => { let cards = []; @@ -265,9 +110,6 @@ function dbGetCardColourRequirement(){ module.exports = { connect, disconnect - , getCards - , getCardById - , getCardsFromDeck // Testing, and trailing , dbGetDecks , dbGetDeckList diff --git a/public/board.js b/public/board.js index 7749e29..76a6151 100644 --- a/public/board.js +++ b/public/board.js @@ -807,14 +807,13 @@ let board = new Board; // At least I think, for now. May need more stuff in future // Request the deck(s) from server/db -requestDeck(); +// When the page loads (for now) start the game +requestStartGame(); // This will trigger an emit to and on from the server will trigger loadBoard(); -// public/main.js -// socket.on('responseGetDeck', function (data) { +// public/main.js // socket.on('responseStartGame', function (data) { function loadBoard(data) { - console.log('DATA'); console.log(data); // Built the original boardstate using the data passed from server @@ -905,10 +904,6 @@ function loadBoard(data) { shuffleDeck(0); // Shuffle player 0 deck shuffleDeck(1); // Shuffle player 1 deck - //return false; - // Fill each players deck with their cards - //createDecks(); - // Play shield from top of each players deck to the maximum allowed (4 typically) for(let currentPlayer = 0; currentPlayer <= players-1; currentPlayer++){ board.playShield(1, 'deck', currentPlayer, maxShield); @@ -1111,79 +1106,6 @@ function clickableCheck(cursorX,cursorY,itemKey){ } -function createDecks(){ - // Create a 'realDeck' element for each player - for(let i = 0; i < players; i++){ - item.push(itemCount); - boardElement[itemCount] = 'realDeck'; - player[itemCount] = i; - // TODO: Added these in to prevent error - // In future want to remove, and add isset checks for non-used data - cardStatus[itemCount] = null; - listPosition[itemCount] = null; - cardFace[itemCount] = 0; // Deck is facedown, as there's no cardArt - itemCount++; - } - - // Loop again and create the deckLists - for(let i = 0; i < players; i++){ - createDeckList(i); - } - -} -// TODO: USE DATABASE FOR THIS!!! -function createDeckList(playerId){ - // TODO:Create the deckList by loading the deckDB - // For now pulling from a deckList array that uses a cardArray - let deckList = null; - if(playerId == 0){ deckList = deckListPlayer; } - if(playerId == 1){ deckList = deckListOpponent; } - - for(let deckItem = 0; deckItem < deckList.length; deckItem++){ - // Create new item for ECS - item.push(itemCount); - // Set card data for new item - // Use the ID from the deckList of player, and return the card of that ID from cardList/DB - // For now, needs to be -1, as ID1 in decklist refers to ID 1 of carlist which is INDEX 0 - // TODO: Make it use the cardList ID, not the index - cardData[itemCount] = cardArray[deckList[deckItem]-1]; - // Set to base position of 'deck' - boardElement[itemCount] = 'deck'; - // Set Attack, ManaCost, ManaColours TODO: When these are implemented seperately - - // Set the player - player[itemCount] = playerId; - // Set the position in the deck (as was added), will be shuffled on game start - listPosition[itemCount] = deckItem+1; - cardFace[itemCount] = 0; // Start with all cards face down - cardSprite[itemCount] = [0,0]; - // Temp sprite set based on colour TODO: Change to set correct sprite from DB - console.log(cardData[itemCount].colour); - switch (cardData[itemCount].colour){ - case 0: // White - cardSprite[itemCount] = [0,0]; - break; - case 1: // Blue - cardSprite[itemCount] = [0,1]; - break; - case 2: // Red - cardSprite[itemCount] = [1,0]; - break; - case 3: // Green - cardSprite[itemCount] = [1,1]; - break; - default: - break; - } - - // Increment the itemCount to prevent overwriting stuff - itemCount++; - } - let cardsInDeck = board.getItems(null, playerId); - - shuffleDeck(playerId); -} - function shuffleDeck(playerId){ // Create a tempDeck array of same length of the player deck diff --git a/public/index.html b/public/index.html index 265c1de..72d0112 100644 --- a/public/index.html +++ b/public/index.html @@ -16,6 +16,8 @@ + +
@@ -58,7 +60,7 @@
- +
diff --git a/public/main.js b/public/main.js index 433553f..c30d765 100644 --- a/public/main.js +++ b/public/main.js @@ -165,24 +165,22 @@ socket.on('responseGetCards', function (data) { }); // Testing getting cards from server/DB -function requestDeck(){ - console.log('+ requestDeck'); - socket.emit('requestDeck'); +function requestStartGame(){ + console.log('+ requestStartGame'); + socket.emit('requestStartGame'); } -function responseGetDeck(data){ - console.log(data); +function responseStartGame(data){ if(!data.success){ alert(data.message); return false; } return data; } -socket.on('responseGetDeck', function (data) { - console.log('<< responseGetDeck'); - responseGetDeck(data); - console.log('Load board?'); +socket.on('responseStartGame', function (data) { + console.log('<< responseStartGame'); + responseStartGame(data); if(data.success !== true){ - alert('Err with responseGetDeck. '+data.message); + alert('Err with responseStartGame. '+data.message); } // Pass only the data to loadBoard loadBoard(data.message); diff --git a/server.js b/server.js index 1f8ff0a..304a5cc 100644 --- a/server.js +++ b/server.js @@ -40,47 +40,33 @@ for (let roomId = 1; roomId <= numRoomsToPreGen; roomId++) { createRoom(roomId); } -// For testing -cardGen.requestDeck(); - -function requestDeckStart(socket){ - // For future: - // Don't try to use promises between server/client - // It's painful and doesn't appear to work. Instead, let client have a loading - // screen, or wait for a while before doing something that requires server data - // like loading the decks... Then have the socket.on clientside trigger - // whatever functions, and stuff needs to happen - // Wasted so much time trying to do async server-client stuff. Don't bother - response = {success: false, message: 'Failed requestDeckStart() server.js'}; +// For testing to see console logs +//cardGen.requestDeck(); + +function requestStartGame(socket){ + response = {success: false, message: 'Failed requestStartGame() server.js'}; cardGen.requestDeck().then(data => { response.success = true; response.message = data; - io.to(socket.id).emit('responseGetDeck', response); + io.to(socket.id).emit('responseStartGame', response); }) .catch(err => { response.message = err; - io.to(socket.id).emit('responseGetDeck', err); + io.to(socket.id).emit('responseStartGame', err); }); } -// End For testing function onConnection(socket){ console.log('+ User connected'); console.log(''); - socket.on('requestGetCards', function(deckId, playerId) { - requestGetCards(socket, deckId, playerId); - }); // New testing fella (working afaik) // TODO: request specific deckId/playerId (and multiples, i.e. get 6 decks at same // time, based on deckId/playerId combo. Maybe pass as array [deckId, playerId],[deck - socket.on('requestDeck', function() { - requestDeckStart(socket); - }); - socket.on("exampleEvent", (data) => { - io.emit("exampleEvent", "hello from server"); + socket.on('requestStartGame', function() { + requestStartGame(socket); }); socket.on('requestRooms', function(filter) { @@ -242,23 +228,3 @@ function requestJoinRoom(socket, playerName, roomId){ } -// Change to Decks, or 'getPlayerDecks' for the game -// Could also be a specific deck if player clicks into one? Although maybe when entering -// decks they get all their decks (maybe just id actually) then load from there? -function requestGetCards(socket, deckId, playerId){ - console.log(deckId); - console.log(playerId); - let response = {'success':false, 'message':'Nothing happened'}; - response.success = true; - - // Await promise, once it's done get the data, if errors send err - database.getCardsFromDeck(deckId, playerId).then(data => { - console.log(data); - response.message = data; - io.to(socket.id).emit('responseGetCards', response); - }) - .catch(err => { - response.message = err; - io.to(socket.id).emit('responseGetCards', err); - }) -}