Join Tournament
The join tournament method allows players to register for and participate in tournaments. This is a critical step for players to compete in tournaments and appear on leaderboards.
Overview
The joinTournament method:
- Registers a player for a specific tournament
- Validates tournament availability and player eligibility
- Returns status code indicating success or failure
- Handles tournament capacity and entry requirements
Method Signature
public function joinTournament(string $gameID, string $tournamentID): int
Parameters
Required Parameters
gameID(String) - The Game ID for the tournamenttournamentID(String) - The Tournament ID to join
Return Value
Returns an integer status code:
- Positive value - Successfully joined tournament
- Zero - Join failed (generic error)
- Negative value - Specific error (check documentation for codes)
Basic Usage
Simple Tournament Join
use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;
$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);
try {
$result = $moitribe->tournRequestsHandler->joinTournament(
'your-game-id',
'tournament-123'
);
if ($result > 0) {
echo "Successfully joined the tournament!\n";
echo "Registration ID: " . $result . "\n";
} else {
echo "Failed to join tournament\n";
echo "Error code: " . $result . "\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Tournament Join with Validation
function joinTournamentSafely($gameId, $tournamentId, $playerId) {
global $moitribe;
try {
// First check if tournament exists and is joinable
$tournaments = $moitribe->tournRequestsHandler->getTournaments($gameId);
$targetTournament = null;
foreach ($tournaments as $tournament) {
if ($tournament->getId() === $tournamentId) {
$targetTournament = $tournament;
break;
}
}
if (!$targetTournament) {
return ['success' => false, 'message' => 'Tournament not found'];
}
if ($targetTournament->getStatus() !== 'active') {
return ['success' => false, 'message' => 'Tournament is not active'];
}
if ($targetTournament->isFull()) {
return ['success' => false, 'message' => 'Tournament is full'];
}
// Check if player meets requirements
if ($targetTournament->getMinLevel() && $playerLevel < $targetTournament->getMinLevel()) {
return ['success' => false, 'message' => 'Player level too low'];
}
// Join the tournament
$result = $moitribe->tournRequestsHandler->joinTournament($gameId, $tournamentId);
if ($result > 0) {
return [
'success' => true,
'message' => 'Successfully joined tournament',
'registration_id' => $result
];
} else {
return ['success' => false, 'message' => 'Failed to join tournament'];
}
} catch (Exception $e) {
error_log("Tournament join error: " . $e->getMessage());
return ['success' => false, 'message' => 'Server error occurred'];
}
}
// Usage
$result = joinTournamentSafely('your-game-id', 'tournament-123', 'player-456');
if ($result['success']) {
echo "Success: " . $result['message'] . "\n";
} else {
echo "Error: " . $result['message'] . "\n";
}
Integration Examples
Tournament Registration System
class TournamentRegistration {
private $moitribe;
private $gameId;
public function __construct($moitribe, $gameId) {
$this->moitribe = $moitribe;
$this->gameId = $gameId;
}
public function registerPlayer($tournamentId, $playerData) {
try {
// Validate tournament
$validation = $this->validateTournament($tournamentId, $playerData);
if (!$validation['valid']) {
return ['success' => false, 'message' => $validation['message']];
}
// Check if already registered
if ($this->isPlayerRegistered($tournamentId, $playerData['player_id'])) {
return ['success' => false, 'message' => 'Already registered for this tournament'];
}
// Handle entry fee if required
if ($validation['entry_fee'] > 0) {
$paymentResult = $this->processEntryFee($tournamentId, $playerData);
if (!$paymentResult['success']) {
return ['success' => false, 'message' => 'Payment failed: ' . $paymentResult['message']];
}
}
// Join tournament
$result = $this->moitribe->tournRequestsHandler->joinTournament(
$this->gameId,
$tournamentId
);
if ($result > 0) {
// Log registration
$this->logRegistration($tournamentId, $playerData['player_id'], $result);
return [
'success' => true,
'message' => 'Successfully registered for tournament',
'registration_id' => $result
];
} else {
return ['success' => false, 'message' => 'Failed to register for tournament'];
}
} catch (Exception $e) {
error_log("Tournament registration error: " . $e->getMessage());
return ['success' => false, 'message' => 'Registration system error'];
}
}
private function validateTournament($tournamentId, $playerData) {
try {
$tournaments = $this->moitribe->tournRequestsHandler->getTournaments($this->gameId);
foreach ($tournaments as $tournament) {
if ($tournament->getId() === $tournamentId) {
if ($tournament->getStatus() !== 'active') {
return ['valid' => false, 'message' => 'Tournament is not active'];
}
if ($tournament->isFull()) {
return ['valid' => false, 'message' => 'Tournament is full'];
}
if ($tournament->getMinLevel() && $playerData['level'] < $tournament->getMinLevel()) {
return ['valid' => false, 'message' => 'Player level too low'];
}
return [
'valid' => true,
'entry_fee' => $tournament->getEntryFee() ?: 0,
'tournament_name' => $tournament->getName()
];
}
}
return ['valid' => false, 'message' => 'Tournament not found'];
} catch (Exception $e) {
return ['valid' => false, 'message' => 'Error validating tournament'];
}
}
private function isPlayerRegistered($tournamentId, $playerId) {
// Check local database or cache for existing registration
// This is a placeholder - implement based on your system
return false;
}
private function processEntryFee($tournamentId, $playerData) {
// Implement payment processing logic
// This is a placeholder - integrate with your payment system
return ['success' => true];
}
private function logRegistration($tournamentId, $playerId, $registrationId) {
// Log registration to your database
error_log("Player $playerId registered for tournament $tournamentId with ID $registrationId");
}
}
// Usage
$registration = new TournamentRegistration($moitribe, 'your-game-id');
$playerData = [
'player_id' => 'player-123',
'level' => 25,
'currency' => 'coins'
];
$result = $registration->registerPlayer('tournament-456', $playerData);
if ($result['success']) {
echo "Registration successful! ID: " . $result['registration_id'] . "\n";
} else {
echo "Registration failed: " . $result['message'] . "\n";
}
Web Tournament Join Handler
function handleTournamentJoinRequest() {
global $moitribe;
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['tournament_id']) || !isset($input['player_id'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing required fields']);
return;
}
$tournamentId = $input['tournament_id'];
$playerId = $input['player_id'];
$gameId = $input['game_id'] ?? 'your-game-id';
try {
// Validate request
if (empty($tournamentId) || empty($playerId)) {
throw new InvalidArgumentException('Tournament ID and Player ID are required');
}
// Join tournament
$result = $moitribe->tournRequestsHandler->joinTournament($gameId, $tournamentId);
if ($result > 0) {
http_response_code(200);
echo json_encode([
'success' => true,
'message' => 'Successfully joined tournament',
'registration_id' => $result
]);
} else {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Failed to join tournament',
'error_code' => $result
]);
}
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Server error occurred']);
error_log("Tournament join API error: " . $e->getMessage());
}
}
// Route handler
if (strpos($_SERVER['REQUEST_URI'], '/api/tournament/join') !== false) {
handleTournamentJoinRequest();
}
Error Handling
Common Error Scenarios
- Tournament not found - Invalid tournament ID
- Tournament not active - Tournament hasn't started or has ended
- Tournament full - Maximum participants reached
- Player level too low - Doesn't meet minimum level requirement
- Already registered - Player already joined this tournament
- Entry fee required - Player hasn't paid entry fee
- Network issues - API communication problems
Error Handling Example
function safeJoinTournament($gameId, $tournamentId) {
global $moitribe;
try {
if (empty($gameId) || empty($tournamentId)) {
throw new InvalidArgumentException("Game ID and Tournament ID are required");
}
$result = $moitribe->tournRequestsHandler->joinTournament($gameId, $tournamentId);
if ($result > 0) {
return ['success' => true, 'registration_id' => $result];
} else {
$errorMessage = $this->getJoinErrorMessage($result);
return ['success' => false, 'message' => $errorMessage, 'error_code' => $result];
}
} catch (InvalidArgumentException $e) {
return ['success' => false, 'message' => $e->getMessage()];
} catch (Exception $e) {
error_log("Tournament join error: " . $e->getMessage());
return ['success' => false, 'message' => 'Failed to join tournament'];
}
}
function getJoinErrorMessage($errorCode) {
switch ($errorCode) {
case 0:
return 'Failed to join tournament';
case -1:
return 'Tournament not found';
case -2:
return 'Tournament is not active';
case -3:
return 'Tournament is full';
case -4:
return 'Player level too low';
case -5:
return 'Already registered for this tournament';
case -6:
return 'Entry fee required';
default:
return 'Unknown error occurred';
}
}
Best Practices
-
Validate Before Joining
- Check tournament status and availability
- Verify player meets requirements
- Check if already registered
-
Handle Entry Fees
- Process payments before joining
- Handle payment failures gracefully
- Provide refund options if join fails
-
Provide Clear Feedback
- Show specific error messages
- Display tournament requirements
- Guide players to resolve issues
-
Log Registration Events
- Track successful registrations
- Monitor failed attempts
- Analyze registration patterns
Related Methods
- List Tournaments - Find available tournaments
- Get Tournament Data - Get tournament details
- Submit Tournament Score - Submit scores after joining
- Pay Tournament Entry - Pay tournament entry fees