Turn based web game in PHP - communication issue - php

I am working on a turn based web game in PHP5.
This is pretty simple game, a kind of board game: two people join a "session" and they play until one of them wins.
My problem in nutshell:
User A and User B play a game.
User A finished his turn
Request will be sent to the server to perform necessary operations.
Now it is time for User B to move..
But how could I notify User B about this?
I mean, now the server has to communicate with the other user, the one that is inactive, not the one that initiated the request.
I know that this could be implemented using some kind of periodic AJAX call that checks whether the opponent finished his turn etc, but such a thing generates a huge number of requests.
Isn't there a better way to solve this?
I'm thinking of something like this:
User A's turn ends
Server saves his score
Server contacts User B
User B's turn gets started.
Is this possible using PHP and comet-style requests somehow? Or is there a better way to do this?
Any help would be appreciated!
Thanks in advance!

An in-memory database of currently running games/turns, and one check from user B every 1.5 secs or so, won't really generate a huge number of requests, or server load.
You can even have a polling scheme like 7s, 5s, 3s, 2s, 1s, 1s and so on, according to what fits your game.
You can even leave PHP out entirely, if you just touch a session file whenever a turn is done, and check the last-modified client side.

Php Sockets !
http://php.net/manual/en/book.sockets.php
server listen
client_a connect
client_b connect
client_a send start game to server
client_a send move to server
server send play client_b
[...]

Related

Looking for MySQL performance advice for database-heavy app

I'm creating a messaging app using jQuery, PHP and MySQL. Every time a user enters a message, I store it in a MySQL table. On the receiving users end, I basically just added a Javascript timer to check the database every X number of seconds for new messages.
The system works well but is this going to be a performance problem? For example, let's say I have 1000 users and I'm hitting a MySQL table every 5 seconds for each user.
Can anyone suggest a better method?
With your actual architecture, your SGBD will get a heart attack :)
The solution reside on implementation of Web Socket
in back-end only 1 instance of PHP check if there is a new update on database, if there is, PHP can invoke a web service to your Web-Socket Server (like NodeJS), and Server send the message to the client

Updating a PHP text-based game continuously

I'm building a multiplayer game in PHP. Each game is split into stages that last a set amount of time - currently 2 minutes. In each stage, players work together for a set amount of time until the game either advances to the next stage, or the stage (and hence the game) is lost, and a new game starts again.
I have a vision of playing the game on an HTML page, where users can see how much time is left in the current stage through a constantly updating countdown clock. When the countdown clock reaches zero, the game either advances or ends, and the result is returned through Ajax. What I'm having problems with is the (theoretical) thought of 100 players playing the game simultaneously.
How do I call the update script? If I call it by running PHP, which player's browser calls it? If a player's browser refreshes the content one second before the stage actually finishes, what happens?
Is PHP the right language for a game like this?
"Is PHP the right language for a game like this?"
Yes, if you do it right. Here's how you do it...
Using a method called Comet, you can have multiple clients pulling data from the server, but only when that data is updated. It works something like this:
Client A makes pull request to server.
Server waits, keeping connection to Client A open.
Client B makes pull request to server.
Server waits, keeping connection to Client B open.
Client A pushes new data to server.
Server pushes new data to Client A and Client B through still open connections.
Client A makes pull request...
etc...
In other words, it means that all clients receive up-to-date information immediately it is pushed to the server by any client. This means you don't have to implement a "refresh every x seconds" system, which is good for 2 reasons:
1) You don;t waste time and bandwidth make requests to the server when nothing has happened;
2) All the clients get data pushed to them at the same time, that's absolutely up-to-date and not x seconds old.
In practice, Comet is implemented via AJAX. Google for some examples of Comet- it's pretty simple, and extremely useful.
In client-server games, your server should be running a simulation in parallel to the client's simulation (the game).
Usually the server simulation is authoritative, so that when, say, a match is over it will inform all clients in the match that the simulation state changed to "match over" or whatever. The client will then lock the UI or present a "Game Over" message or announce winners-- whatever you want.
So for you, your server should run the count down timer, while the clients keeping polling (via AJAX or WebSockets) the server for state changes. When the server's timer hits zero, the next time clients poll the server, the server will say, "Hey, yo-- the game's over!".
Edit
I'd also like to say that PHP will probably work, but you have to understand that PHP was built for web services, not games. Simple games like tic tac toe or checkers or chess can become quite complex when you toss in multiplayer functionality. Simulations often require threading. PHP can do threading but it can get very ugly if you don't know what you're doing.
Well, if you are using the PHP session system, the script will recognize the Ajax request as being from the same user who (for example) logged in into your game.
One second before the stage finishes, well you could return in PHP the time left to the stage so the javascript counter stay synchronized? Both the server and the clients must be aware of the status of the game, else expect hackers somewhen.

Communicate from one page to another? JavaScript, PHP?

