Skip to content

Commit

Permalink
Add some functions in games.php file but they are not working yet
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashikkalis committed Dec 25, 2024
1 parent 3a2b604 commit e272213
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
3 changes: 3 additions & 0 deletions blokus.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ public function routeRequest($input) {
// }
// });

//games functions


// Handle the request
$input = json_decode(file_get_contents('php://input'), true);
$router->routeRequest($input);
Expand Down
84 changes: 84 additions & 0 deletions lib/games.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

require_once 'dbconnect.php';
require_once 'helper.php';

header('Content-Type: application/json');

function getNextPlayerTurn($gameId) {
global $pdo;

$sql = "SELECT current_turn FROM games WHERE game_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId]);
$currentTurn = $stmt->fetchColumn();

if ($currentTurn !== false) {
$sql = "SELECT user_id FROM game_players WHERE game_id = ? ORDER BY player_order";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId]);
$players = $stmt->fetchAll(PDO::FETCH_COLUMN);

$currentIndex = array_search ($currentTurn, $players);
$nextIndex = ($currentIndex + 1) % count($players);

return $players[$nextIndex];
}

return null;
}

function getAvailableMoves($gameId, $playerId) {
global $pdo;

$sql = "SELECT board_state FROM games WHERE game_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId]);
$boardState = $stmt->fetchColumn();

$sql = "SELECT piece_id FROM player_pieces WHERE game_id = ? AND player_id = ? AND is_used = 0";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId, $playerId]);
$availablePieces = $stmt->fetchAll(PDO::FETCH_COLUMN);

$availableMoves = [
'placeholder' => 'Implement game rules to calculate moves'
];

return $availableMoves;
}

function getPlayerPieces($gameId, $playerId) {
global $pdo;

$sql = "SELECT piece_id FROM player_pieces WHERE game_id = ? AND player_id = ? AND is_used = 0";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId, $playerId]);

return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function updatePlayerMove($gameId, $playerId, $move) {
global $pdo;

$pdo->beginTransaction();

try {
$sql = "UPDATE games SET board_state = ?, current_turn = ? WHERE game_id = ?";
$stmt = $pdo->prepare($sql);
$newBoardState = json_encode($move['boardState']);
$stmt->execute([$newBoardState, $move['nextPlayer'], $gameId]);

$sql = "UPDATE player_pieces SET is_used = 1 WHERE game_id = ? AND player_id = ? AND piece_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$gameId, $playerId, $move['pieceId']]);

$pdo->commit();

return true;
} catch (Exception $e) {
$pdo->rollBack();
return false;
}
}
?>

0 comments on commit e272213

Please sign in to comment.