3

I am new in javascript and php. I am creatng an admin panel in which I have an option for the user to play game. But the issue is, every game have a specific time period say 30 mins. So, what I want is that if a user have started the game, the count down must be started and if user once switch from that page to another page, still the counter must be counting and after 30 mins it should end the game.

For example I am on http://www.examplec.com/Game1 my count down of 30 min will start. If I switch from that page to another like http://www.example.com/order then the counter should still count the total time and when its expired, end it and send query to database.

Kindly reply if anyone know the solution. I have already find a solution using session but I want more efficient solution. One more thing a single user can play more than 1 game.

Jenz
  • 8,280
  • 7
  • 44
  • 77

3 Answers3

0

when your game start set a session of current time like this

$_SESSION['game_start_time'] = strtotime(date('d-M-Y g:i:s A')); // it will give you complete current timestamp.

and now check it on every page by including

if(isset($_SESSION['game_start_time']))
{
   $game_start_time = $_SESSION['game_start_time'];
   $current_time = strtotime(date('d-M-Y g:i:s A'));
   $time_diff = $current_time - $game_start_time;

   if($time_diff>(30*60))
   {
        //expire 30 minutes your code is here
   }
   else
   {
           // action if require to do when below 30 minutes of game start.
   }   
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

What you could do is create a table to keep track of the time, this is not the most efficient way but it would be secure.

So create a new table called gametrack with the following fiels:

id userid gameid timestarted etc

so when a user starts a game you insert a record with user info.

Next you need to edit the game page. In the game page you could place a jquery code to request for update on the time.

function gameStatus(){
     $.ajax({
    url: 'status.php?gid=[GAMEID]',
    success: function(data) {
        if(data == 1) {
            //DO SOMETHING, REFRESH THE PAGE, STOP THE GAME ETC
        }
    }
});
}

setInterval("gameStatus()",10000);

the code above would request status.php every 10 seconds, you need to pass the gameid to the file and assuming that the user is registered you can use session to get user info and return 1 if 30 mins has passed.

You can mix this solution with Satish's Answer to use Sessions instead of Databases and still get a live count down with the jquery code above.

Ahoura Ghotbi
  • 2,866
  • 12
  • 36
  • 65
0

You can try this with localStorage

When you want to set variable:

var name = "value";
localStorage.setItem("someVarName", name);

And in any page (like when the page has loaded), get it like:

var Name = localStorage.getItem("someVarName");

Browser compatibility caniuse.com/namevalue-storage

Demo

Prateek
  • 6,785
  • 2
  • 24
  • 37