Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

big_malk

macrumors 6502a
Original poster
Aug 7, 2005
557
1
Scotland
I'm developing a multiplayer online card game, and I'm using PHP to sort out the issuing of cards etc, 9 time out of ten this works fine, but occasionally drops cards. I mean, usually each player (2 − 4) gets five cards, one is added to the 'pile' to start the game, and the rest are put in the stack.
Here's my code that does this:

PHP:
function initialise_table($tableID) {
		$table = $this->CI->db->get_where('tables', array('tableID' => $tableID))->first_row('array');
		if ($table['status'] == 'in-progress' || $table['status'] == 'finished') return;
		
		$deck = json_decode($table['deckOrder'], true);
		$playerIDs = array();
		foreach ($this->table_players($tableID) as $playerID => $player) {
			$cards = array_splice($deck, 0, 5);
			$cards = $this->sortArrayByArray($cards, $this->card_sort_order);
			$cards = $this->flatten($cards);
			$ret = json_encode($cards);
			$update = array();
			$update['cards'] = $ret;
			$update['status'] = 'playing';
			$this->CI->db->update('playerGames', $update, array('playerID' => $playerID, 'tableID' => $tableID));
			$playerIDs[] = $playerID;
		}
		$table['pile'] = json_encode(array_splice($deck, 0, 1));
		$table['stack'] = json_encode($deck);
		shuffle($playerIDs);
		$table['player_order'] = json_encode($playerIDs);
		$table['current_player'] = $playerIDs[0];
		$table['active_power_cards'] = json_encode(array());
		$table['status'] = 'in-progress';
		$this->CI->db->update('tables', $table, array('tableID' => $table['tableID']));
		return $table;
	}

	function flatten($a = array()) {
		foreach($a as $k=>$v) $a[$k]=(array)$v;
		if (count($a) > 0) {
			return call_user_func_array('array_merge',$a);
		} else {
			return array();
		}
	}

$table['deckOrder'] was previously set from the array $cards_array = array('DA','D2','D3','D4','D5','D6','D7','D8','D9','D10','DJ','DQ','DK','SA','S2','S3','S4','S5','S6','S7','S8','S9','S10','SJ','SQ','SK','CA','C2','C3','C4','C5','C6','C7','C8','C9','C10','CJ','CQ','CK','HA','H2','H3','H4','H5','H6','H7','H8','H9','H10','HJ','HQ','HK');

$this->flatten maybe isn't necessary, but I was having trouble with json_encode() making objects javascript couldn't read.

As far as I can tell this should work fine, and about 9 times out of 10 it does, but once in a while a card is left out the game and a player get 4 instead of 5 cards. I'm using PHP 5.2.12 if it's relevant, and I'm stumped :(

Thanks for any help :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.