I have a page on my site where you can play a game. When you die in the game, a function called "playerIsDead();" is called, then the game closes (The game screens are prompt();s and confirm();s shown one after another, so by "the game closes", I mean the page stops showing popup messages.). The playerIsDead(); Function:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
};
I want to make the function increase a variable, totalDeathCount, by one each time, like this:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
totalDeathCount++;
};
So, my question is, how can I store totalDeathCount to the server, so I can display it on the page? I don't want it to show how many deaths have happened locally, I want it to show how many worldwide deaths have occurred.
Any help would be much appreciated!
You could use a MySQL database and store the value using PHP. Or you could simply use javascript's localStorage to store them locally on the device.
var newDeathCount = localStorage.getItem('totalDeathCount') + 1;
localStorage.setItem('totalDeathCount',newDeathCount);
Then you basically stored how many times they have died. Not in a web server but this is an alternate solution.
1) Decide how and create something to persist the information. E.g. write it to a file, store it in a database, etc.
2) Write a simple php script to store the data. (or implement it as part of your existing php backend if available)
3) Make an ajax post request to send the data to the script.
For implementation details use google and your imagination. ;)
Related
I've got a short question. I want to develop a little script on our intranet.
The requirements are:
a button, which count +1 if you click on it
just logged in users can count
all other users should see the counter
I'm a beginner in JS and i only know the localStorage function, but i want to save the counter on the server, so that everybody see's the same status.
Thats what I got, but its just the localStorage, so every computer has their own status of the counter.
if (localStorage.getItem("counter")!=null) {
counter = Number(localStorage.getItem("counter"));
document.getElementById("counterValue").innerHTML = counter;
}
Do you know what I mean? Thanks for the help and sorry for my bad english :)
You need to keep the 'counter' on the server. You should keep it in some kind of persistent storage (not memory, since the memory can be re-set):
simplest is file system (file)
DB (e.g., MySql)
cloud (e.g., AWS S3)
then to get it from storage and present to all users. If you need the value to be presented for all Live, then you'll have to use some solution for that like SignalR.
I want to use a linux device like a BananaPi with a socketcan-compatible can-controller to connect to a automotive can-bus and show its data in realtime on a webpage, which should be hosted on the Pi.
The data should be listed as hex-values and visualized via graphs (the different signals, for example the current speed).
After some research I discovered node-can and I could get managed to show the can-messages as a list on a webpage. But I noticed, that the messages come with a quite huge delay (~2 secs) when there is a huge busload (I sent can messages in a 1 ms period). The same delay occurs, if I use the following minimalistic example:
var can = require('socketcan');
var channel = can.createRawChannel("can1", true);
channel.addListener("onMessage", function(msg) { console.log(msg); } );
channel.start();
I am absolutely new in this topic but I think, that nodejs isn't the best choice to realize this project?
Are there any other (better) methods to realize such a system?
I could imagine something like a C-backend, for example based on candump (with this program no delay occurs at the same busload), and a frontend realized with javascript, html and css. But I have no idea how to get those different single programs together. Could you give me a keyword so I have a starting point for further research (websocket?!)?
I also thought about writing the can frames in a sql database and grab them from the database for the webpage-gui but I have no idea, if/how this works and if this is fast enough....
Thanks in advance!
I will do my best to explain my problem to avoid people pointing me into different directions.
I got an assignment from business people. I don't know the terminology. It is very similar to email notification, message notification on facebook, notification on social media games.
For example, people are sending 20 email messages 5 minutes ago. the screen will display 20 (see attachment). Now, 3 more messages have arrived, the web page should update the number to 23.
Facebook has similar concepts when our friends like/comment message. The notification changes. Same thing is true on social media game. Any status changes on our game, it will reflect it.
I kind of have idea on how to do it cosmetically (on CSS). How to do it using javascript/asp.net. Do I need to postback in order to refresh the message. I never pay attention to that on facebook/yahoo email/social media games. All I know is something is happening, the webpage is updating the status.
Sorry the question is too broad. If someone can help me to point to the right direction, I appreciate any help
HTML5 introduced a very interesting concept call Server-Sent Events in which server can dynamically connect to the client and send data.
Eg:
var source = new EventSource("demo_sse.asp");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data + "<br>";
};
And on server side you can write,
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
<!--Writing "data:" is important-->
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
However, some old browsers may not support this.
One other way to accomplish this task is to use Ajax call as,
function checkNewMessages(totalMessages){
return $.ajax({
url: 'demo.asp',
type: 'GET',
cache: false,
data: {
totalMessages: totalMessage;
}
});
}
checkNewMessages(totalMessages).success(function (data) {
// display the data wherever you want
});
//Checking for new messages every 5 seconds
setInterval(checkNewMessages(totalMessages,5000));
Whatever you write within your Write() in server side will be displayed here. Now to constantly check for the new messages you can call the above ajax function with the help of setInterval()
There are many ways to do this, depending on how real time you need it to be.
The most common way is to use JavaScript with an XmlHttpRequest to call an ASP.NET page which returns the number of messages, I recommend you use a JSON object for this. The benefit of this approach allows you to request data from the server without the user experiencing a full page refresh. You can use JavaScript to set it to call every x seconds depending on your requirements.
Collectively that is known as AJAX, using a JavaScript library such as JQuery can make this much easier.
I've created a whiteboard web app where a multitude of registered users, login and start drawing on the html5 canvas. I devised the 'multiplayer' aspect of the game through python websockets and the login is made with php, currently the canvas page has a 'session_start();' so I can be able to add a feature to see who's currently using the application and I feel it may come in hand for the 'turn based' aspect as well.
Now I'm trying to prevent users from being able to draw on the canvas at the same time, if possible i'd like every user to have a fair turn at drawing on the canvas. I'm not sure how I'd accomplish this but I feel that Javascript will most definitely be the logic behind this.
Any advise or suggestions as to how I'd go about achieving this feature?
EDIT
Ok since nobody has any answers or suggestion I'll try and provide to you what I've attempted so far, I think it may be on the right direction even though it doesn't work:
var player = document.getElementById("inputnameid").value;
var currentPlayer = player; // player class
//array of player objs.
var array1 = [player]; // list that OnCurrentPlayerEndTurn cycles through to choose user
// call this at the start of the app
function OnStartTurn()
{
currentPlayer.OnBeginTurn();
var inputs=document.getElementById('inputty');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=false;
}
//This function will activate the GUI so the user can now act
}
// call this function when setTimeout is 10 seconds
function OnCurrentPlayerEndTurn()
{
setTimeout('OnCurrentPlayerEndTurn();', 10*1000);
change currentPlayer variable to the next player in line
OnStartTurn(); // will cause the next player to begin his turn
}
Your question seems to be focused on the front-end code, which, while important, is not the critical part of this problem. As you've noted, the core of a turn-based game is the round-robin passing of active players. You probably want this to be done server-side: it's much easier to coordinate the various players from there.
You'll maintain a list of the players in a given game on the server. Before the game starts each client will register with the server and an identifying user id is stored there. Then in each round, the server allows each player a turn. The turn order is of course up to the specifics of the game, but the general idea is the same whether turn order is fixed or fluid.
As each player's turn comes around, the server sends a ticket to that player's client. This is essentially a one-time pad (OTP) concept: generate a random token that is hard to guess (so don't use just an increasing integer, but instead some cheap hash function or the like). The client then sends this ticket along with the request for the move they would like to make, and the server validates that the ticket corresponds to the currently active player before taking any action.
Depending on the rules and requirements of the game, the server can then immediately invalidate the ticket (e.g., chess), can wait until an 'end of turn' move, or can invalidate the ticket after some amount of time. The server then generates a new ticket for the next player to go.
The client-side code follows naturally from this architecture. All inputs can be disabled by default, and only enabled when the client holds a valid ticket. If the ticket is designed to time out, you probably want a method of querying the server to determine if it is still valid. If the user is always responsible for ending their own turn (explicitly or implicitly) you can get away without that.
I have a program written in c++ that reads values from this board. Anyways that part is not important. What I have is data that is constantly changing and I will like to graph that data. I was hoping to use a web browser to display the data since there are so many open source graphs and charts out there written in JavaScript. So my problem is to send data to the browser from my c++ program
I already investigated and UDP is not available in browsers yet so I will have to use TCP. TCP websockets are not that fast and I was thinking about using html5 localstorage instead. By that I mean have my c++ program write to the database on localStorage then javascript will wait for the value of that variable to exist and invent some sort of protocol that will make that work. Local storage is really fast for example :
<script type="text/javascript">
var counter = 0;
window.onload = function () {
function Test() {
counter++;
localStorage.p = counter + ""; // perform write
var read = localStorage.p; // perform read
if (read == "5000")
alert((new Date() - now)); // shows 45
else
Test(); // loop again
}
var now = new Date();
Test();
}
</script>
that script takes 54 milliseconds and it reads AND writes 5000 times! That means that instead of creating a plug-in for the browser next time I will just implement some sort of protocol that will enable me to exchange information using the localStorage. For example I could have the browser waiting for the variable x to exist. Once it exist I then creates a variable y by the browser notifying the c++ program that it is ready to receive data and so on. localStorage is just a sqlite database located on C:\Users[USER]\AppData\Local\Google\Chrome\User Data\Default\Local Storage
I haven't seen anyone online that uses this approach. Maybe it is too dangerous and Sqlite cannot handle multiple threads that good and I will be wasting time creating this program.
So should I start implementing this protocol? Should I use websockets? Or should I give it a try to https://stackoverflow.com/a/10219977/637142 ?
I would go with node.js as middleware from your C++ to the browser, instead of using directly websocket (been there done that) go with http://socket.io/ that will make your life much easier :)