I am creating Tic Tac Toe in Angular, and I'd like to track stats from the game over the session, i.e. stats that don't reset when a new board object is created.
I have a TicTacToeComponent that creates a new board and that's about it, and the TicTacToeBoard object has all the fields and logic for the game. The user can create a new board using a button tied to newGame() in TicTacToeComponent or of course a new board is created when you load the page. Obviously tracking stats in the board object won't make sense. I was thinking a session object that creates each game is best, but I'm not sure how I would be able to inject the stats from that into the TicTacToeComponent template... How can I track stats over a whole user session which might have multiple games created? Is this some kind of observable pattern? How can I implement this?
app
|--tic-tac-toe
| |--tic-tac-toe.component.* (imports and instantiates board)
|
|--app.component.* (routes to welcome screen and t-t-t.component
|
|--tic-tac-toe-board.ts (board class, probably should be moved)
Solving this might also allow me to keep a game even when routing to another page and back.
Source code
You can have a Stats component and whenever a game comes to an end, you send an event from the TicTacToeComponent with the relevant information (i.e. game won by player X) and store that in a property of the Stats component.
This would allow you to keep track of different games, but obviously all the information would be lost if the page is refreshed. If you want a more complex solution, you need to implement it server-side.
Since you may not want to use a database, you can use components to create variables in localstorage localStorage.setItem('gamesWon', gamesWon++);
Then you can make an observable or just a getter anywhere in your app to get the data with localStorage.getItem('gamesWon);
So far, I have not found a good way to sufficiently store indestructable objects in memory without some sort of database or using local storage. Following this thread to see if others have found a good solution.
Related
I'm new to Javascript and as an exercise am doing a browser version of a board game.
Since I'm so new to the HTML world, I'd love to know a bit more how asynchronous games on websites like Boiteajeux.net work.
I can go through the steps in my game (I've programmed a lot of the logic), but I'm unsure how to "save" that information such that when the game loads again, the information of the changes have reloaded.
I don't know much about databases and how to store it, so maybe that's the hole in my knowledge.
I'd love to be able to, with each "move" in my game, have it be a permanent change to the webpage such that if I hit refresh, it doesn't return to the pre-game state.
How does this work?
If you just want local persistent state between refreshes, you could look into using localStorage. LocalStorage is a read-only property of the Document's storage object. Unlike SessionStorage, the data stored does not expire.
You can set key items in local storage like so:
localStorage.setItem('myKey', 'some data');
You can read the stored item like this:
var myItem = localStorage.getItem('myKey');
There are also .remove('myKey') and .clear() methods for deleteing items and clearing the storage object.
Assuming your game state is stored in some state object, you could store the stringified object when the state updates.
Something like:
localStorage.setItem('gameState', JSON.stringify(currentState));
And access the state on browser load like this:
var currentState = JSON.parse(localStorage.getItem('gameState'));
This will be a lot easier than setting up a database, but if you want access to your game's state from another browser you will likely need to use a database.
I'm a computer science tutor, with a lot of experience teaching Python and Java but without a lot of web experience. I'm now working with a high school student who has been assigned a project that he wishes to implement in HTML and JS. So this is a good chance for me to learn more about this type of application.
It's an application for taking food orders on the web and showing an illustration of your order. You choose a main dish and any custom alterations. Then you choose another course of the meal, maybe a salad and any alterations. And so on. The first page it shows you will show an empty plate. You choose a course to customize and it will take you to a page that shows options, then another page with further options, and so forth. Each time you are finished configuring an option, it will take you back to the starting page and show a picture of the meal so far on the plate (which was formerly empty).
The main part I'm unfamiliar with is handling persistent state. Although each page will have a unique structure of images (possibly a canvas) and buttons, it will have to remember the order as configured as it loads each page.
I'm wondering what a simple way of handling this is. This is a high school student with very little prior programming experience, and I'm allowed to help her, but it has to be within her grasp to understand overall.
Perhaps sessionStorage is the best bet?
Regarding possible duplication of Persist variables between page loads, my needs are a lot more complex than that question--I need to store more than a single global variable, and I may need a framework to simplify this. In particular, I'm interested in doing this a way that is simple enough for a high school student to understand so that he can implement some of it himself (at least some of it has to be his own work). I don't know if using a framework will make the job simpler (that would be good) or whether it will require more effort to understand the framework (especially relative to an inexperienced student -- not good).
Perhaps sessionStorage is the best bet?
If you want the state to be automatically expired when the browser session ends. Otherwise, use localStorage, which will persist longer than that.
It's important to remember that web storage (both sessionStorage and localStorage) only stores strings, so a common technique is to use it to store JSON that you parse on load, so you can have complex state. E.g.:
// On load
var state = JSON.parse(localStorage.getItem("state-key"));
if (!state) {
// None was stored, create some
state = {/*...default state...*/};
}
// On save
localStorage.setItem("state-key", JSON.stringify(state));
Note that this bit:
var state = JSON.parse(localStorage.getItem("state-key"));
if (!state) {
relies on the fact that getItem returns null if there is no stored data with that key, and JSON.parse coerces its argument to string. null coerces to "null" which will be parsed back into null. :-)
Another way to do it is to use ||:
var state = JSON.parse(localStorage.getItem("state-key")) || {
// default state here
};
I am trying to create blackjack with JS and React.
So far I have got most of it working but my main problem is that everytime react renders it changes the cards and the order of the deck etc. I just need a simple way to store data and so even when react re renders it keeps the order of the deck (array of objects). I am use to firebase but that seems quite heavy for something like this. any ideas? i saw local storage might be an option too but wanted peoples opinions.
I would like to create multiple game instances.
Currently, on the client side a game template is rendered
Template.game.rendered = function () {
graph = new Graph("#graph", nodes);
};
//
function Graph(selector, nodes) { //code here };
This give me a single game instance. Now I would like to create more game instances, hosted in a 'lobby'.
For this I have a collection.lobby.
id,
host,
players,
status,
invitedplayers,
url
This functionality works: I can set the collection values and retrieve them under the assigned url.
Now I need to create a new game instance with this.
I think that I need a Meteor.method that 'renders' a new game container at the specified url. Is this correct ?
How do I have to combine these elements ?
There is enough sample code on github, but everyone does this a little different, so that I have not been able to analyze and understand how to do it.
The answer seem so be here Loading templates with iron router
Ed Die,
If you take a look through the full api documentation for Meteor, and search for the keyword "chat", you'll find examples of chat-room instances being created, which seems very similar to what you're trying to accomplish.
You may or may not need to have a unique url routed, for example www.mygame.com/game/MONGO_ID_HERE or a different generated ID.
The approach could be that each game url or session id get's stored into the database, that game's session data get's stored into that document, and when someone is playing the game, they get assigned that session's id until the game is over.
I hope this helps.
I'm new to Flux/React and I'm having a hard time understanding some of the fundamental architecture decisions:
I know all stores are meant to be singletons, but are they all created at app start, or can the lifetime of a store be smaller, specific to the user's actions?
Can I have multiple instances of the same store type, each initialized with a different context?
Unfortunately, all the examples I've seen seem too simplistic to answer these questions. Let's start with Facebook's chat app example. There are multiple threads each with messages. MessageStore holds all the messages for the entire app and a method called getAllForThread(id) returns a filtered subset of messages. When a message comes into ANY thread, it emits a change notification that causes the MessageSection react component to re-fetch data (regardless of which thread the user is viewing). This obviously doesn't scale. What if we had 10,000 threads each with lots of message activity? Here's how I decided to solve the issue:
Each MessageStore is initialized with a thread id.
Create a singleton MessageStoreFactory that creates and manages MessageStores.
When the user clicks on a thread, instead of the React component subscribing to a global MessageStore, it asks the MessageStoreFactory for the MessageStore for that specific thread.
If the factory already has a MessageStore for that thread, it returns it. Otherwise it creates one, kicks off an async task to fetch the initial data for it, and returns it.
When the React component is torn down (let's say the user navigates away from it), it notifies the Factory that it's all done with the Store. Using reference counting or some other cache logic would allow the Factory to prune unused stores.
How far off base am I with this approach? Is there a simpler approach that still scales?
It seems easier to make smarter data fetching according to the thread which user is viewing. Could I see this facebook's example at some blog-post or presentation?