I'm building a prototype where on one page A I have a controller. Imagine a TV remote. On another page B, independent of form A -- it can be a different screen/computer -- with some elements X, Y, and Z that are going to be animated by the remote on page A.
My first idea would be:
Remote on page A saves an action wanted and sends JSON.
I create a listener on page B that reads the JSON to listen to what action to trigger.
I wonder if this the right direction.
It is just for a prototype so it doesn't have to be a production-perfect idea.
You can use web sockets for this.
Let's assume you're using 2 computers, both pointed at the website, as this technique could work in both scenarios.
If it's just a prototype, you could just simply have your page B poll the server every 5 seconds to look for updates that were submitted by page A.
However, in reality, for a production app with thousands of users, this could consume lots of bandwidth and put a heavy load on your server. To compensate for the load and bandwidth usage, you could increase the polling rate to 10 seconds, or 30 seconds, but in response to this change your users would experience delays while they wait for the browser to request an update from the server.
In a production app, many developers are turning to Comet as a solution. Comet is basically a term given by Alex Russell for a technique that involves using the request/response cycle to simulate server-push.
The general idea is that the browser makes a request to the server, and the server holds that connection open indefinitely. The connection remains open until another user posts an update to the server, in which case, the server then sends a response to the connected users.
The Dojo and Jetty team have demonstrations where they show that this technique can scale to 20,000 connections, when using continuations.
While I think you can carry out your experiment just fine with a database and/or some session variables, if your want to learn more about Comet on PHP, check out How to Implement Comet with PHP. Good luck!
UPDATE:
I also wanted to say that you definitely have the right idea for how to conceptually think about your message passing with JSON:
I create a listener on page B that reads the JSON to listen to what action to trigger.
I really like how you are thinking about passing a message that then tells the page what action to trigger. If you think about it, you could reuse your message passing concept to call other commands so that you avoid reinventing the wheel when a new command comes along that you need to call. Regardless of whether you poll, use Comet, or use WebSockets, it's a great idea to think about abstractions and generic, reusable data transports.
You could do this either with polling (having page B constantly poll for updates from the server) or use a server push technology like server sent events or websockets.
Yes, that would work. You could also just make it the same way you would make a vector line animation. Send the "commands" for movement to a server and record them (in a database, file, whatever) the client program can then request and redraw the movement smoothly any time and anywhere.
Using a cron job to execute Page B for every x unit time will make you check for any latest updated json (queried/returned output according your logic) from Page A. This way, you can use new updated json from page A and do your further task...

Is there away to know if a user is still on my site - instead of using cookies or sessions

I am wondering, if there is a real-time way time ping a user and see if that user is still only.
My site uses jQuery, PHP and CRON jobs
so I was wondering what would be the best way to check that the user is still online.
Each user is issues a cookie aka session key but I don't want to just go by that.
I know real-time analytics are able to it, using javascript so I wonder if I could also do the same thing.
Thanks
it could be done via continues ajax call from client but not recommended.
I suggest use flash or something like that to reduce number of ajax request to the server.
Any method you choose will work the same as what you mentioned, it will just update more often.
You can use an ajax call that pings the server every x seconds and as soon as that stops you'll know they left at most x seconds ago.
A similar option is to use WebSockets or Flash to hold a socket connection with the server and mark them as logged off the moment that socket connection is broken.
Both these options are a bit more difficult to scale than sessions and cookies.
Question is very confused and ambiguous.
No you can't 'ping' a user. You can ping an IP adderss - but the IP addresses you see at your server probably don't map on a one-to-one basis with users.
Which user? All users? Why? What will you do with the information? Have you got a better reason than "I don't want to" for not using session data?
"I know real-time analytics are able to" - then you must know the method they use to do this - or are you just buying the sales speak?
I guess only way to get "real-time" data is to use web-sockets.
another way which is less acurate ( with delay ) is to use repited ajax calls. say 1 per 60 seconds.

Instant Challenge/Notifications system

My setup: Currently running a dedicated server with an Apache, PHP, MYSQL.
My DB is all set up and stores everything correctly. I'm just trying to figure out how to best display things live in an efficient way.
This would be a live challenging system for a web based game.
User A sends a challenge to User B
User B is alerted immediately and must take action on whether to
Accept or Decline
Once User B accepts he and User A are both taken to a specific page
that is served up by the DB (nothing special happens on this
page,and they dont need to be in sync or anything)
The response from User B is a simple yes or no, no other parameters are set by User B, the page they are going to has already been defined when User A sends the challenge.
Whichever config I implement for this challenge system, I am assuming it will also work for instant sitewide notifications. The only difference is that notifications do not require an instant response from User B.
I have read up on long polling techniques, comet etc.. But im still looking for opinions on the best way to achieve this, and make it scalable.
I am open to trying anything as long as it will work with (or in tandem) to my current PHP and MYSQL set up. Thanks!
You're asking about Notifications from a Server to a Client. This can be implemented either by having the Client poll frequently for changes, or having the Server hold open access to the Client, and pushing changes. Both have their advantages and disadvantages.
EDIT: More Information
Pull Method Advantages:
Easy to implement
Server can be pretty naïve about who's getting data
Pull Method Disadvantages:
Resource intensive on the client side, regardless of polling frequency
Time vs. Resource debacle: More frequent polls mean more resource utilization. Less resource utilization means less immediate data.
Push Method Advantages:
Server has more control overall
Data is immediately sent to the client
Push Method Disadvantages:
Potentially very resource intensive on the server side
You need to implement some way for the server to know how to reach each individual client (for example, Apple uses Device UUIDs for their APNS)
What Wikipedia has to say (some really good stuff, actually): Pull, Push. If you are leaning toward a Push model, you might want to consider setting up your app as a Pushlet

Categories