Creazione di uno Realtime script - Amazon GameLift Servers

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Creazione di uno Realtime script

Da utilizzare Amazon GameLift Servers Realtime per il gioco, è necessario fornire uno script (sotto forma di JavaScript codice) per configurare e, facoltativamente, personalizzare una flotta di Amazon GameLift ServersRealtime. In questo argomento vengono illustrati i passaggi fondamentali per la creazione di uno script Realtime. Una volta che lo script è pronto, caricalo nel servizioAmazon GameLift Servers e usalo per creare un parco istanze (consulta Implementa uno script per Amazon GameLift ServersRealtime).

Per preparare uno script da utilizzare con Amazon GameLift ServersRealtime, aggiungi la seguente funzionalità allo Realtime script.

Gestisci il ciclo di vita della sessione di gioco (richiesto)

Come minimo, uno script Realtime deve includere la funzione Init(), che prepara il server Realtime per avviare una sessione di gioco. Inoltre, è consigliabile fornire un modo per terminare le sessioni di gioco, così da assicurare che le nuove sessioni di gioco possano continuare a essere avviate sul parco istanze.

La funzione di chiamata Init(), quando usata, viene passata a un oggetto di sessione di Realtime, che contiene un'interfaccia per il server Realtime. Per ulteriori informazioni su questa interfaccia, consulta Amazon GameLift ServersRealtimeinterfaccia.

Per terminare in modo corretto una sessione di gioco, lo script deve anche chiamare la funzione session.processEnding del server Realtime. Ciò richiede alcuni meccanismi per determinare quando terminare una sessione. Il codice script di esempio illustra un semplice meccanismo che controlla le connessioni dei giocatori e attiva la terminazione della sessione di gioco quando nessun giocatore è connesso alla sessione per un determinato intervallo di tempo.

Amazon GameLift ServersRealtimecon la configurazione di base (inizializzazione e terminazione dei processi del server) funzionano essenzialmente come server di inoltro stateless. Il server Realtime inoltra messaggi e dati di gioco tra i client di gioco collegati al gioco, ma non esegue operazioni indipendenti per elaborare i dati o per eseguire una logica. È anche possibile aggiungere una logica di gioco, attivata da eventi di gioco o da altri meccanismi, in base alle esigenze del gioco medesimo.

Aggiungi la logica di gioco lato server (opzionale)

È anche possibile aggiungere logica di gioco allo script Realtime. Ad esempio, è possibile eseguire una o tutte le seguenti operazioni. Il codice di esempio di script fornisce illustrazione. Consultare Riferimento allo script per Amazon GameLift ServersRealtime.

  • Aggiunta di logica basata sugli eventi. Implementa le funzioni di chiamata per rispondere a eventi client-server. Per un elenco completo di chiamate, consulta Richiamate di script per Amazon GameLift ServersRealtime.

  • Attivazione della logica mediante l'invio di messaggi al server. Crea un set di codici di operazione speciali per i messaggi inviati dai client di gioco al server e aggiunge funzioni per gestire la ricezione Utilizza la chiamata onMessage e analizza il contenuto del messaggio tramite l'interfaccia gameMessage (consulta gameMessage.opcode).

  • Abilita la logica di gioco per accedere alle altre AWS risorse. Per informazioni dettagliate, consultare Comunica con altre AWS risorse delle tue flotte.

  • Consenti alla logica di gioco di accedere alle informazioni sulla flotta per l'istanza su cui è in esecuzione. Per informazioni dettagliate, consultare Ottieni dati sulla flotta per un Amazon GameLift Servers esempio.

Amazon GameLift ServersRealtimeesempio di script

Questo esempio illustra uno script di base necessario per la distribuzione e una Amazon GameLift Servers Realtime logica personalizzata. Contiene la funzione Init() richiesta e utilizza un meccanismo timer per attivare la terminazione delle sessioni di gioco in base all'intervallo di tempo in cui nessun giocatore si è connesso. Include anche alcuni hook per logica personalizzata, tra cui alcune implementazioni di chiamate.

