Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 04 Feb 2008
Online Last Active Today, 12:22 PM

#5225326 Confused. Can I use PHP to make a game?

Posted by fastcall22 on 24 April 2015 - 02:52 PM

Thanks for responding. If you don't mind, could you explain what's going on here?

It looks like you're using more than just JavaScript and PHP here? I really want to stick to HTML (structure the page), CSS (make it look nice), PHP (perform server-side operations), and maybe JavaScript (possibly improve client interface), but nothing else. I'm pretty familiar with HTML and CSS at this point though.

Ah, sorry if I have confused you. The language I use here is coffeescript, which is a language that compiles into javascript. The compiled javascript of the code I posted is here: http://pastebin.com/0di9bsVs.

So, here's whats going on.
$.ajax() queues a POST request (not unlike submitting a HTML form element) to be sent via XHR in the background.
.success and .error chains respective callbacks to be executed when the request completes. We use an additional deferred object to encapsulate all server errors, decoding errors (malformed json), and any application errors:

Bad data or server error: ajax.error() -> deferred.reject with HTTP-error code or jQuery parsing error
Good data, success=false: ajax.success() -> deferred.reject with application error message
Good data, success=true: ajax.success() -> deferred.resolve with payload data

From here we return the deferred object which can then be act upon further, by chaining .done (resolve) and .fail (reject) callbacks to run respective game code and rebuild the page with state.

Note: This is for a responsive game.

For something like partial-page refreshes, you could do something like the following:
<?php # stats.php
include "game.php";

$player = get_player(); 
$stats = $player->stats;

<div class="stats"><?php
	foreach ( $stats as $name => $value ) { ?>
		<div class="stat"><?=$name?></div>
		<div class="value"><?=$value?></div><?php
	} ?>
var update_stats = function() {
    .success(function(html) {
        document.getElementById('playerStats').innerHTML = html;

btnMove.onclick = function() {
        url: 'move.php',
        method: 'POST',
        data: {
            direction: 'UP'

Pardon me, but I'll try to interpret the code. It seems like at the surface, you're still using the $_POST method to talk to the server. How is this much different from my current implementation (I'm not using JavaScript at the moment, just PHP)? Perhaps I'll understand after you explain it.

It's not any different at all. smile.png
PHP is a standard process like everything else: All communication is done through the stdin, stdout, and stderr handles. Upon each request, $_POST is auto-magically constructed from stdin, and $_GET is auto-magically constructed with CGI variables from apache. (PHP's environment variables are inherited and setup by the apache process and contains standard CGI variables like DOCUMENT_ROOT, REQUEST_URI and et al.)

#5225275 Confused. Can I use PHP to make a game?

Posted by fastcall22 on 24 April 2015 - 12:49 PM

If you are interested in the web why PHP?
Since you are going to be using Javascript anyway, why not pick one of the many html5/javascript game engines?
You can use PHP, but there are better options today: local storage and cloud sync.

Local storage and cloud sync are not appropriate replacements for server back-ends. You could use local storage, if the game runs locally and doesn't require communicating with anybody else, including the game's server.
If you're looking for alternative, more responsive back-ends, then look into using websockets with a nodejs server or separate php process dedicated to listening to websockets on a separate port.

#5225262 Confused. Can I use PHP to make a game?

Posted by fastcall22 on 24 April 2015 - 12:21 PM

Right. That's why I need a webhost that supports PHP.

Not necessarily. Well, you'll need one once you've finished your game. smile.png

Until then, you may want to consider running a PHP server directly from your machine using EasyPHP or run a full-fledged web server in a virtual machine with Ubuntu Server or some other Linux distro.

#5225258 Confused. Can I use PHP to make a game?

Posted by fastcall22 on 24 April 2015 - 12:05 PM

I'm not sure how I can use Javascript to communicate with the server in any other way.

Requests can be done with XHR and you can use a cross-browser library such as jQuery, AngularJS, or some other lightweight XHR library. Async processes are a pain in Javascript, since you can only nest async functions, but Promises make things a bit better.

# sample.coffee
# for the compiled javascript, see: http://pastebin.com/0di9bsVs
game_state =
	player_id: null
	last_update_ms: 0
	score: 0

do_update = ->
	defer = $.Deferred()

	$.ajax # nake XHR request
		url: '/update.php'
		method: 'POST'
		dataType: 'JSON'
			last_update: game_state.last_update_ms
			score: game_state.score
	.success (response) ->
		if not (response and response.success)
			defer.reject response.message or 'Unknown error occured'

		defer.resolve response.payload
	.error (response,code) ->
		defer.reject "Server returned #{code}"

	return defer.promise()

.always ->
.done (payload) ->
.fail (error) ->
	alert "An error occured\n#{error}"
# update.php
$response = [
        'success' => false,
        'message' => null,
        'payload' => null
# capture PHP errors and warnings, if desired
function hook_error() {
        global $response;
        $response['debug'][] = func_get_args();
$request = $_POST; # or json_decode php:​//input
try {
        # fill sample data
        $game_data = Game::update();
        $response['success'] = true;
        $response['payload'] = $game_data;
} catch ( Exception $ex ) {
        $response['message'] = $ex->getMessage();
header('Content-Type: application/json');
print json_encode($response);
EDIT: Stupid editor ate my post :​(

#5223786 Rate my Game Loop

Posted by fastcall22 on 16 April 2015 - 02:17 PM

★★☆☆☆ (2 of 5 stars)

Does not handle the spiral of death.
Would not recommend stepping time with programmer again.


In addition to what others have said, you may want to consider the case when the simulation can't keep up and must sacrifice updates to keep the simulation going. Otherwise, the simulation will grind to a halt.

#5223732 FastCall Is Alll

Posted by fastcall22 on 16 April 2015 - 11:06 AM

omg dsm-senpai noticed me ohmy.png

It was written in response to dsm's affection to trigraphs. I figured, why stop at trigraphs? Here's teh code. There's still room for "improvement," but whatever:

#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>
#define mod %
#define div /
#define mul *
#define add +
#define sub -
#define insert <<
#define extract >>
#define shl <<
#define shr >>
#define bor |
#define band &
#define bxor ^
#define bnot ~
#define ptr *
#define assign =
#define equal_to ==
#define addr_of  &
#define open_paren (
#define open_bracket [
#define open_brace {
#define open_angle <
#define less_than <
#define close_paren )
#define close_bracket ]
#define close_brace }
#define close_angle >
#define greater_than >
#define comma ,
#define call ()
#define member .
#define block_begin {
#define block_end }
#define stop ;
int main open_paren int argc comma char ptr ptr argv close_paren
	using namespace std stop
	string line stop
	while open_paren
		cout insert "\n> " insert flush and
		getline open_paren cin comma line close_paren close_paren
		istringstream stream open_paren line close_paren stop
		auto vec assign vector open_angle int close_angle open_paren
			istream_iterator open_angle int close_angle open_paren stream close_paren comma
			istream_iterator open_angle int close_angle call
		close_paren stop
		sort open_paren
			vec member begin call comma
			vec member end call
		close_paren stop
		cout insert '[' stop
		if open_paren vec member size call close_paren block_begin
			copy open_paren
				vec member begin call comma
				vec member end call sub 1 comma
				ostream_iterator open_angle int close_angle open_paren
					cout comma ", "
			close_paren stop
			cout insert vec member back call stop
		cout insert ']' insert endl stop
Sample run:
> 9 4 -3 4 0 7 8
[-3, 0, 4, 4, 7, 8, 9]

> -3 4 7 10 9 6
[-3, 4, 6, 7, 9, 10]

> 4 3 1 5 7
[1, 3, 4, 5, 7]

#5223303 Constant Buffers Disappearing

Posted by fastcall22 on 14 April 2015 - 07:59 PM

How are you setting up your constant buffer? Are you filling it with DeviceContext.MapSubresource and are you attaching it to the shader via DeviceContext.VertexShader.SetConstantBuffer?
Is it disappearing randomly during the program, or before the very first frame?

#5218599 c++ count lines in txt file and then read these lines without reopening a file

Posted by fastcall22 on 23 March 2015 - 02:47 PM

omg wiredcat, pls

	// read
	size_t len = 0;
	char* str = read_all_text(path,&len);
	const char* end = str + len;

	// count and allocate
	size_t line_ct = count((const char*)str,end,'\n') + 1;

	size_t ldx = 0;
	const char** lines = new const char*[line_ct];

	// process
	lines[ldx++] = str;
	for ( char* p = str; p < end; ++p ) {
		switch ( *p ) {
			case '\n':
				assert(ldx < line_ct);
				lines[ldx++] = p + 1;
			case '\r':
				*p = 0;

			default: ;

	// beep boop
	for ( size_t idx = 0; idx < line_ct; ++idx )
		printf("%i %s\n",idx,lines[idx]);

	// clean-up
	delete[] lines;
	delete[] str;

#5218480 c++ count lines in txt file and then read these lines without reopening a file

Posted by fastcall22 on 23 March 2015 - 09:47 AM

If you only need read-only access to the file, then you can avoid quite a few dynamic allocations by reading the entire file into a string, then find and replace newlines with null-terminators, adding them to a list of const char*. And, it's trivial to count the number of lines beforehand, as you don't reprocess the file or read each line and immediately discard the lines.

#5217693 Doge Indirection

Posted by fastcall22 on 19 March 2015 - 12:56 PM


#5215156 Logic for polygonizing lines where the polygon with multiple holes

Posted by fastcall22 on 07 March 2015 - 11:23 AM

You can use a library such as CGAL or use GLU's tessellators. The general approach seems to be to construct a Delaunay triangulation with all of the edges and then punch out the holes. As for determining what's in and what's out, use the winding order of the contour to determine whether or not it's adding or subtracting from the geometry.

#5214351 Convenient approach to composite pattern in C++

Posted by fastcall22 on 03 March 2015 - 08:26 PM

template<typename C, typename F>
static inline Caller<C, F> operator->*(C &c, F &&f) {

Yeah, okay. I'm totally okay with what just happened and am totally fine with how readable this is.

static ::operator->*... Yup!

#5214350 Source code with errors: http://ideone.com/eSWKwf

Posted by fastcall22 on 03 March 2015 - 08:16 PM


First: Your code was mangled when you copy-pasta'd. Here is the cleaned up code.
Second: You're missing a '#' for the preprocessor directive #define.
Third: In C++, it's usually more pragmatic to use a constant over a macro, but each is acceptable: const int SIZE = 10;
Fourth: You're missing a closing brace for your for loop after line 33.
Fifth: This has nothing to do with "3D" or "game programming" :|

#5213014 Read data from specified adress of memory.

Posted by fastcall22 on 25 February 2015 - 09:26 PM

(I think he's asking why he can't deref a void pointer.)

Then you still need to memcpy, because you cannot what to write without knowing the type, unless you store this information elsewhere:
void do_the_thing(void* write_to, const void* read_from) {
    // Nope!  How many bytes do we write?  What about copy constructors or move constructors?
    // *write_to = read_from;

    // Ok, but dangerous -- you don't know if either are Foobars and you might violate the rule of 3
    memcpy( (char*)write_to, (const char*)read_from, sizeof(Foobar) );

    // Ok, but dangerous -- you don't know if either are actually Foobars
    *reinterpret_cast<Foobar*>(write_to) = *reinterpret_cast<const Foobar*>(read_from);

int whatever(const Foobar& foo_a, Foobar& foo_b ) {
    const void* read_from = &foo_a;
    void* write_to = &foo_b;
    // sometime later...

    do_the_thing(write_to, read_from);  // Ok, both are Foobars

    const char* str = "Hello there";
    int truth = 47;
    do_the_thing(&str, &truth); // so many levels of wrong
This is also assuming that he isn't trying to ReadProcessMemory or WriteProcessMemory.

#5213011 Read data from specified adress of memory.

Posted by fastcall22 on 25 February 2015 - 09:09 PM

He doesn't want to read and write, he wants to read and write.

He doesn't want to "he doesn't want to read and write, he wants to read and write", he wants to "he doesn't want to read and write, he wants to read and write" with variables.