// Example Realtime Server Script 'use strict'; // Example override configuration const configuration = { pingIntervalTime: 30000, maxPlayers: 32 }; // Timing mechanism used to trigger end of game session. Defines how long, in milliseconds, between each tick in the example tick loop const tickTime = 1000; // Defines how to long to wait in Seconds before beginning early termination check in the example tick loop const minimumElapsedTime = 120; var session; // The Realtime server session object var logger; // Log at appropriate level via .info(), .warn(), .error(), .debug() var startTime; // Records the time the process started var activePlayers = 0; // Records the number of connected players var onProcessStartedCalled = false; // Record if onProcessStarted has been called // Example custom op codes for user-defined messages // Any positive op code number can be defined here. These should match your client code. const OP_CODE_CUSTOM_OP1 = 111; const OP_CODE_CUSTOM_OP1_REPLY = 112; const OP_CODE_PLAYER_ACCEPTED = 113; const OP_CODE_DISCONNECT_NOTIFICATION = 114; // Example groups for user-defined groups // Any positive group number can be defined here. These should match your client code. // When referring to user-defined groups, "-1" represents all groups, "0" is reserved. const RED_TEAM_GROUP = 1; const BLUE_TEAM_GROUP = 2; // Called when game server is initialized, passed server's object of current session function init(rtSession) { session = rtSession; logger = session.getLogger(); } // On Process Started is called when the process has begun and we need to perform any // bootstrapping. This is where the developer should insert any code to prepare // the process to be able to host a game session, for example load some settings or set state // // Return true if the process has been appropriately prepared and it is okay to invoke the // GameLift ProcessReady() call. function onProcessStarted(args) { onProcessStartedCalled = true; logger.info("Starting process with args: " + args); logger.info("Ready to host games..."); return true; } // Called when a new game session is started on the process function onStartGameSession(gameSession) { // Complete any game session set-up // Set up an example tick loop to perform server initiated actions startTime = getTimeInS(); tickLoop(); } // Handle process termination if the process is being terminated by Amazon GameLift Servers // You do not need to call ProcessEnding here function onProcessTerminate() { // Perform any clean up } // Return true if the process is healthy function onHealthCheck() { return true; } // On Player Connect is called when a player has passed initial validation // Return true if player should connect, false to reject function onPlayerConnect(connectMsg) { // Perform any validation needed for connectMsg.payload, connectMsg.peerId return true; } // Called when a Player is accepted into the game function onPlayerAccepted(player) { // This player was accepted -- let's send them a message const msg = session.newTextGameMessage(OP_CODE_PLAYER_ACCEPTED, player.peerId, "Peer " + player.peerId + " accepted"); session.sendReliableMessage(msg, player.peerId); activePlayers++; } // On Player Disconnect is called when a player has left or been forcibly terminated // Is only called for players that actually connected to the server and not those rejected by validation // This is called before the player is removed from the player list function onPlayerDisconnect(peerId) { // send a message to each remaining player letting them know about the disconnect const outMessage = session.newTextGameMessage(OP_CODE_DISCONNECT_NOTIFICATION, session.getServerId(), "Peer " + peerId + " disconnected"); session.getPlayers().forEach((player, playerId) => { if (playerId != peerId) { session.sendReliableMessage(outMessage, playerId); } }); activePlayers--; } // Handle a message to the server function onMessage(gameMessage) { switch (gameMessage.opCode) { case OP_CODE_CUSTOM_OP1: { // do operation 1 with gameMessage.payload for example sendToGroup const outMessage = session.newTextGameMessage(OP_CODE_CUSTOM_OP1_REPLY, session.getServerId(), gameMessage.payload); session.sendGroupMessage(outMessage, RED_TEAM_GROUP); break; } } } // Return true if the send should be allowed function onSendToPlayer(gameMessage) { // This example rejects any payloads containing "Reject" return (!gameMessage.getPayloadAsText().includes("Reject")); } // Return true if the send to group should be allowed // Use gameMessage.getPayloadAsText() to get the message contents function onSendToGroup(gameMessage) { return true; } // Return true if the player is allowed to join the group function onPlayerJoinGroup(groupId, peerId) { return true; } // Return true if the player is allowed to leave the group function onPlayerLeaveGroup(groupId, peerId) { return true; } // A simple tick loop example // Checks to see if a minimum amount of time has passed before seeing if the game has ended async function tickLoop() { const elapsedTime = getTimeInS() - startTime; logger.info("Tick... " + elapsedTime + " activePlayers: " + activePlayers); // In Tick loop - see if all players have left early after a minimum period of time has passed // Call processEnding() to terminate the process and quit if ( (activePlayers == 0) && (elapsedTime > minimumElapsedTime)) { logger.info("All players disconnected. Ending game"); const outcome = await session.processEnding(); logger.info("Completed process ending with: " + outcome); process.exit(0); } else { setTimeout(tickLoop, tickTime); } } // Calculates the current time in seconds function getTimeInS() { return Math.round(new Date().getTime()/1000); } exports.ssExports = { configuration: configuration, init: init, onProcessStarted: onProcessStarted, onMessage: onMessage, onPlayerConnect: onPlayerConnect, onPlayerAccepted: onPlayerAccepted, onPlayerDisconnect: onPlayerDisconnect, onSendToPlayer: onSendToPlayer, onSendToGroup: onSendToGroup, onPlayerJoinGroup: onPlayerJoinGroup, onPlayerLeaveGroup: onPlayerLeaveGroup, onStartGameSession: onStartGameSession, onProcessTerminate: onProcessTerminate, onHealthCheck: onHealthCheck };