text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- título: OnDialogResponse descripción: Este callback se llama cuando un jugador responde a un cuadro de diálogo mostrado usando ShowPlayerDialog ya sea clickeando un botón, presionando ENTER/ESC o haciendo doble click en un elemento de lista (si el diálogo utiliza el estilo DIALOG_STYLE_LIST). tags: [] --- ## Descripción Este callback se llama cuando un jugador responde a un cuadro de diálogo mostrado usando ShowPlayerDialog ya sea clickeando un botón, presionando ENTER/ESC o haciendo doble click en un elemento de lista (si el diálogo utiliza el estilo DIALOG_STYLE_LIST). | Nombre | Descripción | | ----------- | ----------------------------------------------------------------------------------------------------------------------- | | playerid | El ID del jugador que respondió el diálogo. | | dialogid | El ID del diálogo al que respondió el jugador, asignado en ShowPlayerDialog. | | response | 1 para botón izquierdo y 0 para botón derecho (si sólo hay un botón, siempre 1). | | listitem | El ID del elemento de lista que seleccionó el jugador (empieza de 0) (si no se está usando DIALOG_STYLE_LIST, será -1) | | inputtext[] | El texto ingresado en la caja de entrada por el jugador o el texto del elemento de lista seleccionado. | ## Devoluciones 1 - Prevendrá a otros filterscripts de recibir este callback. 0 - Indica que este callback será pasado al siguiente filterscript. Siempre se llama primero en filterscripts. ## Ejemplos ```c // Definimos el ID del diálogo para poder controlar las respuestas #define DIALOG_RULES 1 // En algún comando ShowPlayerDialog(playerid, DIALOG_RULES, DIALOG_STYLE_MSGBOX, "Reglas del servidor", "- No Cheating\n- No Spamming\n- Respect Admins\n\nAceptas las reglas?", "Sí", "No"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_RULES) { if (response) // Si clickeó en "Sí" o apretó enter { SendClientMessage(playerid, COLOR_GREEN, "Gracias por aceptar las reglas del servidor!"); } else // Si apretó la tecla ESC o clickeó en "No". { Kick(playerid); } return 1; // Manejamos un diálogo, así que hay que devolver 1. Como en OnPlayerCommandText. } return 0; // TENÉS que devolver 0 acá! Como en OnPlayerCommandText. } #define DIALOG_LOGIN 2 // En algún comando ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Ingresá tu contraseña:", "Login", "Cancelar"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_LOGIN) { if (!response) // Si clickeó 'Cancelar' o apretó la tecla ESC { Kick(playerid); } else // Si apretó enter o clickeó en el botón 'Login' { if (CheckPassword(playerid, inputtext)) { SendClientMessage(playerid, COLOR_RED, "Ahora estás logeado!"); } else { SendClientMessage(playerid, COLOR_RED, "Contraseña incorrecta."); // Mostrando de nuevo el diálogo de login ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Ingresá tu contraseña:", "Login", "Cancelar"); } } return 1; // Manejamos un diálogo, así que hay que devolver 1. Como en OnPlayerCommandText. } return 0; // TENÉS que devolver 0 acá! Como en OnPlayerCommandText. } #define DIALOG_WEAPONS 3 // En algún comando ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Armas", "Desert Eagle\nAK-47\nCombat Shotgun", "Seleccionar", "Cerrar"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_WEAPONS) { if (response) // Si clickeó en 'Seleccionar' o apretó enter. { // Dándole el arma al jugador switch(listitem) { case 0: GivePlayerWeapon(playerid, WEAPON_DEAGLE, 14); // Dándole una Desert Eagle case 1: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // Dándole una AK-47 case 2: GivePlayerWeapon(playerid, WEAPON_SHOTGSPA, 28); // Dándole una Combat Shotgun } } return 1; // Manejamos un diálogo, así que hay que devolver 1. Como en OnPlayerCommandText. } return 0; // TENÉS que devolver 0 acá! Como en OnPlayerCommandText. } #define DIALOG_WEAPONS 3 // En algún comando ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Armas", "Arma\tMunición\tPrecio\n\ M4\t120\t500\n\ MP5\t90\t350\n\ AK-47\t120\t400", "Seleccionar", "Cerrar"); public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[]) { if (dialogid == DIALOG_WEAPONS) { if (response) // Si clickeó en seleccionar o hizo doble click en algún arma { // Dándole el arma al jugador switch(listitem) { case 0: GivePlayerWeapon(playerid, WEAPON_M4, 120); // Dándole una M4 case 1: GivePlayerWeapon(playerid, WEAPON_MP5, 90); // Dándole una MP5 case 2: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // Dándole una AK-47 } } return 1; // Manejamos un diálogo, así que hay que devolver 1. Como en OnPlayerCommandText. } return 0; // TENÉS que devolver 0 acá! Como en OnPlayerCommandText. } ``` ## Notas :::tip Los parámetros pueden contener diferentes valores, según el estilo del diálogo ([click para más ejemplos](../resources/dialogstyles)). ::: :::tip Es apropiado usar la sentencia 'switch' para ir cambiando entre los diferentes ID's de diálogos, si tenés muchos. ::: :::warning El diálogo de un jugador no se oculta cuando el gamemode se reinicia, causando que el server imprima en la consola "Warning: PlayerDialogResponse PlayerId: 0 dialog ID doesn't match last sent dialog ID" en caso de que algún jugador responda a este después del reinicio. ::: ## Funciones Relacionadas - [ShowPlayerDialog](../functions/ShowPlayerDialog): Mostrar un diálogo a un jugador.
openmultiplayer/web/docs/translations/es/scripting/callbacks/OnDialogResponse.md/0
{ "file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnDialogResponse.md", "repo_id": "openmultiplayer", "token_count": 2896 }
359
--- título: OnPlayerDisconnect descripción: Este callback se llama cuando un jugador se desconecta del servidor. tags: ["player"] --- ## Descripción Este callback se llama cuando un jugador se desconecta del servidor. | Nombre | Descripción | | -------- | -------------------------------------------------- | | playerid | El ID del jugador que se desconectó. | | reason | La razón de la desconexión. (ver tabla abajo) | ## Devoluciones 1 - Prevendrá a otros filterscripts de recibir este callback. 0 - Indica que este callback será pasado al siguiente filterscript. Siempre se llama primero en filterscripts. ## Razones | ID | Razón | Detalles | | -- | ------------- | -------------------------------------------------------------------------------------------- | | 0 | Timeout/Crash | La conexión del jugador se perdió. Ya sea si su juego crasheó o su internet tuvo una falla. | | 1 | Quit | El jugador salió a propósito, ya sea con /quit (/q) o a través del menú de pausa. | | 2 | Kick/Ban | El jugador fue kickeado o baneado por el servidor. | ## Ejemplos ```c public OnPlayerDisconnect(playerid, reason) { new szString[64], playerName[MAX_PLAYER_NAME]; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); new szDisconnectReason[3][] = { "Timeout/Crash", "Quit", "Kick/Ban" }; format(szString, sizeof szString, "%s se desconectó del servidor (%s).", playerName, szDisconnectReason[reason]); SendClientMessageToAll(0xC4C4C4FF, szString); return 1; } ``` ## Notas :::tip Algunas funciones pueden no funcionar correctamente cuando son usadas en este callback debido a que el jugador ya está desconectado cuando el callback es llamado. Esto quiere decir que no podés obtener información inequívoca de funciones como GetPlayerIp o GetPlayerPos. ::: ## Funciones Relacionadas
openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerDisconnect.md/0
{ "file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerDisconnect.md", "repo_id": "openmultiplayer", "token_count": 899 }
360
--- título: OnPlayerPickUpPickup descripción: Se llama cuando un jugador recoge un pickup creado con CreatePickup. tags: ["player"] --- ## Descripción Se llama cuando un jugador recoge un pickup creado con CreatePickup. | Nombre | Descripción | | -------- | ----------------------------------------------- | | playerid | El ID del jugador que recogió el pickup. | | pickupid | El ID del pickup, devuelto por CreatePickup. | ## Devoluciones Siempre se llama primero en el gamemode. ## Ejemplos ```c new pickup_Cash; new pickup_Health; public OnGameModeInit() { pickup_Cash = CreatePickup(1274, 2, 0.0, 0.0, 9.0); pickup_Health = CreatePickup(1240, 2, 0.0, 0.0, 9.0); return 1; } public OnPlayerPickUpPickup(playerid, pickupid) { if (pickupid == pickup_Cash) { GivePlayerMoney(playerid, 1000); //Cuando el jugador pasa por el pickup con ícono de dinero, le da $1000 } else if (pickupid == pickup_Health) { SetPlayerHealth(playerid, 100.0); //Cuando el jugador pasa por el pickup con ícono de corazón, le da 100 de vida } return 1; } ``` ## Funciones Relacionadas - [CreatePickup](../functions/CreatePickup): Crea un pickup. - [DestroyPickup](../functions/DestroyPickup): Destruye un pickup.
openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerPickUpPickup.md/0
{ "file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerPickUpPickup.md", "repo_id": "openmultiplayer", "token_count": 524 }
361
--- título: OnRecordingPlaybackEnd descripción: Este callback se llama cuando un archivo grabado siendo reproduciendo con NPCStartRecordingPlayback llega a su fin. tags: [] --- ## Description Este callback se llama cuando un archivo grabado siendo reproduciendo con NPCStartRecordingPlayback llega a su fin. ## Ejemplos ```c public OnRecordingPlaybackEnd() { StartRecordingPlayback(PLAYER_RECORDING_TYPE_DRIVER, "all_around_lv_bus"); //Esto iniciaría el archivo grabado nuevamente una vez que termine de reproducirse. } ```
openmultiplayer/web/docs/translations/es/scripting/callbacks/OnRecordingPlaybackEnd.md/0
{ "file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnRecordingPlaybackEnd.md", "repo_id": "openmultiplayer", "token_count": 185 }
362
--- title: OnGameModeInit description: This callback is triggered when the gamemode starts. tags: [] --- ## Description Ang callback na ito ay nag-ti-trigger kapag nagsisimulang mag run ang isang gamemode. ## Examples ```c public OnGameModeInit() { print("Ang gamemode ay nagsimula."); return 1; } ``` ## Mga Dapat Unawain :::tip Ang function na ito ay maaari rin gamitin sa mga filterscript upang mai-detect kapag ang gamemode ay nabago gamit ang RCON commands tulad ng changemode o gmx, sapagkat ang pagpalit ng gamemode ay hindi nagrereload ng filterscripts. ::: ## Mga Kaugnay na Functions
openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnGameModeInit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnGameModeInit.md", "repo_id": "openmultiplayer", "token_count": 220 }
363
--- title: OnPlayerDeath description: This callback is called when a player dies, either by suicide or by being killed by another player. tags: ["player"] --- ## Description Ang callback na ito ay itinatawag kapag ang isang player ay namatay. Sa mga dahilan na pwedeng namatay ang player sa kanyang sariling gawa o napatay ng iba pang player. | Name | Description | |---------------|-------------------------------------------------------------------------| | playerid | Ang ID ng player na namatay. | | killerid | Ang ID ng player na nam-patay sa playerid, INVALID_PLAYER_ID kung wala. | | WEAPON:reason | Ang ID ng rason kung bakit namatay ang playerid. | ## Returns 0 - Ay pagbabawalan ang ibang filterscript na tanggapin itong callback. 1 - Ay nagpapahiwatig na itong callback ay ipapasa sa susunod na filterscript. Ito ay palaging unang tinatawag sa mga filterscripts. ## Examples ```c new PlayerDeaths[MAX_PLAYERS]; new PlayerKills[MAX_PLAYERS]; public OnPlayerDeath(playerid, killerid, WEAPON:reason) { SendDeathMessage(killerid, playerid, reason); // - Ipinapakita ang impormasyon ng pagpatay sa kill feed. // - Tignan muna kung valid ang player ID ng pumatay. if (killerid != INVALID_PLAYER_ID) { PlayerKills[killerid] ++; // Dagdagan ang PlayerKills ng pumatay. } // - Dagdagan ang PlayerDeaths ng napatay. PlayerDeaths[playerid] ++; return 1; } ``` ## Notes :::tip - Ang rason na nagrereturn ng 37 (flame thrower) ay nanggagaling sa anumanng fire sources (e.g molotov, 18). - Ang rason na regrereturn ng 51 ay nanggagaling sa anumang baril o weapon na gumagawa ng explosion (e.g. RPG, grenade). - Hindi mo na kailangan tignan kung ang killerid ay valid bago gamitin ang SendDeathMessage. Ang INVALID_PLAYER_ID ay isang valid na killerid ID parameter sa function na iyon. - Ang playerid lamang ang may kapakanan na tawagin itong callback. (Magandang alamin para sa anti-fake death na mga hacks/cleo.) :::warning Kailangan mong tignan kung ang 'killerid' ay valid (not IVALID_PLAYER_ID) bago gamitin ito sa isang array (o kahit saan), dahil ito ay nagdudulot ng crash sa script ng OnPlayerDeath (hindi ang buong script). Ito ay dahil ang INVALID_PLAYER_ID ay defined as 65535, kapag ang array ay mayroon lamang 'MAX_PLAYERS' elements, e.g. 500, ikaw ay nagtatangkang i-access ang index na mahigit pa sa 499, na out of bounds. ::: ## Related Functions - [SendDeathMessage](../functions/SendDeathMessage): Dagdagan ng kill sa Death list. - [SetPlayerHealth](../functions/SetPlayerHealth): I set ang health ng player.
openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerDeath.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerDeath.md", "repo_id": "openmultiplayer", "token_count": 1025 }
364
--- title: AddSimpleModelTimed description: Nagdaragdag ng bagong custom na simpleng object model para sa pag-download. tags: [] --- <VersionWarn version='SA-MP 0.3.DL R1' /> ## Description Nagdaragdag ng bagong custom na simpleng object model para sa pag-download. Ang mga file ng modelo ay maiimbak sa Documents\GTA San Andreas User Files\SAMP\cache ng player sa ilalim ng Server IP at Port folder sa isang CRC-form file name. | Name | Description | | ------------ | --------------------------------------------------------------------------------------------------------------------------- | | virtualworld | Ang virtual world ID para gawing available ang modelo sa. Gamitin ang -1 para sa lahat ng mundo. | | baseid | Ang batayang object model ID na gagamitin (orihinal na object na gagamitin kapag nabigo ang pag-download). | | newid | Ang bagong object model ID ay mula -1000 hanggang -30000 (29000 slots) na gagamitin sa ibang pagkakataon kasama ang CreateObject o CreatePlayerObject.| | dffname | Pangalan ng .dff model collision file na matatagpuan sa folder ng server ng mga modelo bilang default (setting ng artpath) | | txdname | Pangalan ng .txd model texture file na matatagpuan sa folder ng server ng mga modelo bilang default (setting ng artpath). | | timeon | Ang oras ng laro sa mundo (oras) ang bagay na ito ay lilitaw | | timeoff | Ang oras ng laro sa mundo (oras) ang bagay na ito ay mawawala | ## Returns 1: Matagumpay na naisakatuparan ang function. 0: Nabigo ang function na isagawa. ## Examples ```c public OnGameModeInit() { AddSimpleModelTimed(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd", 9, 18); // Nagre-render lang ang pader na ito mula 9:00 am hanggang 6:00 pm return 1; } ``` ## Notes :::tip ang useartwork ay dapat munang paganahin sa mga setting ng server upang ito ay gumana Kapag ang virtualworld ay nakatakda, ang mga modelo ay mada-download kapag ang player ay pumasok sa partikular na mundo ::: :::warning Kasalukuyang walang mga paghihigpit sa kung kailan mo maaaring tawagan ang function na ito, ngunit magkaroon ng kamalayan na kung hindi mo sila tatawagan sa loob ng OnFilterScriptInit/OnGameModeInit, magkakaroon ka ng panganib na ang ilang mga manlalaro, na nasa server na, ay maaaring hindi na-download ang mga modelo. ::: ## Related Functions - [OnPlayerFinishedDownloading](../callbacks/OnPlayerFinishedDownloading): Tinatawag kapag natapos na ng player ang pag-download ng mga custom na modelo.
openmultiplayer/web/docs/translations/fil/scripting/functions/AddSimpleModelTimed.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/AddSimpleModelTimed.md", "repo_id": "openmultiplayer", "token_count": 1125 }
365
--- title: BanEx description: Ipagbawal ang isang manlalaro na may dahilan. tags: ["administration"] --- ## Description Ipagbawal ang isang manlalaro na may dahilan. | Name | Description | | -------- | ---------------------------- | | playerid | Ang ID ng player na pagbabawalan.| | reason | Ang dahilan ng pagbabawal. | ## Returns Ang function na ito ay hindi nagbabalik ng anumang partikular na halaga. ## Examples ```c public OnPlayerCommandText( playerid, cmdtext[] ) { if (!strcmp(cmdtext, "/banme", true)) { // I-ban ang manlalaro kung sino ang gumamit ng command na ito na may kasamang dahilan na ("Request") BanEx(playerid, "Request"); return 1; } } /*Upang magpakita ng mensahe (hal. dahilan) para sa player bago isara ang koneksyon kailangan mong gumamit ng timer para gumawa ng pagkaantala. Ang pagkaantala na ito ay kailangan lang ng ilang millisecond ang haba, ngunit ang halimbawang ito ay gumagamit ng isang buong segundo para lamang maging ligtas.*/ forward BanExPublic(playerid, reason[]); public BanExPublic(playerid, reason[]) { BanEx(playerid, reason); } stock BanExWithMessage(playerid, color, message[], reason[]) { // dahilan - dahilan na magagamit para sa BanEx SendClientMessage(playerid, color, message); SetTimerEx("BanExPublic", 1000, false, "ds", playerid, reason); } public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/banme", true) == 0) { // I-ban ang manlalaro kung sino man ang gumamit ng command na ito. BanExWithMessage(playerid, 0xFF0000FF, "You have been banned!", "Request"); return 1; } return 0; } ``` ## Notes :::warning Ang anumang aksyon na direktang ginawa bago ang BanEx() (tulad ng pagpapadala ng mensahe gamit ang SendClientMessage) ay hindi makakarating sa player. Dapat gumamit ng timer para maantala ang pagbabawal. ::: ## Related Functions - [Ban](Ban): I-ban ang manlalaro mula sa paglalaro sa server. - [Kick](Kick): I-kick ang manlalaro mula sa server.
openmultiplayer/web/docs/translations/fil/scripting/functions/BanEx.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/BanEx.md", "repo_id": "openmultiplayer", "token_count": 792 }
366
--- title: ForceClassSelection description: Pinipilit ang isang manlalaro na bumalik sa class selection. tags: [] --- ## Description Pinipilit ang isang manlalaro na bumalik sa class selection. | Name | Description | | -------- | ------------------------------------------- | | playerid | Ang player na ibabalik sa class selection. | ## Returns Ang function na ito ay hindi nagbabalik ng anumang value. ## Examples ```c if (!strcmp(cmdtext, "/class", true)) { ForceClassSelection(playerid); TogglePlayerSpectating(playerid, true); TogglePlayerSpectating(playerid, false); return 1; } ``` ## Notes :::warning Ang function na ito ay hindi nagsasagawa ng pagbabago ng estado sa PLAYER_STATE_WASTED kapag pinagsama sa TogglePlayerSpectating (tingnan ang halimbawa sa ibaba), tulad ng nakalista dito. ::: ## Related Functions - [AddPlayerClass](AddPlayerClass): Magdagdag ng class. - [SetPlayerSkin](SetPlayerSkin): Magtakda ng skin ng manlalaro. - [GetPlayerSkin](GetPlayerSkin): Kunin ang kasalukuyang skin ng manlalaro. - [OnPlayerRequestClass](../callbacks/OnPlayerRequestClass): Tinatawag kapag nagpalit ng class ang manlalaro sa class selection.
openmultiplayer/web/docs/translations/fil/scripting/functions/ForceClassSelection.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/ForceClassSelection.md", "repo_id": "openmultiplayer", "token_count": 419 }
367
--- title: SendRconCommand description: Nagpapadala ng command na RCON (Remote Console). tags: ["administration"] --- ## Description Nagpapadala ng command na RCON (Remote Console). | Name | Description | | --------- | -------------------------------- | | command[] | Ang RCON command na ma e-execute | ## Returns Ang function na ito ay palaging rereturn ng 1. ## Notes :::warning - Hindi sinusuportahan ang pag-login, dahil sa kakulangan ng parameter na 'playerid'. - Tatanggalin ng 'password 0' ang password ng server kung nakatakda ang isa. - Ang function na ito ay magreresulta sa OnRconCommand na tinatawag. ::: ## Examples ```c SendRconCommand("gmx"); // Ito ay isang scripted na bersyon ng pag-type ng "/rcon gmx" in-game. // Ni-restart ng GMX ang mode ng laro. // Halimbawa gamit ang format() new szMapName[] = "Los Santos"; new szCmd[64]; format(szCmd, sizeof(szCmd), "mapname %s", szMapName); SendRconCommand(szCmd); ``` ## Related Functions - [IsPlayerAdmin](IsPlayerAdmin): Sinusuri kung ang isang manlalaro ay naka-log in sa RCON. ## Related Callbacks - [OnRconCommand](../callbacks/OnRconCommand): Tinatawag kapag ipinadala ang isang utos ng RCON. - [OnRconLoginAttempt](../callbacks/OnRconLoginAttempt): Tinatawag kapag may ginawang pagtatangkang mag-log in sa RCON.
openmultiplayer/web/docs/translations/fil/scripting/functions/SendRconCommand.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/SendRconCommand.md", "repo_id": "openmultiplayer", "token_count": 474 }
368
--- title: StopAudioStreamForPlayer description: Ihihinto ang kasalukuyang audio stream para sa isang player. tags: ["player"] --- ## Description Ihihinto ang kasalukuyang audio stream para sa isang player. | Name | Description | | -------- | ------------------------------------------------- | | playerid | Ang player na gusto mong ihinto ang audio stream. | ## Returns Ang function na ito ay hindi nagbabalik ng anumang value. ## Examples ```c public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate) { // Kung ang manlalaro ay lumabas ng sasakyan if (oldstate == PLAYER_STATE_DRIVER || oldstate == PLAYER_STATE_PASSENGER) { StopAudioStreamForPlayer(playerid); // Itigil ang audio stream } return 1; } ``` ## Related Functions - [PlayAudioStreamForPlayer](PlayAudioStreamForPlayer): Nagpe-play ng audio stream para sa isang player. - [PlayerPlaySound](PlayerPlaySound): Magpatugtog ng tunog para sa isang manlalaro.
openmultiplayer/web/docs/translations/fil/scripting/functions/StopAudioStreamForPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/StopAudioStreamForPlayer.md", "repo_id": "openmultiplayer", "token_count": 359 }
369
--- title: Erreurs récentes du client SA:MP description: Liste de toutes les erreurs possibles avec SA:MP / GTA:SA ainsi que leurs solutions. --- ## Erreurs récentes du client SA:MP Le client SA:MP réserve parfois quelques surprises à ses utilisateurs, tantôt à raison d'un dysfonctionnement avec GTA:SA, tantôt à raison d'un problème avec le multijoueur lui-même. ## Côté client ### J'ai l'erreur "San Andreas cannot be found" San Andreas Multiplayer n'est **pas** un programme indépendant du solo de GTA San Andreas. C'est un multijoueur qui ajoute plusieurs fonctionnalités à GTA San Andreas, il faut donc que vous ayez GTA:SA sur votre ordinateur. Il faut également que votre jeu soit en version **EU/US v1.0**, les autres versions comme la v2.0 ou celle de Steam et Direct2Drive ne sont pas compatibles. [Cliquez ici pour télécharger le patch du _downgrade_ de GTA:SA en version 1.0](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661) ### Je ne vois aucun serveur sur le launcher Tout d'abord, assurez-vous de suivre le [guide prescrit](https://team.sa-mp.com/wiki/Getting_Started) par SA:MP. Si, en dépit du fait d'avoir suivi ce guide à la lettre, vous ne voyez toujours aucun serveur, vous devez autoriser SA:MP sur votre pare-feu. Aucun support ne peut être fourni relativement à votre pare-feu tant il y en a. Enfin, assurez-vous d'avoir la version la plus récente de SA:MP ! ### Le solo se charge au lieu du multijoueur :::warning Vous n'êtes pas censé voir les options solo _(nouveau jeu, sauvegardes, etc.)_ -. SA: MP devrait se charger tout seul et ne pas présenter ces options. Si vous voyez "nouveau jeu", c'est que le mode solo a été chargé, pas le mode multijoueur San Andreas. ::: Le solo peut charger pour deux raisons : 1. Vous avez installer SA:MP dans le mauvais fichier ou vous avez une mauvaise version de jeu. Cliquez [ici](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661) pour télécharger le patch. 2. Parfois, le menu du solo peut apparaître, alors même que SA:MP a été chargé correctement. Il suffit de sélectionner une option du menu et cliquez sur la touche echap pour revenir en arrière. Le problème devrait être réglé. ### J'ai un "Unacceptable Nickname" en me connectant sur un serveur Assurez-vous de ne pas utiliser un caractère bloqué par SA:MP *(seulement les caractères 0-9, a-z, \[\], (), \$, @, ., \_ sont autorisés)* et que votre pseudo ne dépasse pas les 20 caractères. Cela peut également arriver lorsqu'un joueur avec le même pseudo que vous est déjà connecté sur le serveur _(cela peut arriver si vous vous reconnectez rapidement après un crash ou timeout)_. ### J'ai "Connecting to IP:Port..." en boucle Le serveur est sans doute hors ligne, mais tentez quand même de désactiver votre pare-feu Windows. Si cette solution fonctionne, vous devriez reconfigurer votre pare-feu. Vérifiez également que vous avez SA:MP en 0.3DL ([télécharger la version 0.3DL](https://archive.org/download/sa-mp-0.3.dl)). ### J'ai un jeu moddé et SA:MP ne charge plus À problème simple, solution simple : retirez vos mods. ### GTA ne veut pas se lancer avec SA:MP Supprimez le fichier gta_sa.set _(Documents\GTA San Andreas User Files)_ et, si tel est le cas, retirez vos cheats/mods. ### Mon jeu crash quand un véhicule explose Si vous avez deux écrans, 3 solutions s'offrent à vous : 1. Désactivez votre second écran quand vous jouez à SA:MP. 2. Mettez la qualité visuelle de votre jeu en low. (Esc > Options > Display Setup > Advanced) 3. Renommez vitre fichier GTA San Andreas _(par exemple, en "GTA San Andreas2"). Cette solution fonctionne, si le problème revient il faudra renommer à nouveau votre fichier. ### Ma souris ne marche plus après avoir quitté le menu echap Si votre souris semble être, totalement ou partiellement, figée alors qu'elle fonctionne dans le menu pause, vous devriez désactiver l'option _multicore_ [sa-mp.cfg](/web/20190421141207/https://wiki.sa-mp.com/wiki/Sa-mp.cfg "Sa-mp.cfg") (valeur à mettre : 0). Ou alors spammmez la touche ECHAP jusqu'à ce que votre souris refonctionne. ### Le fichier dinput8.dll est manquant Il est possible que ce problème survienne quand DirectX n'est pas correctement installé ; il faut alors le réinstaller _(sans oublier de redémarrer son PC)_. Si le problème subsiste, rendez vous dans C:\\Windows\\System32 et copier/coller le fichier dinput.dll dans le dossier de votre GTA San Andreas. Cela devrait fonctionner. ### Je ne peux pas voir le nametag des autres joueurs ! D'abord, sachez que certains serveurs désactivent par défaut le nametag. Ensuite, ce problème arrive parfois sur des ordinateurs avec une carte graphique Intel HD intégrée _(pas très gaming tout ça ...)_. Ce problème n'appelle pas à une solution universelle et totalement fonctionnelle, de telle sorte qu'il conviendrait plutôt de changer d'ordinateur.
openmultiplayer/web/docs/translations/fr/client/CommonClientIssues.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/client/CommonClientIssues.md", "repo_id": "openmultiplayer", "token_count": 1801 }
370
--- title: OnFilterScriptInit description: Cette callback est appelée quand un filterscript est chargé. tags: [filterscript, load, chargé, loaded] --- ## Description Cette callback est appelée quand un filterscript est chargé. Elle n'est appelée que dans le filterscript qui a été chargé. ## Exemple ```c public OnFilterScriptInit() { print("\n--------------------------------------"); print("Filterscript chargé. "); print("--------------------------------------\n"); return 1; } ``` ## Callback connexe - [OnFilterScriptExit](OnFilterScriptExit) : déchargement d'un filterscript
openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnFilterScriptInit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnFilterScriptInit.md", "repo_id": "openmultiplayer", "token_count": 206 }
371
--- title: OnPlayerClickPlayer description: Callback appelée quand un joueur double-clique sur le pseudo d'un joueur dans la tablist. tags: [player, clickplayer, clickedplayerid, source] --- ## Paramètres Callback appelée quand un joueur double-clique sur le pseudo d'un joueur dans la tablist. | Nom | Description | | --------------------- | ---------------------------------------------------------------- | | `int` playerid | ID du joueur qui double-clique sur un pseudo dans la tablist | | `int` clickedplayerid | ID du joueur sélectionn | | `int` source | Source du clic du joueur | ## Valeur de retour Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback. ## Exemple ```c public OnPlayerClickPlayer(playerid, clickedplayerid, CLICK_SOURCE:source) { new message[32]; format(message, sizeof(message), "Vous avez sélectionné le joueur %d", clickedplayerid); SendClientMessage(playerid, 0xFFFFFFFF, message); return 1; } ``` ## Astuces :::tip Il n'y a qu'une seule 'source' de clic (0 - CLICK_SOURCE_SCOREBOARD). ::: ## Callbacks connexes - [OnPlayerClickTextDraw](OnPlayerClickTextDraw): Quand un joueur clique sur un textdraw. - [OnPlayerClickMap](OnPlayerClickMap): Quand un joueur place un point sur la map avec le clic droit.
openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerClickPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerClickPlayer.md", "repo_id": "openmultiplayer", "token_count": 657 }
372
--- title: OnPlayerFinishedDownloading description: Callback appelée quand un joueur fini de télécharger les models custom du serveur. tags: ["player"] --- <VersionWarn name='callback' version='SA-MP 0.3.DL R1' /> ## Paramètres Callback appelée quand un joueur fini de télécharger les models custom du serveur. Pour plus d'informations sur comment ajouter des custom models sur son serveur, référez-vous aux tutoriels sur [Burgershot.gg](https://forum.open.mp/). | Nom | Description | | ------------------ | ------------------------------------------------------------------------------ | | `int` playerid | ID du joueur qui a fini le téléchargement des models custom. | | `int` virtualworld | ID du virtual world pour lequel le joueur a fini le téléchargement des models | ## Valeur de retour Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback. ## Exemple ```c public OnPlayerFinishedDownloading(playerid, virtualworld) { SendClientMessage(playerid, 0xffffffff, "Téléchargement fini."); return 1; } ``` ## Astuces :::tip Cette callback est appelée chaque fois qu'un joueur change de virtual word, même s'il n'y a aucun custom model dans le world concerné. ::: ## Fonctions connexes
openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerFinishedDownloading.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerFinishedDownloading.md", "repo_id": "openmultiplayer", "token_count": 564 }
373
--- title: OnPlayerSelectedMenuRow description: Cette callback est appelée lorsqu'un joueur sélectionne un article depuis un menu (ShowMenuForPlayer). tags: ["player", "menu"] --- ## Paramètres Cette callback est appelée lorsqu'un joueur sélectionne un article depuis un menu [(ShowMenuForPlayer)](../functions/ShowMenuForPlayer). | Nom | Description | | -------------- | -------------------------------------------------------------------- | | `int` playerid | L'ID du joueur qui a sélectionné le menu. | | `int` row | L'ID de la ligne qui a été sélectionnée. La première ligne = **0**. | ## Valeur de retour Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback. ## Exemple ```c new Menu:MyMenu; public OnGameModeInit() { MyMenu = CreateMenu("Menu 1", 1, 50.0, 180.0, 200.0, 200.0); AddMenuItem(MyMenu, 0, "Item 1"); AddMenuItem(MyMenu, 0, "Item 2"); return 1; } public OnPlayerSelectedMenuRow(playerid, row) { if (GetPlayerMenu(playerid) == MyMenu) { switch(row) { case 0: print("Item 1 sélectionné"); case 1: print("Item 2 sélectionné"); } } return 1; } ``` ## Astuces :::tip L'ID du menu choisi n'est pas un paramètre de cette callback. GetPlayerMenu doit être utilisé pour déterminer quel menu le joueur a-t-il sélectionné. ::: ## Fonctions connexes - [CreateMenu](../functions/CreateMenu): Créer un menu. - [DestroyMenu](../functions/DestroyMenu): Détruit un menu. - [AddMenuItem](../functions/AddMenuItem): Ajoute un item dans un menu spécifique. - [ShowMenuForPlayer](../functions/ShowMenuForPlayer): Montre un menu pour un joueur. - [HideMenuForPlayer](../functions/HideMenuForPlayer): Cache un menu pour un joueur.
openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerSelectedMenuRow.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerSelectedMenuRow.md", "repo_id": "openmultiplayer", "token_count": 818 }
374
--- title: OnVehicleDeath description: Cette callback est appelée lorsqu'un véhicule est détruit - en explosant ou en tombant dans l'eau. tags: ["vehicle"] --- ## Paramètres Cette callback est appelée lorsqu'un véhicule est détruit - en explosant ou en tombant dans l'eau. | Nom | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `int` vehicleid | L'ID du véhicule détruit. | | `int` killerid | L'ID du joueur qui a causé les dégâts. Généralement le conducteur ou un passager (si il y en a) ou le joueur le plus proche. | ## Valeur de retour Aucune. ## Exemples ```c public OnVehicleDeath(vehicleid, killerid) { new string[40]; format(string, sizeof(string), "Le véhicule %i a été détruit par le joueur id %i.", vehicleid, killerid); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## Astuces :::tip Cette callback est appelée lorsqu'un véhicule entre dans l'eau mais il peut être sauvé de la destruction si il est submergé en partie ou si il est téléporté. Cette callback ne sera pas appelée une seconde fois et le véhicule disparaîtra après la sortie du conducteur, ou peu de temps après. ::: ## Fonctions connexes - [SetVehicleHealth](../functions/SetVehicleHealth): Modifie la vie d'un véhicule.
openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnVehicleDeath.md/0
{ "file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnVehicleDeath.md", "repo_id": "openmultiplayer", "token_count": 721 }
375
# Wiki SA-MP dan Dokumentasi open.mp Selamat Datang di Wiki SA-MP, dikelola oleh tim open.mp dan komunitas SA-MP terbesar! Situs ini bertujuan untuk memberi akses yang mudah, mudah untuk berkontribusi untuk dokumentasi SA-MP mula mula dan, tentu saja termasuk, open.mp. ## Wiki SA-MP sudah tiada Sayangnya, wiki SA-MP telah offline september lalu - beberapa konten website nya dapat ditemukan di public internet archive. Pada intinya, kami butuh bantuan komunitas untuk memindahkan wiki yang lama ke rumah barunya, disini! Jika kamu berminat, cek [halaman ini](/docs/meta/Contributing) untuk info lebih lanjut. Jika kamu tidak mengerti menggunakan GitHub atau mengkonversi HTML, jangan khawatir! Kamu dapat membantu kami dengan memberi tahu kami tentang issue (melalui [Discord](https://discord.gg/samp), [forum](https://forum.open.mp) atau social media) dan yang paling penting: _sebarkan!_ Jadi pastikan untuk bookmark situs ini dan bagikan kepada semua yang sedang mencari kemana Wiki SA-MP pergi. Kami menerima kontribusi untuk memperbaiki dokumentasi dan juga tutorial dan panduan untuk membuat sesuatu yang simpel seperti membuat gamemodes yang simpel dan cara menggunakan libraries dan plugins. Jika kamu berminat dalam berkontribusi maka silahkan ke [GitHub page](https://github.com/openmultiplayer/wiki) ini.
openmultiplayer/web/docs/translations/id/index.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/index.md", "repo_id": "openmultiplayer", "token_count": 493 }
376
--- title: OnPlayerClickPlayerTextDraw description: Callback ini terpanggil ketika pemain mengklik sebuah player-textdraw. tags: ["player", "textdraw", "playertextdraw"] --- ## Deskripsi Callback ini terpanggil ketika pemain mengklik sebuah player-textdraw. Ini tidak akan terpanggil ketika player membatalkan mode 'select' (ESC) - tetapi pengecualian untuk OnPlayerClickTextDraw. | Nama | Deskripsi | | ------------ | ---------------------------------------- | | playerid | ID dari pemain yang mengklik textdraw. | | playertextid | ID dari player-textraw yang pemain klik. | ## Returns Ini akan selalu terpanggil pertama di filterscripts jadi mengembalikan nilai 1 akan melarang filterscript lain untuk melihatnya. ## Contoh ```c new PlayerText:gPlayerTextDraw[MAX_PLAYERS]; public OnPlayerConnect(playerid) { // Buat TexDraw nya disini gPlayerTextDraw[playerid] = CreatePlayerTextDraw(playerid, 10.000000, 141.000000, "TextDrawKu"); PlayerTextDrawTextSize(playerid, gPlayerTextDraw[playerid], 60.000000, 20.000000); PlayerTextDrawAlignment(playerid, gPlayerTextDraw[playerid],0); PlayerTextDrawBackgroundColor(playerid, gPlayerTextDraw[playerid],0x000000ff); PlayerTextDrawFont(playerid, gPlayerTextDraw[playerid], 1); PlayerTextDrawLetterSize(playerid, gPlayerTextDraw[playerid], 0.250000, 1.000000); PlayerTextDrawColor(playerid, gPlayerTextDraw[playerid], 0xffffffff); PlayerTextDrawSetProportional(playerid, gPlayerTextDraw[playerid], 1); PlayerTextDrawSetShadow(playerid, gPlayerTextDraw[playerid], 1); // Buat ini bisa dipencet PlayerTextDrawSetSelectable(playerid, gPlayerTextDraw[playerid], 1); // Lalu tunjukkan ke player PlayerTextDrawShow(playerid, gPlayerTextDraw[playerid]); return 1; } public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if(newkeys == KEY_SUBMISSION) { SelectTextDraw(playerid, 0xFF4040AA); } return 1; } public OnPlayerClickPlayerTextDraw(playerid, PlayerText:playertextid) { if(playertextid == gPlayerTextDraw[playerid]) { SendClientMessage(playerid, 0xFFFFFFAA, "Anda mengklik sebuah TextDraw, wow!."); CancelSelectTextDraw(playerid); return 1; } return 0; } ``` ## Notes :::warning Ketika player menekan ESC untuk membatalkan pemilihan textdraw, OnPlayerClickTextDraw akan dipanggil dengan ID textraw yang menjadi 'INVALID_TEXT_DRAW'. OnPlayerClickPlayerTextDraw tentu tidak akan terpanggil. ::: ## Fungsi Terkait - [PlayerTextDrawSetSelectable](../functions/PlayerTextDrawSetSelectable.md): Mengatur apakah player-textdraw dapat dipilih menggunakan SelectTextDraw - [OnPlayerClickTextDraw](OnPlayerClickTextDraw.md): Terpanggil ketika player mengklik sebuah textdraw. - [OnPlayerClickPlayer](OnPlayerClickPlayer.md): Terpanggil ketika player mengklik yang lain.
openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerClickPlayerTextDraw.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerClickPlayerTextDraw.md", "repo_id": "openmultiplayer", "token_count": 1069 }
377
--- title: OnPlayerStreamIn description: Callback ini akan terpanggil ketika pemain lain berada di jangkauan stream dari klien pemain. tags: ["player"] --- ## Deskripsi Callback ini akan terpanggil ketika pemain lain berada di jangkauan stream dari klien pemain. | Nama | Deskripsi | | ----------- | ------------------------------------------------------ | | playerid | ID dari pemain lain yang berada dalam jangakauan stream klien pemain. | | forplayerid | ID dari pemain yang berada di jangkauan stream pemain lain. | ## Returns Ini akan selalu terpanggil pertama di filterscripts ## Contoh ```c public OnPlayerStreamIn(playerid, forplayerid) { new string[40]; format(string, sizeof(string), "Player %d berada di sekitarmu.", playerid); SendClientMessage(forplayerid, 0xFFFFFFFF, string); return 1; } ``` ## Catatan :::tip Callback ini akan terpanggil juga oleh NPC. ::: ## Fungsi Terkait
openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerStreamIn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerStreamIn.md", "repo_id": "openmultiplayer", "token_count": 396 }
378
--- title: DestroyObject description: Menghancurkan (menghapus) objek yang sudah di buat dengan CreateObject. tags: [] --- ## Deskripsi Menghancurkan (menghapus) objek yang sudah di buat dengan CreateObject. | Nama | Deskripsi | | -------- | ---------------------------------------------------------- | | objectid | ID dari objek yang akan di hancurkan. | ## Returns Fungsi ini tidak mengembalikan nilai spesifik apapun. ## Contoh ```c public OnObjectMoved(objectid) { DestroyObject(objectid); return 1; } ``` ## Fungsi Terkait - [CreateObject](CreateObject): Membuat Objek. - [IsValidObject](IsValidObject): Mengecek apakah objek tertentu valid. - [MoveObject](MoveObject): Memindahkan objek. - [StopObject](StopObject): Menghentikan suatu objek agar tidak bergerak. - [SetObjectPos](SetObjectPos): Mengatur posisi objek. - [SetObjectRot](SetObjectRot): Mengatur rotasi objek. - [GetObjectPos](GetObjectPos): Mencari lokasi objek. - [GetObjectRot](GetObjectRot): Mengecek rotasi dari objek. - [AttachObjectToPlayer](AttachObjectToPlayer): Menempelkan objek ke pemain. - [CreatePlayerObject](CreatePlayerObject): Membuat satu objek hanya untuk satu pemain. - [DestroyPlayerObject](DestroyPlayerObject): Menghancurkan objek pemain. - [IsValidPlayerObject](IsValidPlayerObject): Mengecek apakah objek pemain tersebut valid. - [MovePlayerObject](MovePlayerObject): Memindahkan objek pemain. - [StopPlayerObject](StopPlayerObject): Memberhentikan objek pemain. - [SetPlayerObjectPos](SetPlayerObjectPos): Mengatur posisi objek pemain. - [SetPlayerObjectRot](SetPlayerObjectRot): Mengatur rotasi objek pemain. - [GetPlayerObjectPos](GetPlayerObjectPos): Mencari lokasi objek pemain - [GetPlayerObjectRot](GetPlayerObjectRot): Mengecek rotasi objek pemain. - [AttachPlayerObjectToPlayer](AttachPlayerObjectToPlayer): Menempelkan objek pemain ke pemain.
openmultiplayer/web/docs/translations/id/scripting/functions/DestroyPickup.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/DestroyPickup.md", "repo_id": "openmultiplayer", "token_count": 699 }
379
--- title: strlen description: Mendapatkan panjang dari sebuah string. tags: ["string"] --- <LowercaseNote /> ## Deskripsi Mendapatkan panjang dari sebuah string. | Nama | Deskripsi | | -------------- | ------------------------------------- | | const string[] | String yang akan dihitung panjangnya. | ## Returns Panjang string dalam bentuk integer. ## Contoh ```c new stringLength = strlen("This is an example string."); // stringLength menjadi 26 ``` ## Related Functions - [strcmp](strcmp): Membanding dua string untuk mengecek apakah mereka sama. - [strfind](strfind): Mencari sebuah string di string lainnya. - [strins](strins): Memasukkan teks kedalam sebuah string. - [strmid](strmid): Mengekstrak bagian dari sebuah string ke string lainnya. - [strpack](strpack): Membungkus sebuah string menjadi string baru. - [strval](strval): Mengkonversi sebuah string menjadi integer. - [strcat](strcat): Menggabungkan dua buah string menjadi sebuah string. - [strdel](strdel): Menghapus bagian dari sebuah string.
openmultiplayer/web/docs/translations/id/scripting/functions/strlen.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/strlen.md", "repo_id": "openmultiplayer", "token_count": 398 }
380
--- id: panelstates title: Keadaan Panel description: Information tentang ukuran byte dan bit status panel yang sesuai. --- :::note Keadaan ini untuk digunakan dengan [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus) dan [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus). ::: ## Digit ke-sekian menyimpan apa? - The **digit pertama** menyimpan keadaan panel **kiri-depan** untuk mobil atau **mesin(-kiri)** untuk pesawat. - The **digit ke-dua** menyimpan keadaan panel **kanan-depan** untuk mobil atau **mesin(-kanan)** untuk pesawat. - The **digit ke-tiga** menyimpan keadaan panel **kiri-belakang** untuk mobil atau **kemudi (di penyeimbang vertikal)** untuk pesawat. - The **digit ke-empat** menyimpan keadaan panel **kanan-belakang** untuk mobil atau **elevator (di ekor)** untuk pesawat. - The **digit ke-lima** menyimpan keadaan panel **kaca depan** untuk mobil atau **kemudi guling (di sayap)** untuk pesawat. - The **digit ke-enam** menyimpan keadaan panel **bemper depan** untuk mobil. - The **digit ke-tujuh** menyimpan keadaan panel **bemper belakang** untuk mobil. Tidak semua kendaraan mendukung panel yang telah disebutkan. Tingkat kerusakan memengaruhi penanganan pesawat cukup banyak dan pesawat akan mengeluarkan asap hitam dari bagian apapun yang telah rusak. Untuk kebanyakan panel, terdapat 4 keadaan: **tidak rusak (nilai 0)**, **rusak (nilai 1)**, **longgar menggantung (nilai 2)**, dan **terlepas (nilai 3)**. Keadaan usak dan longgar menggantung ini cukup rusak (ketika mengubah dari longgar menggantung ke keadaan rusak, panel akan longgar menggantung dan rusak, bukan hanya rusak, tapi hanya rusak kembali jika kendaraan mengalami _re-stream_, ...). Untuk memperbaiki perilaku aneh ini, atur ulang kerusakan untuk panel tersebut dahulu, kemudian terapkan keadaan yang dibutuhkan. Dengan cara ini, dapat memungkinkan untuk membuat sebuah panel longgar menggantung ketika mengendarai, tapi secara fisik tidak rusak (untuk lebih jelas maksud dari ini, ubahlah dari 0 ke 2, daripada dari 0 ke 1 ke 2). Kelihatannya Anda hanya bisa membaca nilai dari keadaan kaca depan. Pengaturan ini mengubah nilai di server, tapi tidak mengubah perubahan secara fisik pada kendaraan. Perhatikan bahwa digit-digit ini dihitung dari belakang, sehingga digit pertama ini digit paling kanan. ## Contoh Kode berikut menjelaskan bahwa bemper mobil bagian depan dan belakang telah dihilangkan: `00000011 00110000 00000000 00000000` Bagaimanapun, SA-MP mengembalikan nilai desimal, sehingga Anda harus mengubahnya dalam bentuk bilangan biner terlebih dahulu untuk mendapatkan hasil seperti di atas. Seperti contoh di atas, SA-MP akan mengembalikan nilai seperti ini: `53477376` ## Contoh penggunaan Untuk menghapus bemper mobil bagian depan dan tidak mengubah panel lainnya: ```c new panels, doors, lights, tires; GetVehicleDamageStatus(vehicleid, panels, doors, lights, tires); UpdateVehicleDamageStatus(vehicleid, (panels | 0b00000000001100000000000000000000), doors, lights, tires); // Bagian '0b' artinya adalah nilai panels dibaca dalam bentuk biner. Sama seperti '0x' menandakan bilangan heksadesimal. ```
openmultiplayer/web/docs/translations/id/scripting/resources/panelstates.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/scripting/resources/panelstates.md", "repo_id": "openmultiplayer", "token_count": 1181 }
381
--- id: controllingaserver title: "Mengendalikan Server" descripion: Perintah yang berguna untuk mengendalikan server. --- ## Mengganti gamemode ### Menjalankan sebuah gamemode kustom/ter-download - Buka direktori server yang telah Anda pasang. (contoh: /Rockstar Games/GTA San Andreas/server) - Ambil file .amx yang telah ter-download/ter-compile dan letakkan di folder gamemodes di mana server yang telah Anda pasang. - Gunakan RCON untuk mengganti mode seperti yang telah dideskripsikan (2.1) - Selain itu, Anda dapat menambah mode baru ke rotasi baru, telah dideskripsikan juga (2.3) ### Menggunakan Filterscript Sama seperti menjalankan gamemode kustom, kecuali: - Letakkan file .amx di folder `filterscripts` - Tambahkan di file server.cfg: `filterscripts <scriptname>` ## Memberi kata sandi untuk server Anda - Jika Anda ingin memberi kata sandi yang di mana hanya teman-teman Anda yang bisa bergabung, tambahkan ini di [server.cfg](server.cfg): ``` password terserah ``` - Ini akan membuat server Anda terproteksi oleh kata sandi yang telah ditetapkan dengan 'terserah' - gantilah dengan kata sandi yang Anda inginkan. - Anda dapat mengubah kata sandi dari dalam game dengan menggunakan `/rcon password passwordbarunya`. - Anda dapat menghapus kata sandi dengan `/rcon password 0` atau dengan menyalakan ulang server. ## Menggunakan RCON ### Masuk Anda bisa masuk ketika di dalam game dengan mengetik `/rcon login password` atau dari luar game dengan menggunakan moe RCON di [Kendali Konsol Jarak Jauh](remoteconsole). Kata sandinya sama dengan yang Anda tetap di file [server.cfg](server.cfg) ### Menambah Pelarangan ##### samp.ban samp.ban adalah file yang digunakan untuk menyimpan pelarangan, termasuk informasi tentang pelarangan: - IP - Tanggal - Waktu - Nama (Nama dari orang atau alasan, lihat [BanEx](../../functions/BanEx)) - Jenis pelarangan Untuk menambah sebuah pelarangan, tambahkan sebuah baris seperti ini: ``` ALAMAT_IP_DI_SINI [28/05/09 | 13:37:00] PEMAIN - ALASAN PELARANGAN ``` Di mana `ALAMAT_IP_DI_SINI`, adalah alamat IP yang ingin Anda larang. ##### Fungsi Ban() Fungsi [Ban](../../functions/Ban) dapat digunakan untuk melarang pemain dari sisi skrip. Fungsi [BanEx](../../functions/BanEx) akan menambah alasan opsional seperti ini: ``` 13.37.13.37 [28/05/09 | 13:37:00] Cheater - INGAME BAN ``` ##### Perintah pelarangan dari RCON Perintah `ban` RCON, dieksekusi dengan mengetik `/rcon ban` di dalam game atau mengetik "ban" di konsol, adalah digunakan untuk melarang pemain tertentu yang ada di server. Untuk melarang sebuah alamat IP, lihat bagian selanjutnya. Dengan mengetik: ``` # Di dalam game: /rcon ban PLAYERID # Konsol: ban PLAYERID ``` ##### banip Perintah `banip` RCON, dieksekusi dengan mengetik `/rcon banip` di dalam game atau mengetik "banip" di konsol, adalah digunakan untuk melarang alamat IP tertentu. Untuk melarang seorang pemain di server Anda, lihat bagian sebelumnya. Peritnah ini menerima wildcard untuk rangeban (pelarangan dengan rentang tertentu). Dengan mengetik: ``` # Di dalam game: /rcon banip IP # Konsol: banip IP ``` ### Menghapus Pelarangan Ketika seseorang telah dilarang, ada dua cara untuk menghapusnya. - Hapus dari samp.ban - Menggunakan perintah RCON `unbanip` #### samp.ban samp.ban dapat ditemukan di direktori server SA-MP Anda, terdapat baris yang berisi informasi di setiap pelarangannya: - IP - Date - Time - Nama (Nama dari orang atau alasan, lihat [BanEx](../../functions/BanEx)) - Jenis pelarangan (INGAME, IP BAN, dll.) Examples: ``` 127.8.57.32 [13/06/09 | 69:69:69] NONE - IP BAN 13.37.13.37 [28/05/09 | 13:37:00] Kyeman - INGAME BAN ``` Untuk menghapus larangannya, cukup harus baris tersebut, kemudian eksekusi perintah RCON `reloadbans` untuk membuat server membaca ulang samp.ban. #### unbanip Perintah RCON unbanip dapat digunakan di dalam game atau dari konsol server (kotak hitam). Untuk menghapus larangan alamat IP, cukup mengetik `/rcon unbanip ALAMAT_IP` di dalam game atau `unbanip ALAMAT_IP` di dalam konsol. Contoh: ``` 13.37.13.37 [28/05/09 | 13:37:00] Kyeman - INGAME BAN ``` ``` # Di dalam game: /rcon unbanip 13.37.13.37 # Konsol: unbanip 13.37.13.37 ``` Untuk menghapus larangannya, cukup gunakan perintah `unbanip`, kemudian eksekusi perintah RCON `reloadbans` untuk membuat server membaca ulang samp.ban. #### reloadbans `samp.ban` adalah sebuah file yang menyimpan informasi alamat IP yang saat ini telah dilarang dari server. File ini dibaca ketika server dinyalakan, jadi ketika Anda menghapus larangan IP atau pemain, Anda HARUS mengetika perintah RCON `reloadbans` untuk membuat server membaca ulang `samp.ban` dan memperbolehkan mereka untuk bergabung ke server. ### Perintah RCON Ketika cmdlist untuk perintah (atau, varlist untuk variabel) yang menggunakan RCON di dalam game (`/rcon cmdlist`). Berikut adalah fungsi yang bisa Anda bisa gunakan sebagai admin: | Perintah | Deskripsi | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `/rcon cmdlist` | Menampilkan sebuah daftar berisi perintah-perintah. | | `/rcon varlist` | Menampilkan sebuah daftar berisi variabel-variabel saat ini. | | `/rcon exit` | Menutup server. | | `/rcon echo [text]` | Memunculkan `[text]` di konsol server (BUKAN di dalam game konsol pemain). | | `/rcon hostname [name]` | Mengganti teks hostname (_contoh: /rcon hostname my server_). | | `/rcon gamemodetext [name]` | Mengganti teks gamemode (_contoh: /rcon gamemodetext my gamemode_). | | `/rcon mapname [name]` | Mengganti teks nama peta (_contoh: /rcon mapname San Andreas_). | | `/rcon exec [filename]` | Mengeksekusi file yang mengandung server.cfg (_contoh: /rcon exec blah.cfg_). | | `/rcon kick [ID]` | Menendang pemain berdasarkan ID pemain (_contoh: /rcon kick 2_). | | `/rcon ban [ID]` | Melarang pemain berdasarkan ID pemain (_contoh: /rcon ban 2_). | | `/rcon changemode [mode]` | Perintah ini akan mengganti gamemode saat ini ke gamemode yang diinginkan (_contoh: jika Anda ingin bermain sftdm: /rcon changemode sftdm_). | | `/rcon gmx` | Memuat gamemode selanjutnya di [server.cfg](server.cfg). | | `/rcon reloadbans` | Memuat ulang samp.ban yang di mana alamat IP yang telah dilarang disimpan. Seharusnya digunakan setelah menghapus pelarangannya. | | `/rcon reloadlog` | Memuat ulang server_log.txt. Tidak menampak efek apapun. | | `/rcon say` | Memunculkan sebuah pesan ke pemain di konsol klien. (contoh: `/rcon say hello` akan muncul `Admin: hello`). | | `/rcon players` | Memunculkan pemain yang ada di server (nama, alamat IP, dan ping). | | `/rcon banip [IP]` | Melarang berdasarkan alamat IP (_contoh: /rcon banip 127.0.0.1_). | | `/rcon unbanip [IP]` | Menghapus larangan berdasarkan alamat IP (_contoh: /rcon unbanip 127.0.0.1_). | | `/rcon gravity` | Mengganti gravitasi (_contoh: /rcon gravity 0.008_). | | `/rcon weather [ID]` | Mengganti cuaca (_contoh: /rcon weather 1_). | | `/rcon loadfs` | Memuat filterscript (_contoh: /rcon loadfs adminfs_). | | `/rcon weburl [server url]` | Mengganti URL server di masterlists/klien SA-MP. | | `/rcon unloadfs` | Menghentikan filterscript (_contoh: /rcon unloadfs adminfs_). | | `/rcon reloadfs` | Memuat ulang filterscript (_contoh: /rcon reloadfs adminfs_). | | `/rcon rcon\_password [PASSWORD]` | Mengganti password RCON | | `/rcon password [password]` | Mengatur/menghapus kata sandi server | | `/rcon messageslimit [count]` | Mengubah jumlah pesan yang dikirim klien ke server per detik. (nilai awal 500) | | `/rcon ackslimit [count]` | Mengubah batasan acks (nilai awal 3000) | | `/rcon messageholelimit [count]` | Mengubah batasan lubang pesan (nilai awal 3000) | | `/rcon playertimeout [limit m/s]` | Mengubah waktu dalam milisekon hingga pemain dianggap timeout ketika tidak mengirim paket apapun. (nilai awal 1000) | | `/rcon language [language]` | Mengubah bahasa server (_contoh: /rcon language English_). Muncul di penjelajah server. | Jumlah/pembatasan di atas dibuat untuk menghindari beberapa alat yang bisa menyerang server SA-MP dengan membuatnya freeze atau crash. Jadi, cukup atur sesuai dengan server Anda. Nilai awal hanyalah nilai awal, jika Anda mengalami sesuatu yang tidak beres, cukup tambahkan nilainya secepat mungkin, jadi pemain yang tidak bersalah tidak akan ditendang. [Baca lebih lanjut](http://web-old.archive.org/web/20190426141744/https://forum.sa-mp.com/showpost.php?p=2990193&postcount=47) ### Callback dan Fungsi Terkait Berikut adalah callback dan fungsi yang mungkin berguna, karena mereka terkait dengan artikel ini atau sebaliknya. #### Callback - [OnRconLoginAttempt](../../callbacks/OnRconLoginAttempt): Terpanggil ketika ada yang berusaha untuk masuk ke RCON. #### Fungsi - [IsPlayerAdmin](../../functions/IsPlayerAdmin): Memeriksa apakah pemain sudah masuk ke RCON. - [SendRconCommand](../../functions/SendRconCommand): Mengirim perintah RCON melalui skrip.
openmultiplayer/web/docs/translations/id/server/controllingserver.md/0
{ "file_path": "openmultiplayer/web/docs/translations/id/server/controllingserver.md", "repo_id": "openmultiplayer", "token_count": 6211 }
382
--- title: AddPlayerClass description: Dodaje klasę do wyboru klasy. tags: ["player"] --- ## Opis Dodaje klasę do wyboru klas. Klasy umożliwiają graczom spawnowanie się z wybranym przez nich skinem. | Nazwa | Opis | | ------------- | ----------------------------------------------------------- | | modelid | Skin, z którym gracze będą się spawnować. | | Float:spawn_x | Koordynat X miejsca spawnu tej klasy. | | Float:spawn_y | Koordynat Y miejsca spawnu tej klasy. | | Float:spawn_z | Koordynat Z miejsca spawnu tej klasy. | | Float:z_angle | Kierunek, w który skierowany będzie gracz po zespawnowaniu. | | weapon1 | Pierwsza broń, którą gracz otrzyma po zespawnowaniu. | | weapon1_ammo | Liczba sztuk amunicji dla pierwszej broni. | | weapon2 | Druga broń, którą gracz otrzyma po zespawnowaniu. | | weapon2_ammo | Liczba sztuk amunicji dla drugiej broni. | | weapon3 | Trzecia broń, którą gracz otrzyma po zespawnowaniu. | | weapon3_ammo | Liczba sztuk amunicji dla trzeciej broni. | ## Zwracane wartości ID klasy, która właśnie została dodana. 319, jeżeli limit klas (320) został osiągnięty. Najwyższe możliwe ID klasy to 319. ## Przykłady ```c public OnGameModeInit() { // Gracze mogą się zespawnować skinem CJ (0) lub skinem The Trutha (1). AddPlayerClass(0, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // CJ AddPlayerClass(1, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // The Truth return 1; } ``` ## Uwagi :::tip Maksymalne ID klasy to 319 (zaczynając od 0, czyli łącznie 320 klas). Po osiągnięciu tego limitu, każda następna dodana klasa będzie zastępować ID 319. ::: ## Powiązane funkcje - [AddPlayerClassEx](AddPlayerClassEx.md): Dodaje klasę z domyślną drużyną. - [SetSpawnInfo](SetSpawnInfo.md): Konfiguruje ustawienia spawnu dla gracza. - [SetPlayerSkin](SetPlayerSkin.md): Ustawia skin gracza.
openmultiplayer/web/docs/translations/pl/scripting/functions/AddPlayerClass.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pl/scripting/functions/AddPlayerClass.md", "repo_id": "openmultiplayer", "token_count": 1131 }
383
--- title: AttachCameraToPlayerObject description: Przyczepia kamerę gracza do obiektu stworzonego tylko dla niego. tags: ["player"] --- ## Opis Przyczepia kamerę gracza do obiektu stworzonego tylko dla niego. Gracz może poruszać swoją kamerą, gdy jest przyczepiona do obiektu. Można z tego korzystać razem z MovePlayerObject i AttachPlayerObjectToVehicle. | Nazwa | Opis | | -------------- | -------------------------------------------------------------------- | | playerid | ID gracza, który będzie miał przyczepioną kamerę do swojego obiektu. | | playerobjectid | ID obiektu gracza, do którego będzie przyczepiona kamera. | ## Zwracane wartości Ta funkcja nie zwraca żadnych konkretnych wartości. ## Przykłady ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/attach", false)) { new playerobject = CreatePlayerObject(playerid, 1245, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0); AttachCameraToPlayerObject(playerid, playerobject); SendClientMessage(playerid, 0xFFFFFFAA, "Twoja kamera jest teraz przyczepiona do obiektu."); return 1; } return 0; } ``` ## Uwagi :::tip Obiekt musi zostać utworzony, zanim spróbujemy przyczepić do niego inny obiekt. ::: ## Powiązane funkcje - [AttachCameraToObject](AttachCameraToObject.md): Przyczepia kamerę gracza do globalnego obiektu. - [SetPlayerCameraPos](SetPlayerCameraPos.md): Ustawia pozycję kamery gracza. - [SetPlayerCameraLookAt](SetPlayerCameraLookAt.md): Ustawia, gdzie ma być skierowana kamera gracza.
openmultiplayer/web/docs/translations/pl/scripting/functions/AttachCameraToPlayerObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pl/scripting/functions/AttachCameraToPlayerObject.md", "repo_id": "openmultiplayer", "token_count": 740 }
384
--- title: Contribuição description: Como contribuir com SA-MP Wiki e a documentação open.mp. --- Esta documentação está aberta para qualquer um contribuir para seu desenvolvimento e aperfeiçoamento! Tudo que você precisa é uma conta no [GitHub](https://github.com) e algum tempo livre. Você inclusive não necessita ter conhecimentos de Git, podendo fazer tudo pela interface da web. ## Editando Conteúdo Em cada página há um botão que o(a) leverá para uma página no GitHub para editar: ![Edit this page link present on each wiki page](images/contributing/edit-this-page.png) Por exemplo, clicando em [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) o(a) levará para [esta página](https://github.com/openmultiplayer/web/edit/master/docs/scripting/functions/SetVehicleAngularVelocity.md) a qual contém um editor de texto para fazer algumas mudanças no arquivo(assumindo que você esteja logado(a) no GitHub). Faça suas edições e envie um "Pull Request", isso significa que os organizadores da Wiki e outros membros da comunidade irão revisar suas mudanças, discutir se são necessárias então incorporá-las ou não. ## Adicionando um Conteúdo Novo Adicionar um novo conteúdo pode ser um pouco mais complicado, poderá fazer de duas maneiras: ### Interface do GitHub Quando pesquisar um diretório no GitHub, haverá um botão Add file no canto direito superior do arquivo: ![Add file button](images/contributing/add-new-file.png) Você pode tanto enviar um arquivo 'Markdown' que você já escreveu, ou escrever diretamento no editor de texto do GitHub. Este arquivo _PRECISA_ conter a extensão `.md` e conter 'Markdown'. Para mais informações sobre 'Markdown, acesse [este guia](https://guides.github.com/features/mastering-markdown/). Uma vez feito isso, clique em "Propose new file" (Propor novo arquivo) e um "Pull Request" será aberto para revisão. ### Git Se você deseja usar Git, tudo que precisa é clonar o repositório da WIki com: ```sh git clone https://github.com/openmultiplayer/wiki.git ``` Abre o repositório em seu editor favorito. Eu recomendo Visual Studio Code, pois contém ótimas ferramentas de edição e formatação de arquivos "Markdown". Como pode ver, estou escrevendo usando Visual Studio Code! ![Visual Studio Code markdown preview](images/contributing/vscode.png) Eu recomendo duas extensões que irão aperfeiçoar sua experiência: - [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) por David Anson - Essa extensão faz com que o arquivo seja formatado corretamente, prevenindo alguns erros semânticos e sintáticos. Nem todos avisos são importantes, mas alguns podem ajudar a melhorar e leitura. Use ao seu julgamento, em caso de dúvida, consulte um revisor. - [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) Pelo time Prettier.js - Este formatará automaticamente seus arquivos "Markdown" para que todos usem um estilo consistente. O repositório da Wiki contém algumas configurações em `package.json` que a extensão deverá usar automaticamente. Tenha certeza de habilitar "Format On Save" nas configurações do seu editor, para que os arquivos sejam formatados automaticamente a cada save. ## Notas, Dicas e Convenções ### Links Internos Não utilize URL's absolutas para links dentro do site. Use caminhos relativos. - ❌ ```md Para ser usado com [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer) ``` - ✔ ```md Para ser usado com [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer) ``` `../` significa "vá até o diretório", então se o arquivo que está editando estiver dentro do diretório `functions` e estiver 'linkando' com `callbacks` você usará `../` para ir até `scripting/` e então `callbacks/` para entrar no diretório, e então o nome do arquivo (sem `.md`) da callback que gostaria de 'linkar'. ### Imagens Imagens vão dentro de um sub-diretório em `/static/images`. Então quando você 'linkar' uma imagem em `![]()` você utiliza `/images/` como o caminho base (sem necessidade de `static`, é apenas para o repositório). Em caso de dúvida, leia uma página que contenha imagens e copie como está feito nela. ### Metadata A primeira coisa em _qualquer_ documento aqui deve ser a "metadata": ```mdx --- title: Minha Documentação description: Esta é uma página sobre coisas, comidas e X-Burguer! --- ``` Toda página deve conter um título e uma descrição. Para uma lista completa do que pode ir entre `---`, verifique [a documentação do Docusaurus](https://v2.docusaurus.io/docs/markdown-features#markdown-headers). ### Títulos Não crie um Título "level 1" (`<h1>`) com `#`, pois este é gerado automaticamente. Seu primeiro título deverá _sempre_ ser `##` - ❌ ```md # Meu Título Esta documentação é para... # Sub-seção ``` - ✔ ```md Esta documentação é para... ## Sub-seção ``` ### Utilize `Code Snippets` para Referências Técnicas Quando escrever um parágrafo que contém nomes de funções, números, expressões ou qualquer outra coisa que não seja linguagem básica (comunicação), cerque-os com \`sinal de crase\`. Isso facilita separar a linguagem ao descrever coisas de referência técnica, elementos como nome de funções ou partes de códigos. - ❌ > A função fopen retornará um valor com uma tag do tipo File:, não há problema nesta linha pois o valor de retorno é armazenado em um variável que também tem a tag File:. Entretanto, na próxima linha o valor 4 é adicionado ao arquivo. 5 não tem tag [...] - ✔ > A função `fopen` retornará um valor com uma tag do tipo `File:`', não há problema nesta linha pois o valor de retorno é armazenado em um variável que também tem a tag `File:`. Entretanto, na próxima linha o valor `4` é adicionado ao arquivo. `4` não tem tag [...] No exemplo acima, `fopen` é o nome de uma função e não uma palavra em português, então cerca-la com `code` "snippet" (crase) ajuda a distinguir um do outro. Também, se o parágrafo estiver relizando uma referência a um bloco de código, isso ajudaria o leitor a associar as palavras com o exemplo. ### Tabelas Se a tabela tem títulos, eles vão na parte de cima: - ❌ ```md | | | | ------- | ------------------------ | | Vida | Estado do Motor | | 650 | Sem dano | | 650-550 | Fumaça Branca | | 550-390 | Fumaça Cinza | | 390-250 | Fumaça Preta | | < 250 | Em chamas (irá explodir) | ``` - ✔ ```md | Vida | Estado do Motor | | ------- | ------------------------ | | 650 | Sem dano | | 650-550 | Fumaça Branca | | 550-390 | Fumaça Cinza | | 390-250 | Fumaça Preta | | < 250 | Em chamas (irá explodir) | ``` ## Migrar do SA-MP Wiki Maior parte do conteúdo já foi movido, mas se encontrar uma página faltando, aqui está um pequeno guia de como converter o conteúdo para "Markdown". ### Pegando o HTML 1. Clique neste botão (Firefox) ![image](images/contributing/04f024579f8d.png) (Chrome) ![image](images/contributing/f62bb8112543.png) 2. Passe o mouse sobre o canto esquerdo superior da página, na margem da esquerda ou no canto até você ver `#content` ![image](images/contributing/65761ffbc429.png) Ou pesquise por `<div id=content>` ![image](images/contributing/77befe2749fd.png) 3. Copie o HTML interno daquele elemento ![image](images/contributing/8c7c75cfabad.png) Agora você tem _apenas_ o código HTML do _conteúdo_ da página, então poderá converter para "Markdown". ### Convertendo HTML para Markdown Para converter HTML básico (sem tabelas) para "Markdown" use: https://domchristie.github.io/turndown/ ![image](images/contributing/77f4ea555bbb.png) ^^ Veja como bagunçou completamente a tabela... ### Tabelas HTML Para Tabelas Markdown Devido a ferramenta superior não suportar tabelas, utilize esta: https://jmalarcon.github.io/markdowntables/ Então copie apenas o elemento `<table>`: ![imagem](images/contributing/57f171ae0da7.png) ### Toques Finais A conversão não será perfeita, então uma limpeza manual será necessária. As ferramentas de formatação listadas acima devem ajuda-lo, mas ainda poderá gastar um tempo realizando trabalho manual. Se você não tem tempo, não se preocupe! Envie um rascunho não finalizado, então alguém poderá continuar de onde você parou! ## Acordo de Licença Todo projeto open.mp contém um [Acordo de Licença do Contribuidor](https://cla-assistant.io/openmultiplayer/homepage). Isso, basicamente, significa que você concorda em usarmos o seu trabalho e coloca-lo sob a licença de código aberto. Quando abrir um Pull Request pela primeira vez, o bot CLA-Assistant irá colocar um link onde você pode assinar o acordo.
openmultiplayer/web/docs/translations/pt-BR/meta/Contributing.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/meta/Contributing.md", "repo_id": "openmultiplayer", "token_count": 3495 }
385
--- title: OnNPCModeExit description: Essa callback é executada quando o script de um NPC é descarregado. tags: [] --- ## Descrição Essa callback é executada quando o script de um NPC é descarregado. ## Exemplos ```c public OnNPCModeExit() { print("O script do NPC foi descarregado!"); return 1; } ``` ## Callbacks Relacionadas - [OnNPCModeInit](../callbacks/OnNPCModeInit): Executada quando o script do NPC é carregado.
openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnNPCModeExit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnNPCModeExit.md", "repo_id": "openmultiplayer", "token_count": 160 }
386
--- title: OnPlayerEnterVehicle description: Esta callback é chamada quando um jogador começa a entrar em um veículo, isso significa que o jogador não está no veículo ainda quando esta callback é chamada. tags: ["player", "vehicle"] --- ## Descrição Esta callback é chamada quando um jogador começa a entrar em um veículo, isso significa que o jogador não está no veículo ainda quando esta callback é chamada. | Nome | Descrição | | ----------- | ----------------------------------------------------- | | playerid | O ID do jogador que está tentando entra no veículo. | | vehicleid | O ID do veículo que o jogador está tentando entrar. | | ispassenger | 0 se entrar como piloto. 1 se entrar como passageiro. | ## Retorno Sempre é chamada primeiro em filterscripts. ## Exemplo ```c public OnPlayerEnterVehicle(playerid, vehicleid, ispassenger) { new string[128]; format(string, sizeof(string), "Você está entrando no veículo de id %i", vehicleid); SendClientMessage(playerid, 0xFFFFFFFF, string); return 1; } ``` ## Notas :::tip Esta callback é chamada quando um jogador começa a entrar em um veículo, não quando ele entram nele. Veja OnPlayerStateChange. Esta callback ainda é chamada se o jogador for impedido de entrar no veículo. ::: ## Funções Relacionadas - [PutPlayerInVehicle](../functions/PutPlayerInVehicle.md): Coloca um jogador em um veículo. - [GetPlayerVehicleSeat](../functions/GetPlayerVehicleSeat.md): Verifica qual assento o jogador está.
openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerEnterVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerEnterVehicle.md", "repo_id": "openmultiplayer", "token_count": 578 }
387
--- title: OnPlayerSelectedMenuRow description: Esta callback é chamada quano um jogador seleciona um item de um menu (ShowMenuForPlayer). tags: ["player", "menu"] --- ## Descrição Esta callback é chamada quano um jogador seleciona um item de um menu (ShowMenuForPlayer). | Nome | Descrição | | -------- | ----------------------------------------------------------- | | playerid | O ID do jogador que selecionou um item de um menu | | row | O ID da linha que o jogador selecionou, sendo a primeira o ID 0. | ## Retorno Sempre é chamada primeiro na Gamemode. ## Exemplo ```c new Menu:MeuMenu; public OnGameModeInit() { MeuMenu = CreateMenu("Menu Exemplo", 1, 50.0, 180.0, 200.0, 200.0); AddMenuItem(MeuMenu, 0, "Item 1"); AddMenuItem(MeuMenu, 0, "Item 2"); return 1; } public OnPlayerSelectedMenuRow(playerid, row) { if (GetPlayerMenu(playerid) == MeuMenu) { switch(row) { case 0: print("Item 1 Selecionado"); case 1: print("Item 2 Selecionado"); } } return 1; } ``` ## Notas :::tip O ID do menu não é passado através da callback, portanto, GetPlayerMenu deve ser utilizado para determinar em qual menu o jogador selecionou o item. ::: ## Funções Relacionadas - [CreateMenu](../functions/CreateMenu): Cria um menu. - [DestroyMenu](../functions/DestroyMenu): Destrói um menu. - [AddMenuItem](../functions/AddMenuItem): Adiciona um item a um menu em específico. - [ShowMenuForPlayer](../functions/ShowMenuForPlayer): Mostra o menu para algum jogador. - [HideMenuForPlayer](../functions/HideMenuForPlayer): Esconde o menu para algum jogador.
openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerSelectedMenuRow.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerSelectedMenuRow.md", "repo_id": "openmultiplayer", "token_count": 686 }
388
--- title: OnVehicleRespray description: Essa callback é chamada quando um jogador sai de uma Garagem de Personalização, mesmo sem trocar cores. tags: ["vehicle"] --- ## Descrição Essa callback é chamada quando um jogador sai de uma Garagem de Personalização, mesmo sem trocar cores. Cuidado, Oficinas de Pintura não chamam essa callback nativamente. | Nome | Descrição | | --------- | ------------------------------------------------------------ | | playerid | ID do jogador que está dirigindo o veículo. | | vehicleid | ID do veículo que foi repintado. | | color1 | Nova cor primária pintada no veículo. | | color2 | Nova cor secundária pintada no veículo. | ## Retornos Sempre é chamada primeiro no Gamemode então retornar 0 lá bloqueia Filterscripts de chamarem ela. ## Exemplos ```c public OnVehicleRespray(playerid, vehicleid, color1, color2) { new string[48]; format(string, sizeof(string), "Você repintou seu veículo ID %d para as cores %d e %d!", vehicleid, color1, color2); SendClientMessage(playerid, COLOR_GREEN, string); return 1; } ``` ## Notas :::tip Essa callback não é chamada ao usar ChangeVehicleColor. Estranhamente, não é chamada também ao ir em uma Oficina de Pintura (só Garagens de Personalização). Código para conserto: http://pastebin.com/G81da7N1 ::: :::warning Bug(s) Notados: Visualizar certos componentes dentro da Garagem de Personalização podem chamar essa callback sem querer. ::: ## Funções Relacionadas - [ChangeVehicleColor](../functions/ChangeVehicleColor): Mudar a cor de um veículo. - [ChangeVehiclePaintjob](../functions/ChangeVehiclePaintjob): Mudar o trabalho de pintura de um veículo. - [OnVehiclePaintjob](OnVehiclePaintjob): Chamada quando o trabalho de pintura de veículo muda. - [OnVehicleMod](OnVehicleMod): Chamada quando o componente de um veículo é modificado. - [OnEnterExitModShop](OnEnterExitModShop): Chamada quando um veículo entra ou sai de uma Garagem de Modificação.
openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnVehicleRespray.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnVehicleRespray.md", "repo_id": "openmultiplayer", "token_count": 869 }
389
--- title: AllowInteriorWeapons description: Define se o uso de armas no interior é permitido ou não. tags: [] --- ## Descrição Define se o uso de armas no interior é permitido ou não. | Name | Descrição | | ----- | ----------------------------------------------------------------------------------------------------- | | allow | 1 para habilitar armas em interiores (habilitado por padrão), 0 para desabilitar armas em interiores. | ## Retorno Esta função não retorna nenhum valor específico. ## Exemplos ```c public OnGameModeInit() { // Isto permitirá armas dentro de interiores. AllowInteriorWeapons(1); return 1; } ``` ## Notas :::warning Esta função não funciona na atual versão do SA:MP! ::: ## Funções Relacionadas - [SetPlayerInterior](SetPlayerInterior.md): Define o interior de um jogador. - [GetPlayerInterior](GetPlayerInterior.md): Obtém o atual interior de um jogador. - [OnPlayerInteriorChange](../callbacks/OnPlayerInteriorChange.md): É chamado quando um jogador muda de interior.
openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AllowInteriorWeapons.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AllowInteriorWeapons.md", "repo_id": "openmultiplayer", "token_count": 440 }
390
--- title: GameModeExit description: Encerra o atual gamemode. tags: [] --- ## Descrição Encerra o atual gamemode. ## Exemplos ```c if (OneTeamHasWon) { GameModeExit(); } ``` ## Funções Relacionadas
openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GameModeExit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GameModeExit.md", "repo_id": "openmultiplayer", "token_count": 92 }
391
--- title: GetPlayerHealth description: A função GetPlayerHealth permite obter a vida de um jogador. tags: ["player"] --- ## Descrição A função GetPlayerHealth permite obter a vida de um jogador. Útil para detetar cheats, entre outras coisas. | Nome | Descrição | | ------------- | -------------------------------------------------- | | playerid | O ID do jogador. | | &Float:health | Float para armazenar vida, passado por referência. | ## Retorno 1 - Sucesso 0 - Falha (por exemplo, jogador não está conectado). A vida de um jogador é armazenada na variável especificada. ## Exemplos ```c // Define a vida do jogador para 50 se for menor que // 50 assim que ele digitar /doctor. if (strcmp(cmdtext, "/doctor", true) == 0) { new Float:health; GetPlayerHealth(playerid,health); if (health < 50.0) { SetPlayerHealth(playerid, 50.0); } return 1; } ``` ## Notas :::warning Mesmo que a vida possa ser definida para valores quase infinitos no lado do servidor, os usuários vão reportar valores até 255. Qualquer valor superior não funcionará; 256 passa a 0, 257 passa a 1, etc. A vida é obtida arredondando os integers: se definir 50.15, o jogador obtém 50.0. ::: ## Funções Relacionadas - [SetPlayerHealth](SetPlayerHealth): Define a vida de um jogador. - [GetVehicleHealth](GetVehicleHealth): Verifica a vida de um veículo. - [GetPlayerArmour](GetPlayerArmour): Verifica o colete/armadura de um jogador.
openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetPlayerHealth.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetPlayerHealth.md", "repo_id": "openmultiplayer", "token_count": 626 }
392
--- title: SetVehicleHealth description: Define a vida de um veículo. tags: ["vehicle"] --- ## Descrição Define a vida de um veículo. Quando a vida do veículo diminui, o motor irá fazer fumaça, até que arde quando diminuir para menos de 250 (25%). | Nome | Descrição | | ------------ | --------------------------------- | | vehicleid | O ID do veículo a definir a vida. | | Float:health | A vida, em valor float. | ## Retorno 1: A função foi executada com sucesso. 0: A função falhou ao ser executada. Isso significa que o veículo não existe. ## Exemplos ```c if (strcmp("/fixengine", cmdtext, true) == 0) { new vehicleid = GetPlayerVehicleID(playerid); SetVehicleHealth(vehicleid, 1000); SendClientMessage(playerid, COLOUR_WHITE, "O motor do veículo foi reparado."); return 1; } ``` ## Notas :::tip A vida máxima do veículo é 1000. Valores maiores são possíveis. Para mais informações sobre os valores de vida dos veículos , veja [esta](../resources/vehiclehealth.md) página. ::: ## Funções Relacionadas - [GetVehicleHealth](GetVehicleHealth.md): Verifica a vida de um veículo. - [RepairVehicle](RepairVehicle.md): Repara totalmente um veículo. - [SetPlayerHealth](SetPlayerHealth.md): Define a vida de um jogador. - [OnVehicleDeath](../callbacks/OnVehicleDeath.md): É chamado quando um veículo é destruído.
openmultiplayer/web/docs/translations/pt-BR/scripting/functions/SetVehicleHealth.md/0
{ "file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/SetVehicleHealth.md", "repo_id": "openmultiplayer", "token_count": 574 }
393
--- title: Contribuire description: Cum să contribui la SA-MP Wiki și la documentația open.mp --- Această sursă de documentare este deschisă pentru oricine vrea să contribuie cu modificări! Tot ce aveți nevoie este de un cont [GitHub](https://github.com) și ceva timp liber. Nici nu trebuie să cunoașteți Git, puteți face totul din interfața web! Dacă doriți să ajutați la menținerea unei limbi specifice, deschideți un PR împotriva fișierului [CODEOWNERS](https://github.com/openmultiplayer/web/blob/master/CODEOWNERS) și adăugați o linie pentru directorul dvs. de limbă cu numele dvs. de utilizator. ## Editarea conținutului În fiecare pagină, există un buton care vă duce la pagina GitHub pentru editare: ![Edit this page](images/contributing/edit-this-page.png) De exemplu, făcând clic pe aceasta pe [SetVehicleAngularVelocity](https://www.open.mp/docs/scripting/functions/SetVehicleAngularVelocity) vă duce la [această pagină](https://github.com/openmultiplayer/web/blob/master/docs/scripting/functions/SetVehicleAngularVelocity.md) care vă prezintă un editor de text pentru a face modificări la fișier (presupunând că sunteți conectat la GitHub). Efectuați modificarea și trimiteți un „Pull Request”, aceasta înseamnă că gestionarii Wiki și alți membri ai comunității vă pot examina modificarea, discuta dacă are nevoie de modificări suplimentare și apoi o pot combina. ## Adaugarea unui continut nou: Adăugarea de conținut nou este puțin mai implicată. Puteți face acest lucru în două moduri: ### Interfata GitHub Când răsfoiți un director pe GitHub, există un buton „Add File” în colțul din dreapta sus al listei de fișiere: ![Add file](images/contributing/add-new-file.png) Puteți încărca fie un fișier Markdown pe care l-ați scris deja, fie îl puteți scrie direct în editorul de text GitHub. Fișierul _trebuie_ să aibă o extensie `.md` și să conțină Markdown. Pentru mai multe informații despre Markdown, consultați [acest ghid](https://guides.github.com/features/mastering-markdown/). Odată ce ați terminat, apăsați „Propose new file” și un Pull Request va fi deschisă pentru examinare. ### Git Dacă doriți să utilizați Git, tot ce trebuie să faceți este să clonați depozitul Wiki cu: ```sh git clone https://github.com/openmultiplayer/wiki.git ``` Deschide-l în editorul tău preferat. Recomand Visual Studio Code, deoarece are unele instrumente excelente pentru editarea și formatarea fișierelor Markdown. După cum puteți vedea, scriu acest lucru folosind Visual Studio Code! ![Visual Studio Code markdown preview](images/contributing/vscode.png) Vă recomandăm două extensii pentru a vă îmbunătăți experiența: - [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) de David Anson - aceasta este o extensie care vă asigură că Markdown-ul dvs. este formatat corect. Previne unele greșeli sintactice și semantice. Nu toate avertismentele sunt importante, dar unele pot ajuta la îmbunătățirea lizibilității. Folosiți cea mai bună judecată și, dacă aveți dubii, întrebați un recenzor! - [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) de echipa Prettier.js - acesta este un formatator care vă va forma automat fișierele Markdown, astfel încât toate să folosească un stil consistent. Depozitul Wiki are câteva setări în „package.json” pe care extensia ar trebui să le utilizeze automat. Asigurați-vă că activați „Format On Save” în setările editorului, astfel încât fișierele dvs. Markdown să fie formatate automat de fiecare dată când salvați! ## Notite, Trucuri si conventii ### Link-uri interne Nu utilizați adrese URL absolute pentru link-uri inter-site. Folosiți căi relative. - ❌ ```md Pentru a fi folosit cu [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer) ``` - ✔ ```md Pentru a fi folosit cu [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer) ``` `../` înseamnă „mergeți într-un director”, deci dacă fișierul pe care îl editați se află în directorul `functions` și vă conectați la „ callbacks ”, utilizați`../`pentru a merge la`scripting /`apoi`callbacks /`pentru a intra în directorul callbacks, apoi numele fișierului (fără`.md`) al callback-ului pe care doriți să-l legați. ### Imagini Imaginile intră într-un subdirector din interiorul `/ static / images`. Apoi, atunci când conectați o imagine într-un `! [] ()` Pur și simplu utilizați `/ images /` ca cale de bază (nu este nevoie de `static`, care este doar pentru depozit). Dacă aveți dubii, citiți o altă pagină care folosește imagini și copiați cum se face acolo. ### Metadata Primul lucru din _orice_ document ar trebui să fie metadatele: ```mdx --- title: My Documentation description: This is a page about stuff and things and burgers, yay! --- ``` Orice pagina ar trebui să includă un titlu și o descriere. Pentru o listă completă a ceea ce poate merge între `---`, consultați [documentația Docusaurus](https://v2.docusaurus.io/docs/markdown-features#markdown-headers). ### Titluri Nu creați un titlu de nivel 1 (`<h1>`) cu `#` deoarece acesta este generat automat. Primul dvs. titlu ar trebui să fie întotdeauna `##` - ❌ ```md # My Title This is documentation for ... # Sub-Section ``` - ✔ ```md This is documentation for ... ## Sub-Section ``` ### Utilizați fragmentele `Code` pentru referințe tehnice Când scrieți un paragraf care conține nume de funcții, numere, expresii sau orice altceva care nu este un limbaj scris standard, înconjurați-le cu astfel de \`backticks\`. Acest lucru face mai ușoară separarea limbajului pentru descrierea lucrurilor de referințe la elemente tehnice, cum ar fi numele funcțiilor și piesele de cod. - ❌ > The fopen function will return a value with a tag of type File:, there is no problem on that line as the return value is being stored to a variable also with a tag of File: (note the cases are the same too). However on the next line the value 4 is added to the file handle. 4 has no tag [...] - ✔ > The `fopen` function will return a value with a tag of type `File:`, there is no problem on that line as the return value is being stored to a variable also with a tag of `File:` (note the cases are the same too). However on the next line the value `4` is added to the file handle. `4` has no tag În exemplul de mai sus, `fopen` este un nume de funcție, nu un cuvânt în limba engleză, așa că înconjurarea acestuia cu marcatori de fragment `code` ajută la deosebirea acestuia de celălalt conținut. De asemenea, dacă paragraful se referă la un bloc de cod de exemplu, acest lucru îl ajută pe cititor să asocieze cuvintele cu exemplul. ### Tabele Dacă un tabel are titluri, acestea trec în partea de sus: - ❌ ```md | | | | ------- | ------------------------------------ | | Health | Engine Status | | 650 | Undamaged | | 650-550 | White Smoke | | 550-390 | Grey Smoke | | 390-250 | Black Smoke | | < 250 | On fire (will explode seconds later) | ``` - ✔ ```md | Health | Engine Status | | ------- | ------------------------------------ | | 650 | Undamaged | | 650-550 | White Smoke | | 550-390 | Grey Smoke | | 390-250 | Black Smoke | | < 250 | On fire (will explode seconds later) | ``` ## Migrarea de pe SA-MP Wiki Majoritatea conținutului a fost mutat, dar dacă găsiți o pagină care lipsește, iată un scurt ghid pentru conversia conținutului în Markdown. ### Obținerea codului HTML 1. Click pe acest buton: (Firefox) ![image](images/contributing/04f024579f8d.png) (Chrome) ![image](images/contributing/f62bb8112543.png) 2. Plasați cursorul în partea stângă sus a paginii principale wiki, în marginea stângă sau în colț până când vedeți `#content` ![image](images/contributing/65761ffbc429.png) Sau cautati pentru `<div id=content>` ![image](images/contributing/77befe2749fd.png) 3. Copiați HTML-ul interior al acelui element ![image](images/contributing/8c7c75cfabad.png) Acum aveți _numai_ codul HTML pentru _contenutul_ real al paginii, lucrurile care ne interesează și îl puteți converti în Markdown. ### Conversia HTML in Markdown Pentru conversia HTML de bază (fără tabele) la Markdown utilizați: https://domchristie.github.io/turndown/ ![image](images/contributing/77f4ea555bbb.png) ^^ Observă acum că se distrug tabelele ... ### Tabelele HTML către tabelele de reducere Deoarece instrumentul de mai sus nu acceptă tabele, utilizați acest instrument: https://jmalarcon.github.io/markdowntables/ Și copiați doar elementul `<table>` în: ![image](images/contributing/57f171ae0da7.png) ### Curatare Conversia probabil că nu va fi perfectă. Deci va trebui să faceți un pic de curățare manuală. Extensiile de formatare enumerate mai sus ar trebui să vă ajute, dar este posibil să fiți nevoit să petreceți doar timp făcând lucrări manuale. Dacă nu ai timp, nu-ți face griji! Trimiteți o schiță neterminată și altcineva poate ridica locul unde ați rămas! ## Acord de licențiere Toate proiectele open.mp au un [Acord de licență pentru colaboratori](https://cla-assistant.io/openmultiplayer/homepage). Acest lucru înseamnă doar că sunteți de acord să ne permiteți să vă folosim lucrarea și să o puneți sub o licență open-source. Când deschideți o cerere de extragere pentru prima dată, botul CLA-Assistant va posta un link unde puteți semna acordul.
openmultiplayer/web/docs/translations/ro/meta/contributing.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/meta/contributing.md", "repo_id": "openmultiplayer", "token_count": 4245 }
394
--- title: OnPlayerClickTextDraw description: Acest callback este apelat atunci când un jucător face clic pe un textdraw sau anulează modul de selectare cu tasta ESC. tags: ["player", "textdraw"] --- ## Descriere Acest callback este apelat atunci când un jucător face clic pe un textdraw sau anulează modul de selectare cu tasta ESC. | Nume | Descriere | | --------- | ----------------------------------------------------------------------------------------| | playerid | ID-ul jucătorului care a făcut clic pe textdraw. | | clickedid | ID-ul textdraw-ului care a fost apasat. INVALID_TEXT_DRAW dacă selecția a fost anulată. | ## Returnări Este întotdeauna numit primul în filterscripts, așa că returnarea 1 acolo blochează și alte scripturi să-l vadă. ## Exemple ```c new Text:gTextDraw; public OnGameModeInit() { gTextDraw = TextDrawCreate(10.000000, 141.000000, "TextDraw-ul Meu"); TextDrawTextSize(gTextDraw,60.000000, 20.000000); TextDrawAlignment(gTextDraw,0); TextDrawBackgroundColor(gTextDraw,0x000000ff); TextDrawFont(gTextDraw,1); TextDrawLetterSize(gTextDraw,0.250000, 1.000000); TextDrawColor(gTextDraw,0xffffffff); TextDrawSetProportional(gTextDraw,1); TextDrawSetShadow(gTextDraw,1); TextDrawSetSelectable(gTextDraw, 1); return 1; } public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if (newkeys == KEY_SUBMISSION) { TextDrawShowForPlayer(playerid, gTextDraw); SelectTextDraw(playerid, 0xFF4040AA); } return 1; } public OnPlayerClickTextDraw(playerid, Text:clickedid) { if (clickedid == gTextDraw) { SendClientMessage(playerid, 0xFFFFFFAA, "Ați făcut clic pe un textdraw."); CancelSelectTextDraw(playerid); return 1; } return 0; } ``` ## Note :::warning Zona pe care se poate face clic este definită de TextDrawTextSize. Parametrii x și y trecuți acelei funcție nu trebuie să fie zero sau negativi. Nu utilizați CancelSelectTextDraw necondiționat în acest callback. Aceasta are ca rezultat o buclă infinită. ::: ## Funcții similare - [OnPlayerClickPlayerTextDraw](OnPlayerClickPlayerTextDraw): Apelat atunci când un jucător dă clic pe un textdraw de jucător. - [OnPlayerClickPlayer](OnPlayerClickPlayer): Apelat când un jucător face clic pe altul.
openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerClickTextDraw.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerClickTextDraw.md", "repo_id": "openmultiplayer", "token_count": 1049 }
395
--- title: OnPlayerKeyStateChange description: Acest callback este apelat atunci când starea oricărei taste acceptate este schimbată (apăsată/eliberată). tags: ["player"] --- ## Descriere Acest callback este apelat atunci când starea oricărei taste [acceptate](../resources/keys) este schimbată (apăsată/eliberată).<br/>Tastele direcționale nu declanșează OnPlayerKeyStateChange (sus/jos/stânga/dreapta). | Name | Descriere | | -------- | ------------------------------------------------------------------------------------------------ | | playerid | ID-ul jucătorului care a apăsat sau a eliberat o tastă. | | newkeys | O hartă (mască de biți) a cheilor deținute în prezent - [vezi aici](../resources/keys) | | oldkeys | O hartă (mască de biți) a cheilor deținute înainte de modificarea curentă - [vezi aici](../resources/keys). | ## Returnări - This callback does not handle returns. - It is always called first in gamemode. ## Note :::info This callback can also be called by NPC. ::: :::tip Directional keys do not trigger OnPlayerKeyStateChange (up/down/left/right).<br/>They can only be detected with [GetPlayerKeys](../functions/GetPlayerKeys) (in [OnPlayerUpdate](../callbacks/OnPlayerUpdate) or a timer). ::: ## Funcții similare #test - [GetPlayerKeys](../functions/GetPlayerKeys): Verificați ce taste ține un jucător. ## Informații suplimentare ### Introducere Acest callback este apelat ori de câte ori un jucător apasă sau eliberează una dintre tastele acceptate (consultați [Taste](../resources/keys)).<br/>Tastele care sunt acceptate nu sunt taste reale de la tastatură, ci funcția mapată in San Andreas, aceasta înseamnă că, de exemplu, nu puteți detecta când cineva apasă pe <strong>bara de spațiu</strong>, dar puteți detecta când apăsă tasta de sprint (care poate fi sau nu atribuită barei de spațiu ( este implicit)). ### Parametrii The parameters to this function are a list of all keys currently being held down and all the keys held down a moment ago. The callback is called when a key state changes (that is, when a key is either pressed or released) and passes the states or all keys before and after this change. This information can be used to see exactly what happened but the variables can not be used directly in the same way as parameters to other functions. To reduce the number of variables only a single BIT is used to represent a key, this means that one variable may contain multiple keys at once and simply comparing values will not always work. ### Cum să NU să verifici o cheie Să presupunem că doriți să detectați când un jucător apasă butonul FIRE, codul evident ar fi: ```c if (newkeys == KEY_FIRE) ``` Acest cod poate funcționa chiar și în testarea dvs., dar este greșit și testarea dvs. este insuficientă. Încercați să vă ghemuiți și să apăsați focul - codul dvs. nu va mai funcționa instantaneu. De ce? Deoarece „newkeys” nu mai este același lucru cu „KEY_FIRE”, este același cu „KEY_FIRE” COMBINAT CU „KEY_CROUCH”. ### Cum se verifică o cheie Deci, dacă variabila poate conține mai multe chei simultan, cum verifici doar una singură? Răspunsul este un pic de mascare. Fiecare tastă are propriul bit în variabilă (unele taste au același bit, dar sunt taste onfoot/incar, deci nu pot fi apăsate niciodată în același timp) și trebuie să verificați doar acel singur bit: ```c if (newkeys & KEY_FIRE) ``` Rețineți că singurul <strong>&</strong> este corect - acesta este un ȘI pe biți, nu un ȘI logic, așa cum se numesc cele două ampersand. Acum, dacă testați acest cod, va funcționa indiferent dacă sunteți ghemuit sau în picioare când apăsați tasta de declanșare. Cu toate acestea, există încă o mică problemă - se va declanșa atâta timp cât țineți cheia. OnPlayerKeyStateChange este apelat de fiecare dată când o tastă se schimbă și acel cod este adevărat ori de câte ori tasta de declanșare este apăsată. Dacă apăsați foc, codul se va declanșa, dacă acea tastă este apăsată și apăsați ghemuit - acel cod se va declanșa din nou deoarece o tastă (ghemuit) s-a schimbat și focul este încă ținut apăsat Cum detectăm când o tastă este apăsată pentru prima dată, dar nu se declanșează din nou când este încă apăsată și se schimbă o altă cheie? ### Cum să verificați dacă o tastă a fost apăsată Aici intervine "oldkeys". Pentru a verifica dacă o tastă tocmai a fost apăsată, trebuie să verificați mai întâi dacă este setată în „tastele noi” - adică este ținută apăsată, apoi verificați că NU este în „tastele vechi” - adică este tocmai a fost ținut apăsat. Următorul cod face acest lucru: ```c if ((newkeys & KEY_FIRE) && !(oldkeys & KEY_FIRE)) ``` Acest lucru va fi adevărat NUMAI atunci când tasta FIRE este apăsată pentru prima dată, nu când este apăsată și se schimbă o altă tastă. ### Cum să verificați dacă o cheie este eliberată Exact același principiu ca mai sus, dar invers: ```c if ((oldkeys & KEY_FIRE) && !(newkeys & KEY_FIRE)) ``` ### Cum se verifică mai multe chei Dacă doriți să verificați dacă jucătorii ȚINȚI se ghemuiesc și trag, atunci următorul cod va funcționa bine: ```c if ((newkeys & KEY_FIRE) && (newkeys & KEY_CROUCH)) ``` Cu toate acestea, dacă doriți să detectați când aceștia apăsați ÎNTÂI PRIME și vă ghemuiți, următorul cod NU VA funcționa. Va funcționa dacă reușesc să apese cele două taste exact în același timp, dar dacă sunt fracționat (cu mult mai puțin de jumătate de secundă), nu va: ```c if ((newkeys & KEY_FIRE) && !(oldkeys & KEY_FIRE) && (newkeys & KEY_CROUCH) && !(oldkeys & KEY_CROUCH)) ``` De ce nu? Deoarece OnPlayerKeyStateChange este apelat de fiecare dată când se schimbă o singură cheie. Așa că ei apasă „KEY_FIRE” - OnPlayerKeyStateChange este apelat cu „KEY_FIRE” în „newkeys” și nu în „oldkeys”, apoi apăsă „KEY_CROUCH” - OnPlayerKeyStateChange este apelat cu „KEY_CROUCH” și „KEY_FIRE” în „newkeys”, dar „ KEY_FIRE" este acum și în „oldkeys”, deoarece a fost deja apăsat, așa că „!(oldkeys & KEY_FIRE)” va eșua. Din fericire, soluția este foarte simplă (de fapt, mai simplă decât codul original): ```c if ((newkeys & (KEY_FIRE | KEY_CROUCH)) == (KEY_FIRE | KEY_CROUCH) && (oldkeys & (KEY_FIRE | KEY_CROUCH)) != (KEY_FIRE | KEY_CROUCH)) ``` Acest lucru poate părea complicat, dar verifică dacă ambele chei sunt setate în „newkeys” și că ambele chei nu au fost setate în „oldkeys”, dacă una dintre ele a fost setată în „oldkeys”, asta nu contează, deoarece nu ambele. au fost. Toate aceste lucruri pot fi simplificate foarte mult cu definiții. ## Simplificare ### Detectarea menținerii unei chei Definiți: ```c // HOLDING(keys) #define HOLDING(%0) \ ((newkeys & (%0)) == (%0)) ``` Ținând apăsată o cheie: ```c if (HOLDING( KEY_FIRE )) ``` Ținând apăsată mai multe chei: ```c if (HOLDING( KEY_FIRE | KEY_CROUCH )) ``` ### Detectare prima apăsare a unei taste Definiți: ```c // PRESSED(keys) #define PRESSED(%0) \ (((newkeys & (%0)) == (%0)) && ((oldkeys & (%0)) != (%0))) ``` Apăsată o tastă: ```c if (PRESSED( KEY_FIRE )) ``` Apăsate mai multe taste: ```c if (PRESSED( KEY_FIRE | KEY_CROUCH )) ``` ### Detectează dacă un jucător apasă o tastă în prezent Definiți: ```c // PRESSING(keyVariable, keys) #define PRESSING(%0,%1) \ (%0 & (%1)) ``` Ținând apăsată o cheie: ```c if (PRESSING( newkeys, KEY_FIRE )) ``` Ținând apăsată mai multe chei: ```c if (PRESSING( newkeys, KEY_FIRE | KEY_CROUCH )) ``` ### Detectarea eliberării unei chei Definiți: ```c // RELEASED(keys) #define RELEASED(%0) \ (((newkeys & (%0)) != (%0)) && ((oldkeys & (%0)) == (%0))) ``` S-a eliberat o cheie: ```c if (RELEASED( KEY_FIRE )) ``` S-au eliberat mai multe chei: ```c if (RELEASED( KEY_FIRE | KEY_CROUCH )) ``` ## Exemple ### Atașați NOS când jucătorul apasă clic ```c public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if (PRESSED(KEY_FIRE)) { if (IsPlayerInAnyVehicle(playerid)) { AddVehicleComponent(GetPlayerVehicleID(playerid), 1010); } } return 1; } ``` ### Super saritura ```c public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if (PRESSED(KEY_JUMP)) { new Float:x, Float:y, Float:z; GetPlayerPos(playerid, x, y, z); SetPlayerPos(playerid, x, y, z + 10.0); } return 1; } ``` ### Modul God în timp ce țineți apăsat ```c new Float:gPlayerHealth[MAX_PLAYERS]; #if !defined INFINITY #define INFINITY (Float:0x7F800000) #endif public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if (PRESSED(KEY_ACTION)) { // Tocmai au apăsat tasta de acțiune, salvează-le // sănătate veche pentru refacere GetPlayerHealth(playerid, gPlayerHealth[playerid]); SetPlayerHealth(playerid, INFINITY); } else if (RELEASED(KEY_ACTION)) { // Au lăsat doar acțiunea - restaurați // vechea lor sănătate din nou. SetPlayerHealth(playerid, gPlayerHealth[playerid]); } return 1; } ``` ### Explicație Nu trebuie să vă faceți griji despre CUM se face, doar că este. HOLDING detectează dacă aceștia apasă o tastă (sau taste), indiferent dacă au apăsat-o înainte, PRESSED detectează dacă doar au apăsat tastele și RELEASED detectează dacă tocmai au eliberat o tastă(e). Cu toate acestea, dacă doriți să aflați mai multe - citiți mai departe. Motivul pentru care trebuie să faceți acest lucru, nu doar folosind & sau ==, este să detectați exact tastele pe care le doriți, ignorând altele care pot fi sau nu apăsate. În binar KEY_SPRINT este: ``` 0b00001000 ``` și KEY_JUMP este: ``` 0b00100000 ``` astfel, OR-ul în cheile dorite (le-am putea adăuga și în acest exemplu, dar nu este întotdeauna cazul) dă: ``` 0b00101000 ``` Dacă am folosit doar & și s-a apelat OnPlayerKeyStateChange pentru un jucător care apasă pe salt, am găsit următorul cod: ``` newkeys = 0b00100000 wanted = 0b00101000 ANDed = 0b00100000 ``` AND-ul celor două numere nu este 0, deci rezultatul verificării este adevărat, ceea ce nu este ceea ce ne dorim. Dacă am folosi doar == cele două numere nu sunt în mod clar aceleași, astfel verificarea ar eșua, ceea ce ne dorim. Dacă jucătorul apăsa salt, sprint și ghemuit, am obține următorul cod: ``` newkeys = 0b00101010 wanted = 0b00101000 ANDed = 0b00101000 ``` Versiunea AND este aceeași cu cheile necesare și, de asemenea, nu 0, astfel încât va da răspunsul corect, totuși cele două numere originale nu sunt aceleași, așa că == va eșua. În ambele exemple, unul dintre cei doi a dat răspunsul corect și unul a dat răspunsul greșit. Dacă îl comparăm pe primul folosind & și == obținem: ``` newkeys = 0b00100000 wanted = 0b00101000 ANDed = 0b00100000 ``` Evident, dorit și AND nu sunt aceleași, așa că verificarea eșuează, ceea ce este corect. Pentru al doilea exemplu: ``` newkeys = 0b00101010 wanted = 0b00101000 ANDed = 0b00101000 ``` Wanted și AND sunt aceleași, așa că compararea lor ca fiind egală va avea ca rezultat un rezultat adevărat, care din nou este corect. Deci, folosind această metodă, putem verifica cu exactitate dacă anumite taste sunt apăsate ignorând toate celelalte taste care pot fi sau nu apăsate. verificarea tastelor vechi folosește doar != în loc de == pentru a se asigura că tastele necesare nu au fost apăsate anterior, așa că știm că una dintre ele tocmai a fost apăsată.
openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerKeyStateChange.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerKeyStateChange.md", "repo_id": "openmultiplayer", "token_count": 5277 }
396
--- title: OnPlayerUpdate description: Acest callback este apelat de fiecare dată când un client/jucător actualizează serverul cu starea lor. tags: ["player"] --- ## Descriere Acest callback este apelat de fiecare dată când un client/jucător actualizează serverul cu starea lor. Este adesea folosit pentru a crea apeluri personalizate pentru actualizările clientului care nu sunt urmărite activ de server, cum ar fi actualizările de sănătate sau armuri sau jucătorii care schimbă arme. | Name | Descriere | | -------- | ------------------------------------------ | | playerid | ID-ul jucătorului care trimite un pachet de actualizare. | ## Returnări 0 - Actualizarea de la acest player nu va fi replicată altor clienți. 1 - Indică faptul că această actualizare poate fi procesată normal și trimisă altor jucători. Este întotdeauna numit primul în filterscript-uri. ## Exemple ```c public OnPlayerUpdate(playerid) { nou iCurWeap = GetPlayerWeapon(playerid); // Returnează arma curentă a jucătorului if (iCurWeap != GetPVarInt(playerid, "iCurrentWeapon")) // Dacă a schimbat armele de la ultima actualizare { // Să apelăm un apel invers numit OnPlayerChangeWeapon OnPlayerChangeWeapon(playerid, GetPVarInt(playerid, "iCurrentWeapon"), iCurWeap); SetPVarInt(playerid, "iCurrentWeapon", iCurWeap);//Actualizează variabila armă } return 1; // Trimite această actualizare altor jucători. } stock OnPlayerChangeWeapon(playerid, oldweapon, newweapon) { new s[128], oWeapon[24], nWeapon[24]; GetWeaponName(oldweapon, oWeapon, sizeof(oWeapon)); GetWeaponName(newweapon, nWeapon, sizeof(nWeapon)); format(s, sizeof(s), "Ai schimbat arma din %s în %s!", oWeapon, nWeapon); SendClientMessage(playerid, 0xFFFFFFFF, s); } public OnPlayerUpdate(playerid) { nou Float:fHealth; GetPlayerHealth(playerid, fHealth); if (fHealth != GetPVarFloat(playerid, "faPlayerHealth")) { // Sănătatea jucătorului s-a schimbat de la ultima actualizare -> server, așa că, evident, acesta este lucrul actualizat. // Să facem verificări suplimentare să vedem dacă și-a pierdut sau a câștigat sănătatea, trișare anti-sănătate? ;) if (fHealth > GetPVarFloat(playerid, "faPlayerHealth")) { /* A căpătat sănătate! Înșelăciune? Scrie-ți propriile scripturi aici pentru a-ți da seama cum este un jucător a castigat sanatate! */ } else { /* A pierdut sănătatea! */ } SetPVarFloat(playerid, "faPlayerHealth", fHealth); } } ``` ## Note <TipNPCCallbacks /> :::warning Acest callback este apelat, în medie, de 30 de ori pe secundă, per jucător; folosește-l doar atunci când știi la ce este destinat (sau mai important pentru ce NU este destinat). Frecvența cu care acest apel invers este apelat pentru fiecare jucător variază, în funcție de ceea ce face jucătorul. Conducerea sau fotografierea va declanșa mult mai multe actualizări decât la ralanti. ::: ## Funcții similare
openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerUpdate.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerUpdate.md", "repo_id": "openmultiplayer", "token_count": 1383 }
397
--- title: AddCharModel description: Adaugă un nou model de caractere personalizat pentru descărcare. tags: [] --- <VersionWarn version='SA-MP 0.3.DL R1' /> ## Descriere Adaugă un nou model de caractere personalizat pentru descărcare. Fișierele model vor fi stocate în documentele playerului \ GTA San Andreas User Files \ SAMP \ cache sub folderul Server IP și Port într-un nume de fișier CRC. | Nume | Descriere | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | baseid | ID-ul modelului de bază de bază de utilizat (comportamentul caracterului și caracterul original de utilizat atunci când descărcarea eșuează) | | newid | Noul ID al modelului skin a variat între 20000 și 30000 (10000 sloturi) pentru a fi utilizat ulterior cu SetPlayerSkin | | dffname | Numele fișierului de coliziune a modelului .dff situat în dosarul serverului de modele în mod implicit (setare artpath). | | txdname | Numele fișierului de textură model .txd situat în dosarul serverului modele în mod implicit (setare artpath). | ## Se intoarce 1: Funcția executată cu succes. 0: Funcția nu a putut fi executată. ## Exemple ```c public OnGameModeInit() { AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd"); AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd"); return 1; } ``` ```c AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd"); AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd"); ``` ## Note :::tip useartwork trebuie activat mai întâi în setările serverului pentru ca acest lucru să funcționeze ::: :::warning În prezent, nu există restricții cu privire la momentul în care puteți apela această funcție, dar rețineți că, dacă nu le apelați în OnFilterScriptInit / OnGameModeInit, aveți riscul ca unii jucători, care sunt deja pe server, să nu fi descărcat modelele. ::: ## Funcții relative - [SetPlayerSkin](SetPlayerSkin.md): Setează skinul unui jucător.
openmultiplayer/web/docs/translations/ro/scripting/functions/AddCharModel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/functions/AddCharModel.md", "repo_id": "openmultiplayer", "token_count": 1013 }
398
--- title: "Scripting: Taguri" description: Un ghid pentru taguri --- ## Introducere O etichetă este un prefix la o variabilă care îi spune compilatorului să trateze variabila special în anumite circumstanțe. De exemplu, puteți utiliza etichete pentru a defini unde o variabilă poate și nu poate fi utilizată, sau un mod special de a adăuga două variabile împreună. Există două tipuri de etichete - etichete puternice (începând cu o literă majusculă) și etichete slabe (începând cu o literă mică), în cea mai mare parte sunt aceleași, însă în anumite circumstanțe etichetele slabe pot fi transformate în etichete fără compilatorul, adică nu veți primi un avertisment, de cele mai multe ori cu etichete slabe și tot timpul cu etichete puternice, schimbarea implicită a etichetei va avea ca rezultat un avertisment pentru a vă spune că datele sunt probabil utilizate greșit. Un exemplu foarte simplu este următorul: ```c new File:myfile = fopen("file.txt", io_read); myFile += 4; ``` Funcția `fopen` va returna o valoare cu o etichetă de tip`Fișier:`, nu există nicio problemă pe acea linie, deoarece valoarea returnată este stocată într-o variabilă, de asemenea, cu o etichetă `Fișier:`(rețineți că la fel și). Cu toate acestea, pe următoarea linie, valoarea `4` este adăugată la mânerul fișierului. "4" nu are etichetă (este de fapt tipul de etichetă `_:` dar variabilele, valorile și funcțiile fără etichetă sunt setate automat la asta și nu trebuie să vă faceți griji în mod normal) și fișierul meu are o etichetă `Fișier :`, evident, nimic și ceva nu pot fi la fel, așa că compilatorul va emite un avertisment, acest lucru este bun, deoarece un handle pentru un fișier nu are sens din punctul de vedere al valorii sale reale și, prin urmare, modificarea acestuia va distruge doar handle-ul și înseamnă fișierul nu poate fi închis deoarece nu mai există un handle valid cu care să treceți și să închideți fișierul. ### Tag-uri puternice După cum sa menționat mai sus, o etichetă puternică este orice etichetă care începe cu o literă mare. Exemple de acestea în SA: MP includ: ```c Float: File: Text: ``` Acestea nu pot fi amestecate cu alte tipuri de variabile și vor emite întotdeauna un avertisment atunci când încercați să faceți acest lucru: ```c new Float:myFloat, File:myFile, myBlank; myFile = fopen("file.txt", io_read); // File: = File:, no warning myFloat = myFile; // Float: = File:, "tag mismatch" warning myFloat = 4; // Float: = _: (none), "tag mismatch" warning myBlank = myFloat; // _: (none) = Float:, "tag mismatch" warning ``` ### Tag-uri slabe O etichetă slabă se comportă în mare parte la fel ca o etichetă puternică, totuși compilatorul nu va emite un avertisment atunci când destinația este lipsită de etichete și sursa este o etichetă slabă. De exemplu, comparați următoarele coduri de etichete puternice și slabe, primul cu eticheta puternică va da un avertisment, al doilea cu eticheta slabă nu: ```c new Strong:myStrong, weak:myWeak, myNone; myNone = myStrong; // Warning myNone = myWeak; // No warning ``` Cu toate acestea, inversul nu este adevărat: ```c myWeak = myNone; // Warning ``` Acest lucru este valabil și în cazul funcțiilor, apelarea unei funcții cu un parametru fără etichetă, trecerea unei variabile slabe etichetate nu va da un avertisment: ```c new weak:myWeak; MyFunction(myWeak); MyFunction(myVar) { ... } ``` Dar apelarea unei funcții cu un parametru marcat (slab sau puternic), trecerea unui parametru neetichetat va da un avertisment. Exemple de etichete slabe în SA: MP sunt mai puțin cunoscute ca atare, deși sunt adesea utilizate și includ: ```c bool: filemode: floatround_method: ``` ## Folosire ### Declarare Declararea unei variabile cu o etichetă este foarte simplă, trebuie doar să scrieți eticheta, nu este necesar să definiți în prealabil o etichetă în orice mod, totuși acest lucru este posibil și are utilizările sale, așa cum va deveni evident mai târziu: ```c new Mytag:myVariable; ``` Declararea unei variabile cu una dintre etichetele existente vă va permite să utilizați acea variabilă cu funcțiile și operatorii deja scrise pentru acel tip de etichetă. ### Funcții Crearea unei funcții pentru preluarea sau returnarea unei etichete este foarte simplă, trebuie doar să prefixați partea relevantă cu tipul de etichetă dorit, de exemplu: ```c Float:GetValue(File:fHnd, const name[]) { ... } ``` Această funcție duce mânerul la un fișier și returnează o valoare float (probabil o valoare citită din fișier și care corespunde numelui valorii trecute în `nume []`). Această funcție ar folosi cel mai probabil funcția `floatstr`, care returnează și un Float: (așa cum vă puteți da seama uitându-vă la bara de stare a pawno când faceți clic pe funcția din lista de funcții din dreapta), după ce ați luat un șir. Implementarea acestei funcții nu este importantă, dar va converti șirul într-o valoare flotantă IEEE, care este apoi stocată ca o celulă (este de fapt strict stocată ca un număr întreg care are doar un model de biți identic cu numărul IEEE relevant ca PAWN este fără tip, dar asta este ceea ce etichetele sunt parțial acolo pentru a combate). ### Operatori Operatorii precum `+`, `==`, `>` etc pot fi supraîncărcați pentru diferite etichete, adică a face `+` pe două `Float: s` face ceva diferit de a o face pe două variabile neetichetate. Acest lucru este util în special în cazul variabilelor flotante, deoarece, așa cum am menționat, nu sunt într-adevăr flotante, sunt numere întregi cu un model de biți foarte specific, dacă operatorii nu ar fi supraîncărcați, operațiunile ar fi efectuate pur și simplu pe numerele întregi, care ar da un blestem au fost interpretate din nou ca un plutitor. Din acest motiv, eticheta Float: are supraîncărcate versiuni ale majorității operatorilor pentru a apela funcții speciale pentru a face calculele în server în loc de pion. Un operator este exact ca o funcție normală, dar în locul unui nume de funcție folosiți "operator(**simbol**)" unde (**simbol**) este operatorul pe care doriți să îl suprascrieți. Operatorii valabili sunt: ```c + - = ++ -- == * / != > < >= <= ! % ``` Lucruri precum `\`, `*`, `=` etc se fac automat. Lucruri precum `&` etc nu pot fi supraîncărcate. De asemenea, puteți supraîncărca un operator de mai multe ori cu diferite combinații de etichete. De exemplu: ```c stock Float:operator=(Mytag:oper) { return float(_:oper); } ``` Dacă adăugați acest lucru la cod și faceți: ```c new Float:myFloat, Mytag:myTag; myFloat = myTag; ``` Nu veți mai primi un avertisment de compilator așa cum ați avea înainte, deoarece operatorul `=` pentru cazul `Float: = Mytag:` este acum gestionat, astfel încât compilatorul să știe exact ce să facă. ### Suprascriere În exemplul de supraîncărcare de mai sus linia funcțională a fost: ```c return float(_:oper); ``` Acesta este un exemplu de suprascriere a etichetelor, `_:` din fața oper înseamnă că compilatorul ignoră practic faptul că oper are un tip de etichetă Mytag: și îl tratează ca tip de etichetă `_:` (adică fără tip de etichetă). Funcția `float ()` etichetează un număr normal, așa că trebuie trecut unul. În acest exemplu, se presupune că `Mytag` stochează un număr întreg obișnuit, dar suprascrierea trebuie tratată foarte atent, de exemplu, următoarele vor da rezultate foarte ciudate: ```c new Float:f1, Float:f2 = 4.0; f1 = float(_:f2); ``` Sensul ar dicta că `f1` va ajunge ca `4.0`, cu toate acestea nu va fi. După cum s-a menționat, f2 stochează o reprezentare a lui `4.0`, nu doar `4` așa cum ar face un întreg, aceasta înseamnă că valoarea reală a variabilei întrucât un număr întreg este un număr foarte impar. Astfel, dacă îi spuneți compilatorului să trateze variabila ca un întreg, va lua pur și simplu modelul de biți din variabilă ca valoare, nu va converti floatul într-un număr întreg, deci veți obține un număr aproape aleatoriu (de fapt nu este aleatoriu, deoarece există un model la punctele flotante IEEE, dar nu va fi nimic ca `4.0`).
openmultiplayer/web/docs/translations/ro/scripting/language/Tags.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/language/Tags.md", "repo_id": "openmultiplayer", "token_count": 3601 }
399
--- title: Statusurile armelor description: Constantele pentru statusurile armelor --- | ID | Definitie | Descriere | | --- | ------------------------ | --------------------------------------- | | -1 | WEAPONSTATE_UNKNOWN | Necunoscuta (Seteaza cand e in vehicul) | | 0 | WEAPONSTATE_NO_BULLETS | Arma nu mai are gloante ramase | | 1 | WEAPONSTATE_LAST_BULLET | Arma mai are decat un singur glont | | 2 | WEAPONSTATE_MORE_BULLETS | Arma are mai multe gloante | | 3 | WEAPONSTATE_RELOADING | Jucatorul isi reincarca arma | ## Functii relatate - [GetPlayerWeaponState](../functions/GetPlayerWeaponState): Verifica starea armei unui jucator
openmultiplayer/web/docs/translations/ro/scripting/resources/weaponstate.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/scripting/resources/weaponstate.md", "repo_id": "openmultiplayer", "token_count": 332 }
400
--- title: Manipularea șirurilor description: Tutorial prietenos pentru începători despre orice manipulare a șirurilor. --- ## Introducere ### Descrierea tutorialului Bună ziua tuturor, cu siguranță este o noapte liniștită drăguță sau cel puțin este la compoziția acestui tutorial. Deci, hei, ce zici de etichetare atât pentru a îmbogăți și / sau pentru a se implica în principalul obiectiv al acestui articol, acesta este și așa cum sugerează titlul, urmând să se concentreze pe `_Manipularea șirurilor_` în pawn, vom trece prin intermediarul absolut lucruri pe care toată lumea ar trebui să le cunoască pentru un fel de sfaturi avansate, inteligente și eficiente. ### Ce este formatarea șirurilor? În general, formatarea unui text este acțiunea de a-l manipula pentru a-i îmbunătăți vizual lizibilitatea, fie că se modifică familia fontului, culoarea, greutatea și așa mai departe. Șirurile fiind o serie de caractere (_alfabete, numere, simboluri_), pe care nu le-am numi în mod specific un text în sine, dar sunt denumite ca atare atunci când sunt afișate, pot fi procesate cu aceeași abordare, dar, din păcate, interpretarea SA-MP de pion nu permite mult (_încă? Poate niciodată_), în general, schimbarea culorii este atât cât putem, da, puteți schimba / personaliza fontul, dar este doar client, și da, [GTA San Andreas ](https://www.rockstargames.com/sanandreas/) (_jocul părinte_) oferă unele fonturi suplimentare, dar asta funcționează numai pe [textdraws](../scripting/resources/textdraws) și [gametext](../scripting/functions/GameTextForPlayer), acest lucru provoacă limitări în ceea ce privește prezentarea textului, dar hei, a trecut peste un deceniu acum și am supraviețuit bine. ### Declarație șir Așa cum am spus mai înainte, șirurile sunt practic matrici de caractere, deci sunt utilizate în același mod în care sunt matricele și, așa cum am crea o matrice, am face-o pentru șirurile care urmează acest format; `string_name [string_size]`. :::info **string_name**: numele matricei de caractere (_de exemplu șir, str, mesaj, text ... etc., atâta timp cât este un nume de variabilă valid (începe cu un caracter sau un subliniat)_). **string_size**: caracterele maxime pe care le-ar avea acest șir. ::: ```cpp // declaring a string of 5 characters new str_1[5]; // declaring a string of 100 characters new str_2[100]; ``` De asemenea, puteți predefini valorile constante, astfel încât să le puteți folosi de mai multe ori ca dimensiuni de șir. ```cpp // declaring a constant #define STRING_SIZE 20 // declaring a string with the size of STRING_SIZE's value new str_3[STRING_SIZE]; ``` :::note La timpul compilării, compilatorul va înlocui toate aparițiile lui `STRING_SIZE` cu valoarea `20`, această metodă economisind timp și este mai ușor de citit în majoritatea cazurilor, rețineți că valoarea pe care o atribuiți constantei `STRING_SIZE` trebuie fie un număr întreg sau altfel va da o eroare de compilare. ::: În plus față de constantele predefinite, puteți efectua operațiuni de bază, operatorul modulo (`%`) va da totuși erori de compilare dacă este utilizat, puteți totuși să scăpați de calculele diviziunii (`/`), dar rețineți, împărțind la `0 `va declanșa erori, bonusul aici este că toate rezultatele plutitoare vor fi rotunjite automat pentru dvs. ```cpp // declaring a constant #define STRING_SIZE 26 // declaring strins with the use of the STRING_SIZE constant and some calculations new str_4[STRING_SIZE + 4], str_5[STRING_SIZE - 6], str_6[STRING_SIZE * 2], str_7[9 / 3]; ``` Teoretic, puteți crea tablouri oarecum ridicol de mari, dar SA-MP pune puține restricții asupra lungimii șirurilor cu care puteți lucra, în funcție de ceea ce lucrați, limitează numărul de caractere pe care le puteți reda în mod normal. #### Limite de lungime SA-MP limitează caracterele care pot fi stocate într-un singur șir și împiedică scripterii să meargă peste bord cu lucrul cu textul, din fericire, nu este atât de rău pe cât ar părea, lista de mai jos descompune unele dintre aceste limite; | | | | | ------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---- | | **Text input** | Textul introdus în chat. | 128 | | **Text output** | Text care se afișează pe ecranul clientului. | 144 | | **Name** | Pseudonimul jucătorului / numele de utilizator. | 24 | | **Textdraw string** | Destul de auto-explicativ. | 1024 | | **Dialog info** | Textul afișat pe toate casetele de dialog de tipul `DIALOG_STYLE_MSGBOX`,`DIALOG_STYLE_INPUT` și `DIALOG_STYLE_PASSWORD`. | 4096 | | **Dialog caption** | Legenda / titlul din partea de sus a dialogului. | 64 | | **Dialog input** | Caseta de introducere de pe „DIALOG_STYLE_INPUT” și „DIALOG_STYLE_PASSWORD”. | 128 | | **Dialog columnt** | Caracterele din fiecare coloană din „DIALOG_STYLE_TABLIST_HEADER” și „DIALOG_STYLE_TABLIST”. | 128 | | **Dialog row** | Caracterele din fiecare coloană din "DIALOG_STYLE_TABLIST_HEADER", "DIALOG_STYLE_TABLIST" și "DIALOG_STYLE_LIST". | 256 | | **Chat bubble** | Balonul de chat care se afișează deasupra etichetei de nume a jucătorului. | 144 | | **Menu title** | Antetul meniului nativ GTA San Andreas (cel mai utilizat pentru magazine\_). | 31 | | **Menu item** | Meniul nativ GTA San Andreas (_ cel mai utilizat pentru magazine_) element / rând. | 31 | Dacă cumva aceste limite au fost depășite, s-ar putea să apară puține inconveniente, acesta poate chiar să blocheze / înghețe serverul în unele cazuri (de exemplu, șiruri lungi de desen text), în alte cazuri, textul s-ar trunchia ca titlul meniului (_daca ajunge la 32 de caractere, se trunchiază la 30_) și articole. Pe lângă limitele stricte puse pe șiruri, există multe altele referitoare la diferite lucruri, puteți vizualiza lista completă [aici](../scripting/resources/limits). #### Atribuirea valorilor Atribuirea valorilor șirurilor se poate face prin mai multe metode, unii le atribuie la crearea lor, altele după, există oameni care folosesc bucle, alte funcții folosesc și da, există care fac acest proces manual, slot cu slot, nu există într-un mod exact corect sau greșit pentru a face acest lucru, unele metode sunt adesea mai eficiente în câteva cazuri decât altele nu sunt, la sfârșitul zilei, tot ce contează este performanța, optimizarea și lizibilitatea. În majoritatea cazurilor, doriți să dați o valoare implicită șirului la crearea acestuia, puteți parcurge acest lucru pur și simplu după cum urmează; ```cpp new message_1[6] = "Hello", message_2[] = "This is another message"; ``` Asigurați-vă că dimensiunea șirului este mai mare decât numărul de caractere pentru care le-ați atribuit, având o dimensiune a șirului mai mică sau egală cu aceasta, va declanșa erori de compilare, lăsând golul de dimensiune dintre cele două paranteze goale (ca în exemplul `mesaj_2`) , va da automat matricei dimensiunea textului pe care l-ați atribuit plus `1`, în acest caz,`23 + 1 = 24`, de ce? Rezervă un slot pentru caracterul nul (_aka the null-terminator_), mai multe despre asta mai târziu, cuvântul `_Bună ziua_` are 5 caractere, deci, pentru a-l stoca pe un șir, ar trebui să aibă 6 celule, 5 celule pentru numărul de caractere al cuvântului și unul pentru **caracterul nul**. Să aruncăm o privire la efectuarea manuală a aceluiași proces slot cu slot, mai întâi, definim o nouă matrice, puteți determina dimensiunea acesteia sau lăsați-o goală pentru ca compilatorul să se umple, ambele ar funcționa foarte bine, vom completa matricea cu caractere pentru a crea șirul `_Bună_`. ```cpp // Including the string' size on its declaration, or it won't work otherwise new message_3[6]; message_3[0] = 'H'; message_3[1] = 'e'; message_3[2] = 'l'; message_3[3] = 'l'; message_3[4] = 'o'; message_3[5] = '\0'; ``` Acolo, am atribuit fiecărui slot din matricea `message_3` un caracter, acest lucru nu va funcționa dacă ar trebui să declarați un sting fără dimensiune definitivă, rețineți că pentru a reprezenta un singur caracter, ar trebui să fie scris între două ghilimele (""), de asemenea, observați cum am început cu slotul 0 și este firesc, având în vedere cum am subliniat modul în care un șir este o matrice de caractere, adică primul slot este întotdeauna 0, iar ultimul este dimensiunea sa minus 1 (_caracterul nul nu contează_), care în acest caz este 4, numărând de la 0 la 4, ceea ce îl face 5 caractere, al șaselea fiind terminatorul nul, mai multe despre asta vor veni mai târziu. De asemenea, puteți atribui numere de șiruri care vor fi vizualizate ca **ASCII** (_un sistem care reprezintă caracterele numeric, acoperă 128 de caractere cuprinse între 0 și 127, mai multe despre asta [aici](https://en.wikipedia.org/wiki/ASCII) _) cod pentru un caracter, același mesaj „_Bună ziua” poate fi atribuit folosind codul \_ASCII_ astfel; ```cpp new message_4[6]; message_4[0] = 72; // ASCII representation of capitalized h, `H` message_4[1] = 101; // ASCII representation of `e` message_4[2] = 108; // ASCII representation of `l` message_4[3] = 108; // ASCII representation of `l` message_4[4] = 111; // ASCII representation of `o` message_4[5] = 0; // ASCII representation of the null terminator ``` Și da, puteți efectua operațiuni numerice cu aceste coduri la fel ca și cu numerele normale, la urma urmei, mașina vede caracterele ca doar simple numere. ```cpp new message_5[1]; message_5[0] = 65 + 1; ``` Dacă ar fi să afișezi `message_5 [0]`, ai primi **B**, ciudat nu? Ei bine, nu, nu chiar, puteți efectua alte operații de bază (_subtractie, multiplicare, divizare și chiar modulul_), numerele flotante vor fi rotunjite automat pentru dvs., să vedem cum funcționează acest lucru. Aveți `65 + 1`, care returnează `66`, verificând tabelul _ASCII_, veți găsi că `66` este reprezentarea numerică a caracterului `_B_` (_capitalized_). Deci, fragmentul de mai sus este în esență același cu a face: `message_5 [0] = 'B'`; Pentru referință, utilizați [acest tabel ASCII](http://www.asciitable.com/). De asemenea, puteți efectua aceeași operație între mai multe caractere sau o combinație a acestora, a acestora și a numerelor, iată câteva exemple; ```cpp new message_6[3]; message_6[0] = 'B' - 1; // Which is 66 - 1, returns 65, the numeric representation of `A` message_6[1] = 'z' - '&'; // Which is 122 - 38, returns 84, the numeric representation of `T` message_6[2] = '0' + '1'; // Which is 48 + 49, returns the numeric representation of `a`, note that '0' and '1' are not the numbers 0 and 1, but rather characters ``` Uneori ar putea deveni confuz dacă nu ați știut niciodată despre sistemul _ASCII_, este nevoie doar de o anumită practică, deoarece înțelegerea modului în care funcționează este foarte utilă. Codul _ASCII_ nu este exclusiv numai pentru numerele zecimale, puteți utiliza, de asemenea, numere hexazecimale sau binare în același mod. ```cpp new numString[4]; numString[0] = 0x50; // The decimal number 80 in hexadecimal, capitalized p, `P` numString[1] = 0b1000001; // The decimal number 65 in binary, capitalized a, `A` numString[2] = 0b1010111; // The decimal number 87 in binary, capitalized w, `W` numString[3] = 0x4E; // The decimal number 78 in hexadecimal, capitalized n, `N` ``` Now let’s see something else, assigning values through loops, it’s literally the same as filling an array through loops, you can use all sorts of looping methods as well, goes as follow; ```cpp // Let's fill this string with capitalized alphabets new message_7[26]; // The for loop for (new i = 0; i < 26; i++) message_7[i] = 'A' + i; // The while loop while (i++ < 'Z') message_7[i - 'A'] = i; // The do-while loop new j = 'A'; do { message_7[j - 'A'] = j; } while (j++ < 'Z'); // You can even use goto to simulate a loop, but it's not recommended. ``` Toate cele trei vor genera același șir exact, _ABCDEFGHIJKLMNOPQRSTUVWXYZ_. Dacă vi s-a părut confuz buclele de mai sus, vă recomandăm să aruncați o privire mai profundă asupra modului în care funcționează buclele, mai multe despre asta puteți găsi [aici](../scripting/language/ControlStructures#loops) și [aici](https://wiki.alliedmods.net/Pawn_Tutorial#Looping). Observați cum am folosit caractere în unele condiții logice, cum ar fi `j ++ <` Z `care se traduce cu ușurință în `j ++ <90“, iarăși, caracterele sunt tratate ca numere, nu vă simțiți ciudat, sunteți binevenit să verificați _ASCII_ masa oricând doriți. Spuneți, doriți să umpleți un șir cu un număr de caractere specifice, (de exemplu, `_AAAAAA_“, `_TTTTTT_“, `_vvvvvv_“, `_666_` (_no, nu este o coincidență_)), ideea tipică care ar putea trece cel mai mult dintre scriptori, o codifică greu, dar ce zici de șirurile lungi, bine, ce zici de utilizarea unei bucle, este bine și asta, dar dacă ți-aș spune că există un mod și mai eficient, la fel cum ai umple o matrice cu aceeași valoare, ați face același lucru pentru șiruri. ```cpp new message_8[100] = {'J', ...}; ``` Codul de mai sus declară un șir nou numit `mesaj_8` cu 100 de celule (_variază de la 0 la 99_) și dă fiecărui slot valoarea `J`, care desigur poate fi folosită atât ca caracter **J**, fie numărul **74** conform sistemului _ASCII_. Un alt lucru pe care îl puteți face cu acest lucru este umplerea șirului cu caractere pe care valorile lor se bazează pe intervale, a se vedea exemplul alfabetelor cu majuscule de la _A_ la _Z_ de mai sus? Să creăm același șir folosind această metodă. ```cpp new message_9[26] = {'A', 'B', ...}; ``` Cât de ușor este asta ?! acest lucru este atât mai optimizat, cât și mai ușor de citit și oferă aceleași rezultate ca cele 3 exemple realizate folosind metodele de buclă de mai sus, deci cum funcționează exact? Ei bine, am dat șirului valori inițiale, `'A'` și `'B'`, care sunt respectiv _65_ și _66_, compilatorul calculează intervalul dintre cele două valori, care în acest caz este _1_ și finalizează completarea celule goale cu valori bazate pe acel interval până când umple întreaga matrice, puteți pune oricâte valori inițiale doriți, dar va lua în considerare doar intervalul dintre ultimele două valori și va funcționa pe baza acestuia, rețineți că valorile inițiale sunt tratate ca cod _ASCII_, deci încercarea de a genera intervale numerice folosind această metodă pe un șir va duce la ceva incomod, să spunem că ați declarat un șir aleatoriu ca acesta; ```cpp new rand_str[5] = {'1', '5', ...}; ``` În mod ideal, acest lucru ar trebui să aibă ieșire **151520** (_mai exact `1 5 15 20`_), dar în schimb, să producă; ** 159 = A **, care este de fapt rezultatul corect, de ce? Pentru că nu uitați, acesta este codul _ASCII_, `_1_` este _49_ și `_5_` este _53_, intervalul dintre cele două este _4 (53 - 49) _, șirul acceptă 5 caractere, am ocupat deja două celule când am inclus catalogul inițial , deci asta face 3 celule goale rămase care trebuie umplute respectând intervalul de 4, deci așa merge **[49 | 53 | 57 | 61 | 65]**, să înlocuim fiecare valoare numerică cu potrivirea codului său _ASCII_. **[`1` | `5` | `9` | '=' | `A`]**, are mai mult sens, nu ?! ## Terminatorul nul M-am referit la acest lucru în primele secțiuni ale acestui tutorial, sper că nu a fost atât de confuz la început, dar chiar dacă a fost, să eliminăm deja confuzia, nu vă faceți griji, nu este nimic greu sau chiar asta avansează, doar un fapt de bază pe care ar trebui să-l cunoașteți, îl voi menține cât mai scurt posibil, dar dacă doriți o viziune mai profundă despre acest lucru, puteți vizita [acest articol](https://en.wikipedia.org/wiki/Null_character). Deci, terminatorul nul (_aka caracterul nul_), este un caracter prezent pe toate șirurile, rolul său este de a indica faptul că un șir s-a încheiat, îl puteți gândi ca pe un semn de punct (.) Orice vine după acest caracter este nu este contabilizat și complet ignorat. Nu îl puteți tasta folosind tastatura, dar puteți face referire la valoarea acesteia în timp ce codificați, însă este prezent pe tabelul _ASCII_, denumit _NUL_, reprezentat de numărul 0. În _pawn_, îl puteți tasta ca valoare numerică sau ca caracter `_\0_`. Backslashul acționează ca un personaj care scapă, este acolo pentru a spune mașinii că acel caracter este caracterul nul cu valoarea 0 și **NU** caracterul `0` care are valoarea `48`. Există un simbol folosit în _pawn_, ** EOS **, prescurtarea pentru **E** nd **O**f**S** tring, este o macro predefinită pentru terminatorul nul, puteți seta terminatorul nul în multe feluri diferite; ```cpp message_9[0] = 0; message_9[0] = '\0'; message_9[0] = 0b; // The decimal number 0 in binary message_9[0] = 0x00; // The decimal number 0 in hexadecimal message_9[0] = _:0.0; // The floating number 0.0, we have to prefix it with the detag '_' to avoid compilation errors message_9[0] = false; message_9[0] = EOS; ``` După cum am spus mai devreme în tutorial, puteți ignora atribuirea caracterului nul, dar este întotdeauna acolo la celulele goale, atunci când declarați un șir nou, toate celulele sale sunt ocupate automat de terminatorul nul, deci, de exemplu, dacă merg înainte și declarați acest șir `text[3]`, tuturor celulelor sale li se atribuie valoarea `0` în mod implicit, iată o simplă reprezentare vizuală a conținutului șirului; | | | | | | ---------- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | | ASCII code | 0 | 0 | 0 | | Characters | '\0' | '\0' | '\0' | Iată un alt exemplu de șir preumplut. ```cpp new text_1[8] = "Hello"; ``` Iată conținutul șirului pe celulă; | | | | | | | | | | | ---------- | --- | --- | --- | --- | --- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | ASCII code | 72 | 101 | 108 | 108 | 111 | 0 | 0 | 0 | | Characters | 'H' | 'e' | 'l' | 'l' | 'o' | '\0' | '\0' | '\0' | Dacă, de exemplu, ați dorit să ștergeți conținutul acestui șir, puteți face acest lucru pur și simplu folosind unul dintre cele trei exemple de mai jos; ```cpp text_1[0] = 0; text_1[0] = EOS; text_1[0] = '\0'; ``` Trecerea șirului printr-o scanare cu raze X va imprima următoarele; | | | | | | | | | | | ---------- | ---- | --- | --- | --- | --- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | ASCII code | 0 | 101 | 108 | 108 | 111 | 0 | 0 | 0 | | Characters | '\0' | 'e' | 'l' | 'l' | 'o' | '\0' | '\0' | '\0' | Dacă încercați să scoateți acest șir, totul dincolo de numărul de slot 0 va fi ignorat și, astfel, etichetat ca un șir gol, chiar și funcția `strlen` va returna 0, deoarece depinde de plasarea caracterului nul pentru a recupera lungimea șirului . ## Funcții de manipulare a șirurilor Când vine vorba de lucrul cu mai multe bucăți de text, _pawn_ te-a acoperit, oferă câteva funcții de bază care fac treaba în mod eficient, nu este nevoie să-ți creezi propriile atunci când ai suport nativ care asigură viteză și optimizare. Acestea sunt câteva funcții acceptate nativ (_preluate din string.inc_); ```cpp native strlen(const string[]); native strpack(dest[], const source[], maxlength=sizeof dest); native strunpack(dest[], const source[], maxlength=sizeof dest); native strcat(dest[], const source[], maxlength=sizeof dest); native strmid(dest[], const source[], start, end, maxlength=sizeof dest); native bool: strins(string[], const substr[], pos, maxlength=sizeof string); native bool: strdel(string[], start, end); native strcmp(const string1[], const string2[], bool:ignorecase=false, length=cellmax); native strfind(const string[], const sub[], bool:ignorecase=false, pos=0); native strval(const string[]); native valstr(dest[], value, bool:pack=false); native bool: ispacked(const string[]); native uudecode(dest[], const source[], maxlength=sizeof dest); native uuencode(dest[], const source[], numbytes, maxlength=sizeof dest); native memcpy(dest[], const source[], index=0, numbytes, maxlength=sizeof dest); ``` Vom arunca o privire mai atentă asupra câtorva dintre ele, cele sunt mai des utilizate. - Funcția `strlen` (aceasta și `sizeof` sunt lucruri complet diferite), care ia un șir ca parametru, returnează lungimea șirului respectiv (numărul de caractere pe care le are), dar acordați atenție, deoarece acest lucru este puțin dificil despre modul în care funcționează, am spus-o mai devreme în tutorial, această funcție depinde de poziția caracterului nul pentru a determina lungimea șirului, deci orice alt caracter nevalid care vine după nu va fi numărat, ca imediat ce este atins primul caracter nul, funcția returnează numărul de celule de la început la acel caracter nul. - `strcat` concatenează șiruri între ele, are nevoie de 3 parametri. ```cpp new str_dest[12] = "Hello", str_source[7] = " World"; strcat(str_dest,str_source); ``` Dacă ar fi să ieșim `str_dest`, va apărea ** Hello World **, cele două șiruri au fost adăugate una la cealaltă, iar rezultatul a fost stocat în` str_dest`, _`Hello` + `World` =` Hello World`_, observați cum am inclus acel spațiu în cel de-al doilea șir, da, spațiile sunt caracter în sine, conform tabelului _ASCII_, valoarea lor este`32`, dacă nu am adăuga spațiul, șirul rezultat ar fi fost **Salut Lume**. - Funcția `strval` va converti un șir într-un număr, de exemplu, următorul șir, ` `2017` `va fi convertit în numărul` 2017`, aceasta funcționează pe numere semnate și nesemnate, dacă șirul nu are caractere numerice , funcția va întoarce `0`, la fel se întâmplă dacă șirul are un caracter numeric, dar începe cu cele non-numerice, dacă un șir începe cu caractere numerice, dar include și caractere non-numerice, caracterele numerice vor fi totuși recuperate și convertite, iată câteva cazuri de utilizare; ```cpp strval("2018"); // Returns `2018`. strval("-56"); // Returns `-56`. strval("17.39"); // Returns `17`, the floating number 17.39 was auto floored for us. strval("no number here"); // Returns `0`. strval("6 starts"); // Returns `6`. strval("here we go, 2018"); // Returns `0`. strval("2017 ended, welcome 2018"); // Returns `2017`. ``` :::tip Există multe biblioteci realizate de comunitate pe care le puteți descărca și care au legătură cu manipularea șirurilor, nu mă pot gândi la o includere mai bună decât [strlib](https://github.com/oscar-broman/strlib). ::: ### Funcția format Aceasta este probabil cea mai utilizată funcție legată de șiruri din comunitate, foarte simplă și ușor de utilizat, tot ceea ce face, este formatarea unor bucăți de text și fragmentarea lor, poate fi implementată în diverse situații, cum ar fi legarea variabilelor și șirurilor împreună, încorporarea culorilor, adăugarea de pauze de linie ... etc. ```cpp format(output[], len, const format[], {Float, _}:...) ``` Funcția de format ia ca parametri matricea de ieșire, dimensiunea sa (_numărul de celule_), șirul de formatare (_aceasta poate fi pre-stocată pe o altă matrice sau poate fi atribuită direct din interiorul funcției_) și, în final, câțiva parametri opționali, aceștia pot să fie variabile din diferite tipuri. Să folosim această funcție pentru a atribui o valoare unui șir gol. ```cpp new formatMsg[6]; format(formatMsg, 6, "Hello"); ``` Ieșirea lui `formatMsg` este **Hello**, rețineți că acesta este un mod prost de a atribui valori șirurilor de caractere, mai ales datorită vitezei sale, există metode mai bune pentru a face acest lucru, am discutat deja unele dintre ele mai devreme etapele acestui tutorial. Nu uitați să puneți întotdeauna dimensiunea corectă a matricei, în caz contrar, va funcționa în continuare, dar oferă un comportament nedorit, funcția de formatare va revărsa dimensiunea matricei și aveți încredere în mine, nu doriți să se întâmple asta, dacă nu doriți să vă deranjați să puneți dimensiunea corectă a șirului de fiecare dată când doriți să lucrați cu această funcție, puteți utiliza pur și simplu funcția `sizeof` (_nu este o funcție în sine, ci mai degrabă o directivă de compilare_), am văzut mai devreme o funcție numită `strlen` care returnează numărul de caractere pe care le are un șir (_exclusiv și oprindu-se la caracterul nul_), dar acesta returnează dimensiunea tabloului, cu alte cuvinte, numărul de celule pe care acesta le are, fie ele completat cu un caracter valid sau nu, în acest caz, 6. ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), "Hello"); ``` Textul trebuie să fie întotdeauna inclus între ghilimele duble, cu toate acestea, există un mod neobișnuit de a introduce text, care este rar folosit, folosește simbolul `#“ și funcționează după cum urmează: ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), #Hello); ``` Acceptă spații, caractere scăpate și puteți folosi chiar și combinația atât a ghilimelelor duble cât și a semnului numeric; ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), "Hello "#World); ``` Codul de mai sus va introduce **Hello World**, această metodă de introducere a șirurilor este mai cunoscută a fi utilizată cu constante predefinite. Să aruncăm o privire la acest exemplu de utilizare a două constante diferite predefinite, una fiind un număr întreg `2017`, cealaltă fiind un șir`2018`. ```cpp #define THIS_YEAR 2018 // Thisconstant has an integer as its value #define NEW_YEAR "2019" // This constant has a string as its value new formatMsg[23]; format(formatMsg, sizeof(formatMsg), "This is "#THIS_YEAR", not"NEW_YEAR); ``` Aceasta va ieși ** Acesta este 2018, nu 2019 **, motivul pentru care am subliniat că cele două constante sunt de tipuri diferite este utilizarea semnului numeric `#`, dacă valoarea este **NU** un șir, atunci trebuie să-l prefixați cu semnul numeric `# THIS_YEAR`, astfel încât va fi tratat ca` `2018` `, altfel veți primi câteva erori de compilare, deoarece pentru o valoare șir, puteți alege să includeți sau să omiteți numărul semn, deoarece va funcționa în ambele sensuri (`NEW_YEAR` este același cu `# NEW_YEAR`). Puteți utiliza acest lucru doar pentru a prelua valori din constante predefinite, nu va funcționa cu variabile obișnuite sau cu matrice / șiruri, deoarece tratarea acestora se poate face folosind substituenți, mai multe despre aceasta mai târziu. De asemenea, puteți alinia câte citate duble doriți una lângă alta, deși nu are sens, deoarece este mai firesc să scrieți doar o propoziție într-o singură pereche de citate duble, iată un exemplu al aceleiași propoziții scris în ambele concepte; ```cpp new formatMsg[29]; // One single pair of double quotations format(formatMsg, sizeof(formatMsg), "This is reality...or is it?!"); // Multiple pairs of double quotations format(formatMsg, sizeof(formatMsg), "This is reality""...""or is it?!"); ``` Ambele vor scoate aceeași propoziție, **Aceasta este realitatea ... sau este?!**. ## Sfaturi de optimizare Acum, că am văzut câteva lucruri de bază despre declararea șirurilor, manipularea ... etc. unii dintre noi ar face salt la practică fără a respecta unele linii directoare generale urmate de comunitate, dacă doar mai multor oameni le-ar păsa de lizibilitate, optimizare și performanță, lumea ar fi fost un loc mai bun. un cod care se compilează bine, nu înseamnă că funcționează bine, majoritatea erorilor provin din acele lucruri mici pe care le-am trecut cu vederea sau le-am creat în așa fel încât să nu interacționeze prietenos cu alte sisteme. un cod bine scris va supraviețui calvarului timpului, cum? Puteți reveni oricând la acesta și depanați, remediați, revizuiți-l cu ușurință, optimizarea va reflecta și rezultatul asupra performanței, încercați întotdeauna să obțineți cele mai bune utilaje și codul optimizat este calea de urmat. Primul lucru care trebuie adus în discuție și care mă declanșează personal este să văd cum se creează șiruri mari atunci când nu sunt folosite aproape jumătate din celulele declarate, declară doar șirurile de dimensiunea pe care o vei folosi, celulele suplimentare vor fi doar sarcini mai multă memorie, să aruncăm o privire la un mod presupus neoptimizat de a declara un șir. ```cpp new badString[100]; badString ="Hello :)"; ``` Am declarat un șir cu _100 celule_, _1 celulă_ ocupă _4 octeți_, hai să facem câteva matematici de bază, _100 \ \* 4 = 400_ octeți, adică aproximativ 0,0004 megabyte*, nimic pentru standardele de astăzi știu, dar se presupune că pe un script imens , evident, va trebui să utilizați mai multe șiruri, \_60*, _70_, naiba _100_ mai multe șiruri? (_posibil mai mult_), acele numere minuscule se vor aduna unul pe celălalt rezultând un număr mult mai mare și vă vor provoca probleme serioase mai târziu și credeți-mă când vă spun că șirul pe care l-am declarat nu se apropie la fel de prost în comparație cu cei care au o dimensiune de cinci ori mai mare sau mai mare. Ceea ce am întâlnit mai mult, ceva care este stereotip tip vag, este utilizarea misterioasă dimensiune a șirului -256-, tocmai de ce oamenii? De ce? Rețineți limitele pe care le pune SA-MP atunci când se ocupă de șiruri, unde intră în joc șirul _256-lung_? Ce ai de gând să faci cu un șir atât de lung (_exceptând formatarea unui dialog / șir de desen text_)? Intrarea maximă a șirului are o lungime de _128_ caractere, adică jumătate din dimensiune, \_512 octeți* tocmai s-au pierdut, spuneți ce? Ați intenționat să-l utilizați pentru ieșire, nu pentru intrare? Este încă mult prea mare, șirurile de ieșire nu trebuie să treacă \_144* caractere, vedeți unde mă duc? Să încercăm să vedem cum ne-am corecta greșeala, avem această propoziție, `Șir bun`, conține _11_ caractere (_spaiul este numărat și ca caracter_) + _1_ pentru terminatorul nul (_trebuie să am întotdeauna acest tip în mind_), ceea ce îl face _12_ caractere în total. ```cpp new goodString[12]; goodString="Good string"; ``` Vedeți cum am păstrat memoria? Doar **48** octeți și nici o greutate suplimentară care ar provoca probleme mai târziu, se simte mult mai bine. Dar, dacă ți-aș spune, poți obține un cod și mai optimizat, așa este, ai auzit vreodată de **șiruri împachetate**? Un șir este de obicei format din mai multe celule și, așa cum am spus mai devreme, fiecare celulă reprezintă 4 octeți, deci șirurile sunt alcătuite din mai multe seturi de _4 octeți_. Un singur caracter ocupă 1 octet și fiecare celulă permite stocarea unui singur caracter, ceea ce înseamnă că pe fiecare celulă se pierd 3 octeți, ```cpp new upkString[5]; upkString = "pawn"; ``` Șirul de mai sus ocupă 5 celule (_adică aproximativ 20 de octeți_), poate fi restrâns la doar 8 octeți, doar 2 celule. ```cpp new pkString_1[5 char]; pkString_1 = !"pawn"; // or pkString_1 = !#pawn; ``` Așa funcționează pur și simplu, declarați un șir cu dimensiunea pe care ar lua-o în mod normal (_numărând terminatorul nul, desigur_), apoi îl completați cu cuvântul cheie `char`, fiecare caracter va fi stocat în octeți, mai degrabă decât în celule, adică fiecare celulă va avea 4 caractere stocate, amintiți-vă că atunci când atribuiți valori șirurilor împachetate, prefixați-le cu un semn de exclamare `!`, totuși, acest lucru nu se aplică pentru un singur caracter. Aceasta este o reprezentare vizuală aproximativă a conținutului `upkString`; | | | | | | | | ---------- | -------------------- | -------------------- | -------------------- | -------------------- | ----------------- | | Cell | 0 | 1 | 2 | 3 | 4 | | Bytes | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | | Characters | \0 . \0 . \0 . **p** | \0 . \0 . \0 . **a** | \0 . \0 . \0 . **w** | \0 . \0 . \0 . **n** | \0 . \0 . \0 . \0 | Și așa ar fi `pkString_1` în al doilea exemplu; | | | | | ---------- | ----------------------------- | ----------------- | | Cell | 0 | 1 | | Bytes | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | | Characters | **p** . **a** . **w** . **n** | \0 . \0 . \0 . \0 | De asemenea, puteți accesa indexatorii unui șir împachetat, după cum urmează; ```cpp new pkString_2[5 char]; pkString_2{0} = 'p'; pkString_2{1} = 97; // ASCII code for the character `a`. pkString_2{2} = 0b1110111; // The decimal number 199 in binary, translates to the character `w`. pkString_2{3} = 0x6E; // The decimal number 110 in hexadecimal, translates to the character `n`. pkString_2{4} = EOS; // EOS (End Of String), has the value of 0, which is the ASCII code for \0 (NUL), the null character. ``` Rezultatul va fi același cu `pkString_1` în acest caz, după cum puteți vedea, codul _ASCII_ este încă luat în considerare, luați notă că, atunci când accesați indexatori pe șiruri împachetate, folosim ** paranteze bucle ** în loc de **paranteze**. Asta înseamnă că indexăm octeții înșiși și nu celulele. :::info În ciuda eficienței lor în păstrarea memoriei, implementarea SA-MP a pionului nu acceptă 100% șiruri împachetate, dar le puteți folosi în continuare în șiruri / matrice utilizate rar. ::: ## Ieșire text #### Consolă ##### `print` Următoarea funcție este probabil cea mai de bază funcție nu numai în pion, ci și în multe alte limbaje de programare, ci acceptă pur și simplu un parametru și îl afișează pe consolă. ```cpp print("Hello world"); ``` ``` Hello world ``` Puteți trece, de asemenea, șiruri predeclarate sau constante predefinite, precum și fuzionarea mai multor dintre ele sau puteți utiliza și semnul numeric `#`, la fel cum am făcut-o cu funcția de formatare, dar rețineți că nu include mai multe parametri, putem trece doar un singur parametru. ```cpp #define HAPPY_STRING "I'm happy today" // String constant. #define NEW_YEAR 2019 // Integer constant. new stylishMsg[12] = "I'm stylish"; print(HAPPY_STRING); print(stylishMsg); print(#2019 is beyond the horizon); print("I'm excited for "#NEW_YEAR); print("What ""about"" you""?"); ``` ``` I'm happy today I'm stylish 2019 is beyond the horizon I'm excited for 2019 What about you? ``` Observați cum am folosit simbolul numeric aici la fel cum am făcut-o cu funcția format, dacă valoarea este un număr întreg, îl prefixați cu `#`, deci este tratat ca un șir. Rețineți, de asemenea, că funcția `print` acceptă șiruri împachetate, totuși acceptă doar variabile de tip șir (_matrice de caractere_), trecând tot ceea ce nu este o matrice, un șir (_fie între ghilimele duble sau prefixat cu simbolul numărului_) dați erori de compilare, astfel încât să faceți oricare dintre următoarele nu va funcționa; ```cpp // Case 1 new _charA = 'A'; print(_charA); // Case 2 new _charB = 66; print(_charB); // Case 3 print('A'); // Case 4 print(66); ``` Să vedem cum putem remedia problema; ```cpp // Case 1 new _charA[2] = "A"; print(_charA); ``` Schimbăm ghilimela simplă la ghilimele duble și dăm matricei două celule, una cu caracterul A și a doua pentru terminatorul nul, deoarece orice dintre ghilimele duble este un șir, ieșirea este **A**. ```cpp // Case 2 new _charB[2] = 66; print(_charB); ``` Schimbăm `_charB` într-o matrice cu o singură celulă și setăm celula etichetată cu 0 la valoarea` 66`, care se traduce în ** B ** conform tabelului _ASCII_, ieșirea este **B**, noi păstrați o celulă suplimentară pentru terminatorul nul (_cât este, așa că nu mai este amuzant?_). ```cpp // Case 3 print("A"); ``` Nu se pot spune multe, tot ce a fost nevoie a fost trecerea de la ghilimele simple la o pereche de ghilimele duble. În ceea ce privește al patrulea caz, nu putem face prea multe în timp ce lucrăm cu funcția `print`, dar poate fi rezolvată pur și simplu folosind o altă funcție similară, numită ... ##### `printf` Pe scurt pentru `_print formatat_`, pot pur și simplu pune, aceasta este o versiune mai diversă a funcției anterioare `print`, mai exact, este ca o combinație între funcția `format` și funcția `print`, ceea ce înseamnă că imprimă caractere pe consola serverului, dar cu avantajul formatării textului de ieșire. Spre deosebire de `print`,` printf` acceptă mai mulți parametri și, de asemenea, cu diferite tipuri, totuși nu acceptă șiruri împachetate, pentru a extinde funcționalitatea sa, folosim aceste secvențe numite `_format specifiers_`, mai multe despre ele ulterior, oferind orice altceva decât ** 1024 ** caractere va <u> bloca serverul </u>, așa că luați note despre asta. ```cpp #define RANDOM_STRING "Vsauce" #define RANDOM_NUMBER 2018 printf("Hey "RANDOM_STRING", Micheal here! #"#RANDOM_NUMBER); ``` Observați cum am asemănat cu funcțiile `print` și `format`, am imbricat acele șiruri într-una singură, care produce următoarele; ``` Hey Vsauce, Micheal here! #2018 ``` Funcția `printf`, așa cum am spus mai devreme, strălucește atunci când se utilizează **specificatorii de format**, este ceea ce o distinge și o diferențiază, puteți atașa cât de multe variabile doriți și puteți scoate șiruri simple și complexe cu ușurință, vom avea o privire mult mai profundă atunci când vom fi prezentați acestor specificați mai târziu. #### Mesaje client În afară de celelalte texte despre păpuși pe care le puteți imprima pe consola serverului, care sunt utilizate în principal pentru depanare, există mesaje care sunt tipărite pe ecranul clientului, în secțiunea de chat, și acestea pot fi formatate în același mod, dar și ele susține încorporarea culorilor, ceea ce face o prezentare minunată pentru texte (_dacă este utilizat corect, desigur_). Rețineți că restricțiile SA-MP privind afișarea șirurilor se aplică și pentru acest tip de mesaje, fiind la fel ca și cele anterioare, limitate la mai puțin de _144 caractere_, sau altfel mesajul nu va fi trimis, uneori chiar vor bloca unele comenzi . Există două funcții care imprimă nativ text pe ecranul clientului, singura diferență dintre ele este scoopul, primul ia trei parametri, ID-ul jucătorului pe care doriți să imprimați textul pe ecranul acestuia, culoarea textului și textul în sine. ```cpp SendClientMessage(playerid, color, const message[]) ``` Spuneți, doriți să trimiteți un text jucătorului al cărui ID este 1, spunându-i `Bună ziua!`; ```cpp SendClientMessage(1, -1, "Hello there!"); ``` Simplu, exact așa, jucătorului cu ID-ul 1 i se va trimite un text spunând **Bună ziua!**, `-1` este parametrul de culoare, în acest caz, este culoarea **alb**, mai multe despre culori mai târziu. Evident, puteți trece și o serie de caractere, șiruri formatate ... etc. Și așa cum am văzut cu alte funcții, puteți utiliza semnul numeric `#`. ```cpp #define STRING_MSG "today" new mornMsg[] = "Hello!"; SendClientMessage(0, -1, mornMsg); SendClientMessage(0, -1, "How are you ",STRING_MSG#?); ``` După cum puteți vedea în exemplul de mai sus, acest lucru va trimite jucătorului cu id-ul _0_ două mesaje colorate în alb, primele mesaje vor spune `_Bună ziua!_`, Iar al doilea va spune, `_Cum ești astăzi?_`, destul de similar cu modul în care funcționează alte funcții. Rețineți că numerele întregi constante predefinite trebuie să fie prefixate cu simbolul "#". ```cpp #define NMB_MSG 3 SendClientMessage(3, -1, "It's "#NMB_MSG" PM"); ``` Destul de auto-explicativ, textul va fi trimis jucătorului cu id-ul _3_, colorat în alb, spunând `_It’s 3 PM_`. Acum, că știi cum să trimiți cuiva un mesaj, poți folosi aceeași abordare pentru a trimite același mesaj tuturor, jocul copiilor într-adevăr, poți pur și simplu pune funcția într-o buclă care trece prin toți jucătorii conectați și să riști să-ți arăți codul în public și numiți-o zi, dar hei, există deja o funcție nativă care face exact același lucru, se aplică aceleași reguli, singurul lucru care diferă între cele două este o ușoară modificare a sintaxei lor. ```cpp SendClientMessageToAll(color, const message[]); ``` destul de auto-explicativ, expus prin numele său, acum să trimitem tuturor de pe server un mesaj de salut. ```cpp SendClientMessageToAll(-1, "Hello everyone!"); ``` La fel, poți să te joci cu el la fel ca și celălalt frate al său, două jucării de la același brand, într-adevăr, încearcă să nu depășești limita de 144 de caractere. #### Textdraws Una dintre cele mai puternice funcționalități ale SA-MP, doar dezlănțuie-ți imaginația, textele sunt practic forme grafice / texte / sprite / modele de previzualizare ... etc. care pot fi afișate pe ecranele clienților, acestea fac ca interfața de utilizare să fie mai activă și mai interactivă (_ într-o măsură_). Dar hei, există și aici limitări, de exemplu, nu puteți afișa un șir care are mai mult de 1024 de caractere, ca să fiu sincer, este mai mult decât suficient. Nimic special nu se poate spune aici, chiar și cu funcționalitatea lor largă, șirurile care pot fi afișate sunt slabe la formatare, nu puteți face cât de mult ați putea cu alte funcții de ieșire, se simte puțin îngust când vine vorba de acest lucru, dar cu siguranță compensează lipsa de formatare cu alte lucruri interesante, mai multe despre textdraws [aici](../scripting/resources/textdraws). #### Dialoguri Dialogurile pot fi considerate ca `_căsuțe de mesaje_`, ele, desigur, vin în diferite tipuri, acceptă câteva intrări diferite și, mai important, acceptă toate tipurile de formatare pe care le face un șir normal, cu care le face mult mai ușor de utilizat decât textdraw . Există și limitări care le privesc, cum ar fi dimensiunile șirurilor și posibilitatea de a le afișa numai sincron pe ecranul clientului, SA-MP oferă doar o funcție nativă pentru tratarea dialogurilor și, sincer, aceasta ar fi una dintre ultimele dvs. preocupări, deoarece Funcția singuratică își face treaba și o face eficient, mai multe despre dialoguri [aici](../scripting/functions/ShowPlayerDialog). ### Interpretarea culorii #### Mesaje și dialoguri ale clienților ##### RGBA **RGBA** (_ scurt pentru roșu verde albastru alfa_), este o utilizare simplă a modelului ** RGB ** cu un canal suplimentar, canalul alfa, practic, o formă de reprezentare digitală a culorilor, prin amestecarea variațiilor de roșu, verde, albastru și alfa (_opacity_), mai multe despre asta [aici](https://en.wikipedia.org/wiki/RGBA_color_space). În implementarea SA-MP cu pawn, folosim numere hexazecimale pentru a reprezenta aceste spații de culoare, roșu, verde, albastru și alfa sunt notate cu câte 2 biți fiecare, rezultând un număr hexazecimal lung de 8 biți, de exemplu; (_FF0000FF = red_), (_00FF00FF = green_), (_0000FFFF = blue_), (_000000FF = black_), (_FFFFFFFF = white_), iată o vizualizare mai clară despre această notație: > <span style={{ color: 'red' }}>FF</span><span style={{ color: 'green' }}>FF</span><span style={{ color: 'blue' }}>FF</span><span style={{ color: 'grey' }}>FF</span> O mulțime de limbaje de programare / scriptare prefixează numere hexazecimale cu semnul numeric `#`, totuși, în pion, le prefixăm cu `0x`, deci următorul număr hexazecimal _8060C1FF_, devine _0x8060C1FF_. Putem, desigur, să folosim numere zecimale pentru a reprezenta culorile, dar este mult mai clar să folosim notația hexazecimală, deoarece este mai ușor de citit între cele două, să vedem următorul exemplu; ```cpp // Representing the color white with decimal numbers SendClientMessageToAll(-1, "Hello everyone!"); // Representing the color white with hexadecimal numbers SendClientMessageToAll(0xFFFFFFFF, "Hello everyone!"); // A client message colored in white will be sent to everybody ``` Rețineți că atribuirea tuturor biților la aceeași valoare va avea ca rezultat variații ale nuanțelor de gri (_no pun intention_), atribuirea canalului alfa la 0 va face textul invizibil. :::tip Este posibil să formatați texte cu multicolor simultan, dar pentru aceasta, încorporăm notația **RGB** mai simplă. ::: ##### RGB Aceasta este exact ca spațiile de culoare **RGBA**, dar fără canal alfa, doar un amestec de roșu, verde și albastru, notat ca un număr hexazecimal de 6 biți, în pion, această notație este folosită mai ales pentru a încorpora culorile în textele, pur și simplu înfășurați numărul hexazecimal de 6 biți între o pereche de paranteze bucle și sunteți pregătit să mergeți, de exemplu; (**{FF0000} = roșu**), (**{00FF00} =verde**), (**{0000FF} = albastru**), (**{000000} = negru**), (**{FFFFFF} = alb**), iată o vizualizare mai clară despre această notație: `{FFFFFF}`. Să vedem acest exemplu rapid aici; ```cpp SendClientMessageToAll(0x00FF00FF, "I'm green{000000}, and {FF0000}I'm red"); ``` Aceasta va trimite următorul mesaj tuturor (_și nu sunt italian_): > <span style={{color: '#00ff00ff'}}>Sunt verde</span><span style={{color: '#ffffff'}}>, si </span><span style={{color: '#ff0000'}}>Sunt rosu</span> Rețineți că notația hexazecimală nu face distincția între majuscule și minuscule, așa că tastarea `0xFFC0E1FF` este la fel ca tastarea` 0xfFC0e1Ff`, același lucru este valabil și pentru culorile încorporate, `{401C15}` este la fel ca `{401c15}`. Uneori, lucrul cu culori se poate dovedi a fi destul de greu, nu este atât de ușor să te plimbi amintindu-ți toate acele numere hexazecimale lungi, ca nici o afacere mare. poți folosi, poți pur și simplu să folosești Google `_color picker_` și să alegi între mii dintre ele, lasă-mă să fac asta dacă nu te deranjează, [iată un instrument simplu](https://www.webpagefx.com/web-design/color-picker/) pe care vă recomand să îl folosiți atunci când lucrați cu culori. Una dintre problemele pe care oamenii le găsesc este gestionarea fluxului lor de lucru, care, dacă este făcut corect, facilitează ritmul de lucru și face mai puțin dureros să lucrezi în jurul proiectelor tale, în timp ce instrumentele de selectare a culorilor sunt de mare ajutor, poți totuși să pierzi multe de timp care trece și se oprește de fiecare dată când trebuie să alegeți o culoare, frustrarea poate fi la fel de enervantă ca o pizza cu ananas, din fericire, puteți profita de constante predefinite și puteți defini cele mai utilizate culori pentru o utilizare ulterioară , iată un exemplu simplu; ```cpp #define COLOR_RED 0xFF0000FF #define COLOR_GREEN 0xFF0000FF #define COLOR_BLUE 0xFF0000FF SendClientMessageToAll(COLOR_RED, "I'm a red text"); SendClientMessageToAll(COLOR_GREEN, "I'm a green text"); SendClientMessageToAll(COLOR_BLUE, "I'm a blue text"); ``` Acesta din urmă poate fi realizat și pe culorile încorporate; ```cpp #define COL_RED "{FF0000}" #define COL_GREEN {FF0000} #define COL_BLUE "{FF0000}" SendClientMessageToAll(-1, ""COL_RED"I'm a red text"); SendClientMessageToAll(-1, "{"COL_GREEN}"I'm a green "COL_BLUE"and blue"); ShowPlayerDialog(playerid, 0, DIALOG_STYLE_MSGBOX, "Notice", "{"COL_GREEN"}Hello! "COL_RED"what's up?", "Close", ""); ``` La momentul compilării, toate constantele predefinite vor fi înlocuite cu valorile lor și, astfel, acest `COL_RED` sunt un text roșu`devine acest`{FF0000}`Sunt un text roșu`, observați cum am folosit două metoda pentru a predefini acele culori, `RRGGBB` și `{RRGGBB}`, intră în preferința personală, care metodă trebuie să treacă, personal, consider că definirea lor ca `RRGGBB` este foarte clar, deoarece sunt prezente utilizările parantezelor crețate, și astfel se face remarcabil faptul că încorporăm o culoare. Aceasta a fost abordarea generală a încorporării culorilor cu șiruri de dialog și mesaje client, este posibil să se utilizeze culori în text în mesajele clientului, dialoguri, etichete text 3D, texte materiale obiecte și plăcuțe de înmatriculare ale vehiculului, dar hei, SA-MP are și texdraws și funcționalități de jocuri, totuși acestea nu acceptă notația RGB și, prin urmare, adăugarea culorilor se face diferit. #### Textdraws și Gametexts așa cum s-a menționat mai sus, notația **RGB** nu este acceptată, dar din fericire, avem alte modalități de a rezolva această problemă, pentru textdraws, puteți utiliza funcția nativă [TextDrawColor](../scripting/functions/TextDrawColor) pentru schimbați culoarea textului de desen, dar același lucru cu textul de desenat ca spațiile de culoare ** RGBA ** sunt pentru mesajele și dialogurile clientului, acestea nu pot fi încorporate, pentru aceasta, folosim o combinație specială de caractere pentru a ne referi la culori și alte câteva simboluri , le puteți vedea [aici](../scripting/resources/gametextstyles). | | | | -------------- | ------ | | \~r\~ | Red | | \~g\~ | Green | | \~b\~ | Blue | | \~w\~ or \~s\~ | White | | \~p\~ | Purple | | \~l\~ | Black | | \~y\~ | Yellow | Deci, culorile de încorporare pot merge astfel: **\~w\~ Bună ziua acesta este \~b\~ albastru \~w\~ și acesta este \~ r\~ roșu** Puteți utiliza o altă combinație de caractere pentru a vă juca cu combinații de culori, **\~h\~**, face o anumită culoare mai deschisă, iată câteva exemple: | | | | ------------------------------ | ---------------- | | \~r\~\~h\~ | Roșu mai deschis | | \~r\~\~h\~\~h\~ | Roșu roz | | \~r\~\~h\~\~h~\~h\~ | Roșu-închis | | \~r\~\~h\~~h~~h~~h\~ | Roz roșu deschis | | \~r\~\~h\~\~h\~\~h\~\~h\~\~h\~ | Roz | | \~g\~\~h\~ | Verde deschis | Puteți găsi mai multe informații despre acest lucru [aici](../scripting/resources/colorslist). ### Caracterul de evadare #### Descriere Caracterul de evadare este un caracter în care, atunci când este prefixat la un anumit caracter sau număr, își creează propriul caracter constant, în majoritatea limbajelor de programare / scriptare, cum ar fi pionul, barul invers este folosit ca caracter de evacuare ("\"), o combinație a acestui și un alt caracter / număr va avea ca rezultat o [secvență de evadare](https://en.wikipedia.org/wiki/Escape_sequence) care are o anumită semnificație, puteți găsi mai multe despre caracterul de evadare [aici](https://en.wikipedia.org/wiki/Escape_character). #### Secvențe de evacuare Secvențele de evacuare facilitează exprimarea anumitor caractere în codul sursă al scriptului dvs., iată un tabel care conține secvențele de evadare utilizate în pawn: | | | | --------------------------------------------- | ------------ | | Bip sonor (pe mașini server) | `\a` or `\7` | | Backspace | `\b` | | Evadare | `\e` | | Formular de alimentare | `\f` | | Linie nouă | `\n` | | Retur transport | `\r` | | Filă orizontală | `\t` | | Fila verticală | `\v` | | Backslash | `\\` | | Citat unic | `\'` | | Citat dublu | `\"` | | Cod de caractere cu valori zecimale "ddd" | `\ddd;` | | Cod de caractere cu valori hexazecimale "hhh" | `\xhhh;` | Să ne uităm la fiecare dintre ei, la urma urmei, cel mai bun mod de a învăța acest gen de lucruri stă în practicarea lor. - ** Secvența de evacuare `Bip audibil` - `\a` ** Un semnal sonor sau un cod de sonerie (_uneori caracter de sonerie_) este un cod de control al dispozitivului trimis inițial pentru a suna un mic clopot electromecanic pe bifere și alte teleimprimante și tele-mașini de scris pentru a alerta operatorii de la celălalt capăt al liniei, adesea a unui mesaj primit. Utilizarea acestuia pe un computer va avea ca rezultat trimiterea unui sunet sonor / de notificare în fundal, acesta poate fi folosit în unele moduri creative, pentru a notifica și / sau avertiza utilizatorii cu privire la anumite activități, secvența de evadare care îl reprezintă este `\a` sau `\7` notat ca cod zecimal), declanșați editorul dvs. de pion și scrieți următorul cod; ```cpp print("\a"); ``` La executarea samp-server.exe, veți auzi un semnal sonor de notificare, puteți utiliza și codul zecimal; ```cpp print("This is a beep \7"); ``` - ** Secvența de evacuare `Backspace` -`\b` ** Această secvență de evadare este notată ca `\b`, pur și simplu mișcă cursorul înapoi, majoritatea oamenilor s-ar aștepta ca acesta să acționeze ca butonul de backspace de pe tastatura tipică, dar nu în totalitate, mișcă trăsura doar o poziție înapoi fără a șterge ceea ce este scris Acolo. Acesta nu are atât de multă utilizare în pion, cu excepția cazului în care ai fost suficient de deștept să scoți ceva util din el, iată cum funcționează. ```cpp print("Hello 2018"); ``` Aceasta va imprima ** Hello 2018 ** în consolă, cursorul rămâne pe poziția caracterului nul, mai clar, astfel: ``` Hello 2018 ^ ``` După cum puteți vedea, cursorul se oprește după ultimul caracter vizibil al șirului, ceea ce este normal, acum, să adăugăm o secvență de ieșire înapoi; ```cpp print("Hello 2018\b"); ``` Asta va avea ca rezultat; ``` Hello 2018 ^ ``` După cum puteți vedea, cursorul se află exact în poziția ultimului caracter vizibil al șirului, care este _8_, este același lucru cu comutarea în modul de inserare de pe tastatură, acum, să adăugăm ceva vrăjitorie la acest lucru. ```cpp print("Hello 2018\b9"); ``` Dacă ați ghicit bine, da, acest lucru va imprima **Bună ziua 2019**, deci, haideți să vedem cum funcționează acest lucru, mașina va procesa șirul caracter cu caracter, până când va ajunge la secvența de evacuare a backspace-ului, apoi va muta unul din cărucior poziția înapoi, care selectează orice caracter de acolo, în acest caz 8, apoi introduce 9 în locul său. ``` Hello 2019 ^ ``` Căruciorul se va deplasa înapoi atâta timp cât există o secvență de scăpare în spate în șir. ```cpp print("Hello 2018\b9\b\b\b"); ``` ``` Hello 2019 ^ ``` Cursorul se va opri în poziția primului caracter dacă cantitatea de secvență de evacuare a spațiului înapoi a depășit cea a numărului de caractere dintre poziția primului caracter (da, matricile încep de la 0, se îndreaptă spre [r/programmerhumor](https://www.reddit.com/r/ProgrammerHumor/) pentru câteva meme-uri bune) și poziția inițială a cursorului. ```cpp print("Hi\b\b\b\b\b\b\b\b\b\b\b\b\b\b"); ``` Va duce întotdeauna la acest lucru; ``` Hi ^ ``` - ** Secvența de evadare `Evacuare` - `\e` ** Cu valoarea hexazecimală de 1B în _ASCII_, este utilizată pentru coduri non-standard comune, să căutăm câteva limbaje de programare precum C, ca exemplu; o secvență precum `\ z` nu este o secvență de evadare validă conform standardului C. Standardul C necesită diagnosticarea unor astfel de secvențe de evadare nevalide (compilatorul trebuie să imprime un mesaj de eroare). Fără a aduce atingere acestui fapt, unii compilatori pot defini secvențe de evadare suplimentare, cu semantică definită de implementare. Un exemplu este secvența de evacuare `\ e`, reprezintă caracterul de evacuare. Cu toate acestea, nu a fost adăugat la repertoriul standard C, deoarece nu are un echivalent semnificativ în unele seturi de caractere. - ** Secvența de evacuare `Form feed` - `\ f` ** Feedul formular este un cod _ASCII_ care rupe paginile. Forțează imprimanta să scoată pagina curentă și să continue imprimarea în partea de sus a alteia. Adesea, va provoca, de asemenea, o întoarcere a căruciorului, acest lucru nu face nicio modificare vizibilă în consola de depanare a _SA-MP_. - ** Secvența de evadare `Linie nouă` - `\ n` ** Noua secvență de evacuare a liniei (denumită și sfârșit de linie, sfârșit de linie (_EOL_), avans de linie sau întrerupere de linie) este un cod _ASCII_ care este notat ca `/ n` cu valoarea zecimală 10, este ceva care este frecvent utilizat , editorii de text inserează acest caracter de fiecare dată când apăsăm butonul Enter de pe tastaturile noastre. Iată un mesaj simplu cu o întrerupere de linie: ```cpp print("Hello, this is line 1\nAnd this is line 2"); ``` Aceasta va genera pur și simplu: ``` Hello, this is line 1 And this is line 2 ``` Desigur, frânele cu mai multe linii sunt realizabile; ```cpp print("H\n\n\ne\n\n\nl\nl\n\no"); ``` ``` H e l l o ``` Acest lucru funcționează diferit la tratarea fișierelor, cu toate acestea, în funcție de sistemul de operare, cum ar fi, de exemplu, în Windows, o întrerupere de linie este de obicei un ** CR ** (_carriage return_) + ** LF ** (_line feed_), tu pot afla mai multe despre diferențe [aici](https://en.wikipedia.org/wiki/Newline). - ** Secvența de evacuare `Returnare transport` - `\ r` ** Returnarea transportului este un cod _ASCII_ care este adesea asociat cu fluxul de linie, dar poate servi ca lucru propriu de la sine, pur și simplu mută transportul la începutul liniei curente, echivalent cu un caz specific despre care am discutat folosind mai multe backspaces (`\b`) secvență de evacuare, să vedem următorul exemplu, fără a utiliza această secvență de evacuare, aceasta este ieșirea normală pe care am obține-o: ```cpp print("Hello"); ``` ``` Hello ^ ``` Săgeata reprezintă poziția cursorului, care este plasată după ultimul caracter vizibil al șirului, din nou, acesta este comportamentul normal așteptat, acum să adăugăm revenirea căruței în mix: ```cpp print("Hello\r"); ``` ``` Hello ^ ``` Cursorul este deplasat la începutul liniei, selectând primul caracter ** `H`**, inserând acum orice se va schimba **`H`** la orice introducem, apoi se mută la următorul caracter rămânând pe modul de inserare: ```cpp print("Hello\rBo"); ``` ``` Hello ^ ``` Așa cum am văzut în secțiunea de alimentare de linie, întreruperile de linie funcționează diferit în diferite sisteme de operare, ferestrele, de exemplu, utilizează o întoarcere de căruță urmată de o alimentare de linie pentru a efectua o întrerupere de linie, la fel ca mașinile de scris clasice. - ** Secvența de evadare `fila orizontală` - `\t`** Tabelarea este ceva pe care îl folosim în fiecare zi, de la indentarea textului / codului, până la afișarea tabelului, acea tastă de tabulator care se află chiar în partea tastaturii este într-adevăr o economie de timp, a fost o durere atât de mare și a consumat mult timp pentru a folosi în mod excesiv multe spații, dar acesta taie tortul cu ușurință, nu numai că este util în mod practic, este într-adevăr puternic prezent în domeniul programării, este notat ca `\t`, oamenii ar argumenta câte spații valorează o filă, majoritatea ar spune că merită 4 spații, dar există unii care spun că merită 8 spații, cineva creatură demonică ar prefera chiar spații decât filele, dar acesta este un alt discurs despre sine, să observăm acest exemplu simplu: ```cpp print("Hello\tWorld"); ``` ``` Hello World ``` Iată un altul cu mai multe tabulări: ```cpp print("Hello\t\t\t\t\tWorld"); ``` ``` Hello World ``` - ** Secvența de evadare `Tab vertical` - `\v` ** Pe vremea vechii mașini de scris, aceasta a avut o utilizare mai populară, a fost folosită pentru a trece la următoarea linie pe verticală, dar acum, acest lucru nu mai este cazul, nu are nicio utilizare vizibilă în zilele noastre și asta include imprimante și chiar și limbaje de programare, iar pionul nu face excepție. - **\_The `Backslash` escape sequence - `\*`** După cum am văzut, backslash-ul este considerat caracterul de evadare, așa că ori de câte ori programul îl observă, îl consideră un punct de plecare al unei secvențe de evadare, nu îl privește ca pe un personaj independent și, astfel, fie va da o eroare de compilare (_dacă nu a fost urmat de un caracter valid_), fie nu o va imprima, în cazul amanetului, compilatorul va ridica o eroare (_error 027: constantă de caracter nevalid_). Din fericire, putem rezolva această problemă scăpând de bară inversă, iar acest lucru se face prin prefixarea unei alte baruri inversă: ```cpp print("Hello \\ World"); ``` ``` Hello \ World ``` :::caution Avertisment Ieșirea nu va lua în considerare prima bară inversă și o va imprima pe cea de-a doua, deoarece prima scapă de a doua și păcălește programul pentru a-l vizualiza ca un caracter brut. O bară inversă poate scăpa doar de un caracter la rândul său, astfel încât să faceți următoarele va crește o eroare de compilare. ::: ```cpp print("Hello \\\ World"); ``` Gândiți-vă la asta ca la perechi de bare inversă, toată lumea scapă de cea de după și, prin urmare, ar trebui să conducă întotdeauna la un număr par de bare inversă; ```cpp print("Hello \\\\\\ \\ World"); ``` ``` Hello \\\ \ World ``` După cum ați observat cu siguranță, secvențele de evadare nu sunt niciodată tipărite, ele servesc doar ca instrucțiuni care exprimă anumite evenimente, dacă vrem să le forțăm să fie tipărite, putem scăpa de caracterul lor de evadare ("\"), atunci programul nu se va uita la le ca secvență de evadare: ```cpp print("This is the escape sequence responsible for tabulation: \\t"); ``` Prima bară inversă scapă de a doua, apoi se imprimă, apoi caracterul ** t** este lăsat singur și, astfel, este considerat ca un caracter independent: ``` Aceasta este secvența de evacuare responsabilă pentru tabulare: \t ``` - ** Secvența de evadare `Citat unic` - `\'`** Acest lucru este greu de prezentat atunci când scriu codul de amanet, eu însăși nu m-am găsit folosind acest lucru în nicio situație de codare, în alte limbi care tratează textul dintre ghilimelele unice ca un șir, folosesc foarte mult acest lucru pentru a limita confuzia care se întâmplă atunci când se cuibărește singur ghilimele între ele, într-adevăr nu face nicio diferență în pion, iată un exemplu simplu; ```cpp print("Single quote '"); // or print("Single quote \'"); ``` Oricum ar fi, ieșirea va fi aceeași: "" Citat unic: ' "" Singura utilizare la care mă pot gândi în legătură cu acest lucru este setarea unei variabile a caracterului `** '**`, așa că, evident, dacă faceți următoarele, veți provoca o eroare de compilare; ```cpp new chr = '''; ``` Pur și simplu pentru că compilatorul va considera prima pereche de ghilimele simple ca o singură entitate, iar a doua ca o secvență de ghilimele nedeschise, așa că, pentru a remedia acest lucru, va trebui să scăpăm de cel din mijloc; ```cpp new chr = ''\'; ``` - ** Secvența de evadare `Citat dublu` - `\"`** Spre deosebire de ghilimele unice, acesta poate provoca probleme atunci când vine vorba de cuibărirea lor împreună, pion tratează orice dintre ghilimele duble ca un șir, deci ce se întâmplă dacă doriți să introduceți un ghilimel dublu în șirul dvs., care va deruta programul, nu ar ști la ce servește fiecare ghilimă, să luăm acest exemplu ca exemplu: ```cpp print("Hello "world"); ``` De îndată ce compilatorul observă primele ghilimele, acesta va trata tot ce urmează ca parte a unui șir și va termina procesul de îndată ce atinge un alt ghilimel și, astfel, compilatorul va prelua **"Bună ziua"** ca un șir și va vedea ** Lumea ** ca niște sensuri care umplu găurile codului dvs. Pentru a rezolva acest lucru, trebuie să scăpăm de ghilimele duble pe care dorim să le imprimăm: ```cpp print("Hello \"world"); ``` Acum, compilatorul va trata al doilea ghilimel ca o secvență de evadare, deoarece este prefixat de un caracter de evadare (**\\**): ``` Hello "world ``` Să adăugăm un alt ghilimel doar pentru dracu: ```cpp print("Hello \"world\""); ``` ``` Hello "world" ``` Nu ar putea fi mai simplu. De-a lungul acestei secțiuni, am văzut cum putem reprezenta secvențe de evadare prin prefixarea caracterului de evadare ("\\") la un anumit caracter, dar acesta este doar un mod de a nota acele valori, printre altele, vom arunca o privire asupra alți doi; - **Secvențe de evacuare cu cod de caractere (cod zecimal) - `\ddd;`** Nu schimbă nimic în legătură cu secvențele de evadare, este doar un mod diferit de a le exprima, folosind coduri zecimale _ASCII_, de exemplu, dacă doriți să imprimați A, dar notați-l zecimal, puteți introduce codul zecimal _ASCII_, după cum urmează : ```cpp print("\65;"); ``` Acest lucru nu se referă doar la caractere alfanumerice, ci și la alte caractere, cum ar fi bipul audibil (`\ a`), cu valoarea zecimală `7`, poate fi reprezentat conform acestei notații ca `\7`; Semicol și virgulă este opțional și poate fi eliminat, dar este întotdeauna mai bine să mergeți cu abordarea inițială, scopul său este de a da secvenței de evadare un simbol de terminare explicit atunci când este utilizat într-o constantă de șir. - ** Secvențe de evacuare cu cod de caractere (cod zecimal) - `\xhhh;` ** Similar cu notația zecimală _ASCII_, putem folosi și formatul hexazecimal, caracterul **A**, putând fi scris fie ca `\65`; **sau` \ x41`;**, semi-colonul poate fi omis dacă doriți, acest lucru se aplică atât aici, cât și pe notația zecimală. ```cpp print("\x41;"); ``` ``` A ``` Puteți găsi toate aceste valori prin simpla căutare în `**Tabel ASCII**`, iar ceea ce este interesant este că este gratuit. #### Caracter de evadare personalizat Dacă ați observat, am continuat să apelez repetând `**caracterul de evadare**` de mai multe ori pe parcursul ultimei secțiuni, unde aș fi putut să-l menționez pur și simplu ca `**bară inversă**`, sau chiar scurtcircuitat, (`\`), motivul este că caracterul de evadare nu este un caracter absolut absolut, ci mai degrabă poate fi schimbat de preferință, îl puteți avea ca _@, ^, \ \$_ și așa mai departe, în mod implicit este o bară inversă , dar modul în care rămâne este determinat doar de dvs. n pentru a o schimba, folosim directiva pre-procesor `pragma`, această directivă specială acceptă parametri diferiți, pentru fiecare sarcină specifică a acestora, și există unul care răspunde de setarea caracterului de evacuare pe care ne vom concentra, este `ctrlchar`. ```cpp #pragma ctrlchar '$' main() { print("Hello $n World"); print("This is a backslash: \\"); print("The his a dollar sign: $$"); } ``` ``` Hello World This is a backslash: \ This is a dollar sign: $ ``` După cum puteți vedea, fluxul de linie este notat ca `$n` în loc de `\n` acum, iar backslash-ul nu mai este considerat caracterul de evadare și, în consecință, semnul dolar necesită să fie scăpat de un alt semn dolar. Cu toate acestea, nu poți schimba acest lucru în (`-`), dar orice altceva este o practică acceptabilă, dar niciodată nu este acceptată niciodată din punct de vedere etic. Flăcău nebun absolut. Această porțiune de aici nu are absolut nimic de-a face cu secvențele de evadare, dar este utilizată la formatarea textelor și a gametextului, este mai bine să o puneți aici decât oriunde altundeva; | | | | ----- | ----------------------------------------------------------------------------------------------------------------------------- | | `~u~` | Săgeată sus (gri) | | `~d~` | Săgeată în jos (gri) | | `~<~` | Săgeată la stânga (gri) | | `~>~` | Săgeată dreapta (gri) | | `]` | Afișează simbolul `*` (numai în stilul text 3, 4 și 5) | | `~k~` | maparea tastelor tastaturii (de ex. `~ k ~~ VEHICLE_TURRETLEFT ~` și `~ k ~~ PED_FIREWEAPON ~`). Căutați aici o listă de chei | maparea tastelor tastaturii (de ex. `~ k ~~ VEHICLE_TURRETLEFT ~` și `~ k ~~ PED_FIREWEAPON ~`). Căutați aici o listă de chei ### Specificator format #### Descriere Substituentii sau specificatorii sunt caractere scăpate de un semn procentual (`%`), indică poziția relativă și tipul de ieșire al anumitor parametri, servesc după cum sugerează și numele lor `_Prezentatori_`, salvează un loc pentru date care le vor înlocui ulterior în interiorul șirului, există diferite tipuri de specificatori și chiar urmează o formulă specifică; ``` %[flags][width][.precision]type ``` Atributele dintre paranteze sunt toate opționale și depinde de dvs., fie de utilizator, fie să le păstrați sau nu, ceea ce definește într-adevăr un specificator format larg cunoscut de **tip %**, partea tip este înlocuită cu un caracter pentru a reprezenta un anumit tip de ieșire; (_integer, float ... etc_). Substituentii sunt folosiți numai pentru funcțiile care acceptă parametri, astfel funcțiile precum tipărirea nu vor avea niciun efect, o alternativă la acesta este `printf` mai avansat. Let us look at the different output types that can be used: | **Specificator** | **Inteles** | | ---------------- | ------------------------------------------------------ | | `%i` | Întreg (_număr întreg_) | | `%d` | Întreg (_număr întreg_) | | `%s` | Şir | | `%f` | Număr în virgulă mobilă (`Float: tag`) | | `%c` | Caracter ASCII | | `%x` | Număr hexazecimal | | `%b` | Număr binar | | `%%` | Literal `'%'` | | `%q` | Scăpați un text pentru SQLite. (_Adăugat în 0.3.7 R2_) | - ** Specificatorii întregi - `%i` și `%d` ** Să le înfășurăm pe amândouă, în pion, acești doi specificatori fac același lucru exact, ambii numere întregi de ieșire, chiar dacă `% i` înseamnă întreg și `% d` înseamnă zecimal, sunt un sinonim pentru același lucru. Cu toate acestea, în alte limbi, diferența nu constă în ieșire, ci mai degrabă în intrare cu funcții precum `scanf`, unde`% d` scanează un număr întreg ca o zecimală semnată, iar% i implicit la zecimal, dar permite și hexazecimal (_if precedat de `0x`_) și octal (_dacă precedat de` 0`_). Utilizările acestor doi specificatori merg după cum urmează: ```cpp printf("%d is here", 2018); printf("%d + %i = %i", 5, 6, 5 + 6); ``` ``` printf("%d is here", 2018); printf("%d + %i = %i", 5, 6, 5 + 6); ``` Ieșirea acceptă, de asemenea, constante, variabile și funcții predefinite. ```cpp #define CURRENT_YEAR 2018 new age = 19; printf("It’s %d", CURRENT_YEAR); printf("He is %d years old", age); printf("Seconds since midnight 1st January 1970: %d", gettime()); ``` ``` It's 2018 He is 19 years old Seconds since midnight 1st January 1970: 1518628594 ``` După cum puteți vedea, orice valoare pe care o trecem în parametrii funcției `printf` este înlocuită de substituentul respectiv și amintiți-vă, **ordinea contează**, substituenții dvs. ar trebui să urmeze aceeași ordine ca și parametrii dvs. în apel, și folosiți întotdeauna tipul corect de specificator, dacă nu faceți acest lucru, nu va rezulta o eroare, dar poate genera rezultate nedorite, dar în unele cazuri, aceste rezultate nedorite sunt ceea ce ne dorim. Ce credeți că se va întâmpla dacă am încerca să imprimăm un float sau un șir folosind un specificator întreg? Să aflăm; ```cpp printf("%d", 1.12); printf("%d", "Hello"); printf("%d", 'H'); printf("%d", true); ``` ``` 1066359849 72 72 1 ``` Cât de ciudat, total neașteptat, dar nu neapărat inutil, acest comportament exact este profitat în atât de multe situații. În primul rând, să vedem de ce a ieșit `1.12` _1066359849_, ei bine, asta se numește comportament nedefinit, puteți afla mai multe despre acest lucru [aici](https://en.wikipedia.org/wiki/Undefined_behavior). Încercarea de a produce un șir folosind un specificator întreg va da codul _ASCII_ al primului său caracter, în acest caz, codul caracterului H, 72, la fel se întâmplă cu ieșirea unui singur caracter. Și, în cele din urmă, scoaterea unui boolean va da 1 dacă este adevărat și 0 dacă este fals. Șirurile sunt matrici în sine, așa că scoaterea unei matrici aici va da valoarea primului slot din matricea respectivă, modul în care va fi afișat depinde de ce tip este (_intreg, float, caracter, boolean_). - ** Specificatorii șirului - `%s` ** Acest specificator, așa cum înseamnă șir, este responsabil pentru ieșirea șirurilor (_evident_): ```cpp printf("Hello, %s!", "World"); ``` ``` Hello, world! ``` Să redăm, de asemenea, valori care nu sunt șiruri, folosind și acest lucru: ```cpp printf("%s", 103); printf("%s", true); printf("%s", 'H'); printf("%s", 1.12); ``` ``` g H ) ``` Numărul "103" a fost tratat ca codul _ASCII_ pentru _g_ și, astfel, a fost tipărit _g_, același lucru este valabil și pentru simbolul ciudat de sub el, caracterul cu valoarea true, aka _1_ a fost tipărit, mai simplu, caracterul "H" a fost tipărit așa cum este, dar hei, ce s-a întâmplat cu numărul de tip float "1.12"? îți amintești de **comportamentul nedefinit**? Da, `1.12` a rezultat într-un număr întreg uriaș, care a continuat să se revărseze (valoarea sa împărțită la _255_) ori, până când a rezultat într-un număr între _0_ și _254_, în acest caz, _40_, care este codul _ASCII_ al caracterului. Din nou, la fel ca specificatorul întregului, acesta acceptă constante, variabile și funcții predefinite: ```cpp #define NAME "Max" new message[] = `Hello there!`; printf("His name is %s", NAME); printf("Hey, %s", message); printf("%s work", #Great); ``` ``` His name is Max Hey, Hello there! Great work ``` - ** Specificatorii pentru float - `%f` ** Acest specificator - scurt pentru float-, așa cum sugerează și numele său, scoate numere flotante, pe secțiunile anterioare, am încercat să scoatem numere flotante folosind specificatorul întreg și apoi am obținut acel comportament nedefinit, dar acum, că știm despre acest specificator , putem scoate în siguranță flotante fără probleme; ```cpp printf("%f", 1.235); printf("%f", 5); printf("%f", 'h'); ``` Numărul de tip float _1.235_ a ieșit foarte bine, cu adăugarea unor umpluturi, cu toate acestea, restul tuturor ieșirilor _0.000000_, practic _0_, asta pentru că specificatorul `%f` va scoate doar numere flotante, cu alte cuvinte, numere care nu au un număr fix de cifre înainte și după punctul zecimal; adică punctul zecimal poate pluti. Pentru a remedia problema, pur și simplu adăugăm partea fracțională: ```cpp printf("%f", 5.0); printf("%f", 'h' + 0.0); ``` ``` 5.000000 104.000000 ``` Deși `%f` este substituentul de tip float cel mai frecvent utilizat, specificatorul `%h` face cam același lucru: ```cpp printf("%h", 5.0); ``` ``` 5.000000 ``` - ** Specificatorii de caractere - `%c` ** Acest specificator, scurt pentru caracter, funcționează ca substituentul șirului, dar generează doar un singur caracter, să observăm următorul exemplu: ```cpp printf("%c", 'A'); printf("%c", "A"); printf("%c", "Hello"); printf("%c", 105); printf("%c", 1.2); printf("%c", true); ``` ``` A A H i s ``` După cum puteți vedea, trecerea unui șir va genera doar primul caracter și trecerea unui număr va genera caracterul al cărui cod _ASCII_ se potrivește cu acel număr (_Booleanii sunt convertiți la 0 și respectiv 1_). - ** Specificatorii hexazecimali - `%x` ** Următorul specificator afișează valoarea pe care o trecem ca număr hexazecimal, pur și simplu, o conversație de numere dintr-o bază dată în baza 16. ```cpp printf("%x", 6); printf("%x", 10); printf("%x", 255); ``` ``` 6 A FF ``` La fel ca și cazurile pe care le-am văzut în secțiunile anterioare, trecerea valorilor altele decât numerele întregi le va converti la valorile lor întregi respective și le va genera ca numere hexazecimale; ```cpp printf("%x", 1.5); printf("%x", 'Z'); printf("%x", "Hello"); printf("%x", true); ``` ``` 3FC00000 5A 48 1 ``` Prima valoare `1.5`, va avea ca rezultat un comportament nedefinit la conversia sa într-un număr întreg (_1069547520_), apoi întregul rezultat va fi afișat ca hexazecimal (_3FC00000_), caracterul `Z`, va avea valoarea sa _ASCII_ (90) convertit în hexazecimal (5A). Șirul `Bună ziua` va avea doar primul său caracter (H) cu valoarea _ASCII_ de (72) convertită în hexazecimal (48). Și ieșirile `adevărate` (1) ca hexazecimal, care se convertește în (1), (fals va ieși 0). - ** Specificatorii binari - `%b` ** Următorul specificator, scurt pentru `_binary_` este utilizat pentru a imprima valorile trecute ca numere binare, caracterele trecătoare vor converti codul său _ASCII_ în binar, la fel și cazul șirurilor în care este considerat doar primul caracter, booleenii sunt considerați adevărați și fals, respectiv, numerele flotante se încadrează în cazul comportamentului nedefinit, ca pentru numere întregi și hexazecimale, acestea sunt convertite în binar și de ieșire. ```cpp printf("%b", 0b0011); printf("%b", 2); printf("%b", 2.0); printf("%b", 0xE2); printf("%b", 'T'); printf("%b", "Hello"); printf("%b", true); ``` ``` 11 10 1000000000000000000000000000000 11100010 1010100 1001000 1 ``` - ** Literalul `%` ** La fel ca caracterul implicit de scăpare (`\`), compilatorul vede (`%`) ca un caracter special și, astfel, tratează secvența ca un substituent, atâta timp cât există un caracter după (`%`) este considerat ca specificator chiar dacă nu este valid, să observăm aceste două cazuri; ```cpp printf("%"); printf("Hello %"); printf("% World"); printf("Hello % World"); ``` ``` % Hello % World Hello World ``` După cum puteți vedea, dacă aveți (`%`) singur ca secvență individuală, acesta va fi afișat, dar nu același lucru se întâmplă atunci când este urmat de spațiu sau de orice alt caracter, rezultând astfel scoaterea unui caracter spațial. Pentru a încălca această problemă, o scăpăm folosind un alt semn procentual după cum urmează; ```cpp printf("This is a percent sign %%, we just had to escape it!"); ``` ``` Acesta este un %, doar a trebuit să scăpăm de el! ``` Desigur, acest lucru se referă doar la funcții care acceptă formatarea, cum ar fi `printf` și `format`, de exemplu, încercarea de a afișa un semn procentual folosind funcția `print` nu va necesita scăparea acestuia. - ** Specificatorul `%q` ** Acesta nu are o mare importanță în subiectul nostru principal, este folosit pe scară largă pentru a scăpa de șirurile sensibile atunci când lucrați cu _SQLite_ și credeți-mă, nimeni nu vrea să cadă sub cazul [tabelului lui Bobby](http://bobby-tables.com/about). Când am introdus substituenții, facem referire la o formulă specifică care îi privește, ca un memento, iată-l; ``` %[flags][width][.precision]type ``` Până acum, am vorbit doar despre semnul `%` și despre tipul depus, celelalte sunt opționale, dar fiecare este eficient în diferite cazuri, le puteți include pentru a controla mai bine modul în care valorile dvs. sunt tratate atunci când sunt afișate. - ** Lățimea depusă ** Acesta este responsabil pentru specificarea rezultatului minim de caractere, poate fi omis dacă este necesar, trebuie doar să tastați valoarea acestuia ca număr întreg, să vedem câteva exemple; ```cpp printf("%3d", 5555); printf("%3d", 555); printf("%3d", 55); printf("%3d", 5); ``` ``` 5555 555 55 5 ``` Am instruit specificatorul să blocheze ieșirea la 3 caractere sau mai mult, la început, ieșirea numărului de 4 și 3 caractere a mers bine, dar caracterele mai scurte de 3 caractere au rămas căptușite cu spații, chiar și la lățimea de ieșire. Există, de asemenea, posibilitatea de a avea valori dinamice ale lățimii, pentru aceasta, folosim semnul asterisc (`*`). ```cpp printf("%*d", 5, 55); ``` ``` 55 ``` Mai întâi, trecem valoarea lățimii care a fost `5`, apoi valoarea pe care dorim să o afișăm `55`, astfel încât substituentul redă un minim de 5 caractere, adică 5 minus 2, ceea ce ne oferă 3 spații de umplere. - ** Câmpul steaguri ** Acesta funcționează foarte bine cu câmpul de lățime, deoarece lățimea specifică caracterele minime pentru ieșiri, acesta tamponează golul lăsat în urmă cu orice îi spuneți. În cazul în care au rămas spații în urmă, nu va exista niciun tampon. ```cpp printf("%3d", 55); printf("%5x", 15); printf("%2f", 1.5) ``` ``` 055 0000F 01.500000 ``` Primul număr 55, este scurt pe un caracter din cauza lățimii parametrului zecimal, deci este umplut cu un 0. În ceea ce privește 15, este convertit la valoarea hexadecimală respectivă _F_ și umplut cu 4 0 pentru a valida lățimea lui substituent. Observați cum a fost umplut doar numărul dinaintea punctului zecimal. Utilizarea valorilor dinamice ale lățimii rămâne și aici, trebuie doar să includem asteriscul, să trecem o valoare și să urmărim cum se întâmplă magia; ```cpp printf("%0*d", 5, 55); ``` ``` 00055 ``` - ** Câmpul de precizie ** Câmpul Precizie specifică de obicei o limită maximă la ieșire, în funcție de tipul de formatare particular. Pentru tipurile numerice cu virgulă mobilă, specifică numărul de cifre din dreapta punctului zecimal pe care ieșirea trebuie rotunjită. Pentru tipul de șir, acesta limitează numărul de caractere care ar trebui să fie redate, după care șirul este trunchiat. ```cpp printf("%.2f", 1.5); printf("%.*f", 10, 1.5); printf("%.5s", "Hello world!"); printf("%.*s", 7, "Hello world!"); ``` ``` 1.50 1.5000000000 Hello Hello w ``` După cum puteți vedea, valorile dinamice de precizie pot fi folosite atât cu semnele de poziție plutitoare, cât și cu șirul de caractere. Un truc foarte interesant pe care îl putem trage datorită câmpului de precizie este obținerea de șiruri de caractere, acum, acum, există o mulțime de metode pe care le putem folosi pentru a face acest lucru, și asta fără a lua în considerare nativul [strfind](../scripting/functions/strfind) și să nu uităm de funcțiile uimitoare pe care le-am obținut la [strlib](https://github.com/oscar-broman/strlib) din **Slice**. Să vedem cum putem obține același rezultat folosind doar câmpul de precizie. ```cpp substring(const source[], start = 0, length = -1) { new output[256]; format(output, sizeof(output), "%.*s", length, source[start]); return output; } ``` Să încercăm să descifrăm această bucată de cod, trecem pur și simplu șirul sursă, (șirul din care urmează să extragem), o poziție de pornire (slotul pe care vom începe să îl extragem) și lungimea caracterelor pe care le dorim a extrage. Valoarea noastră returnată va fi formatată în funcție de următorul substituent `%. * S`, includem câmpul de precizie și îl folosim pentru a determina o valoare dinamică care va fi lungimea caracterelor extrase, apoi oferim un punct de plecare pentru extragerea prin adăugarea `sursă [start]` care trece de la primul slot la numărul slotului `start` pe care l-am trecut în parametrii funcției. Să apelăm funcția și să vedem cum merge de aici: ```cpp new message1[] = "Hello!", message2[] = "I want an apple!"; print(substring(.source = message1, .start = 1, .length = 3)); print(substring(.source = message2, .start = 7, .length = 8)); ``` ``` ell an apple ``` Simplu nu? Bonus de trivia, trecerea unei _negative_ ca lungime de extracție va avea ca rezultat emiterea tuturor caracterelor din șirul dvs. sursă începând din slotul **start**. Pe de altă parte, trecerea 0 ca lungime de extracție returnează o valoare nulă. Să aruncăm o privire asupra acestor cazuri: ```cpp new message3[] = "Arrays start at 1, says the Lua developer!"; print(substring(message3)); // start = 0 by default, length = -1 by default print(substring(message3, .length = 6)); // start = 0 by default, length = 6 print(substring(message3, 7, 10)); // start = 7, length = 10 print(substring(message3, strlen(message3) - 14)); // start = 28, length = -1 by default print(substring(message3, strlen(message3) - 14, 3)); // start = 28, length = 3 ``` ``` Arrays start at 1, says the Lua developer! Arrays start at 1 Lua developer! Lua ``` #### Utilizare Punând toate acțiunile pe care le-am văzut până acum la acțiune, putem oricum să ne formăm șirurile destul de potrivite, până acum am lucrat în principal în consolă, folosind funcțiile `print` și `printf` pentru a ne transmite datele , în principal `printf`, adică datorită suportului său nativ pentru formatarea șirurilor în mișcare, de unde și f pe numele funcției. Însă în lumea reală, majorității oamenilor nu le place să se uite la terminale, sunt prea înfricoșători și complicate pentru utilizatorul obișnuit și, după cum știți cu toții, mesajele clientului apar pe ecranul jocului și nu consola, totuși , acestea nu pot fi formatate în mișcare, sunt mai mult ca o funcție de imprimare s-ar putea spune, pentru a ocoli această limitare, folosim și o altă funcție foarte eficientă, numită `format`, nu vom aprofunda definiția acesteia, așa cum am am trecut deja prin explicarea acestuia în părțile anterioare, (consultați [acest](../scripting/functions/format)), dar, iată un memento al sintaxei sale; ```cpp format(output[], len, const format[], {Float,_}: ...} ``` Să aruncăm o privire la aceste exemple; **Exemplul 1**: _Nume jucător - Presupunând că există o redare pe server cu codul 9 numit Player1_: ```cpp // MAX_PLAYER_NAME is a predefined constant with the value of 24, we add 1 to take into account the null terminator, thanks to Pottus for pointing that out. new playerName[MAX_PLAYER_NAME + 1], output[128], playerid = 9; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); format(output, sizeof(output), "[Info]: the player with the id of %d is called {EE11CC}%s.", playerid, playerName);SendClientMessageToAll(0, output); ``` > [Informații]: playerul cu ID-ul 9 este numit <span style={{color: '#ee11cc'}}>Player1</span>. Pur și simplu, obținem doar numele jucătorului și începem să formatăm șirul, substituentul `% d` este responsabil pentru afișarea variabilelor `playerid`, care deține valoarea `9`, substituentul `%s` afișează `playerName` șir care conține numele jucătorului datorită funcției `GetPlayerName`. Afișăm apoi șirul formatat tuturor de pe server folosind funcția `SendClientMessageToAll`, observăm că valoarea`0` din primul său parametru indică culoarea neagră, care va fi culoarea mesajului, valoarea hexagonală încorporată `{FFFF00}`este ceea ce a dus la ca numele jucătorului să fie galben. **Exemplul 2**: _In-game Clock - Afișarea orei curente în joc_: ```cpp new output[128], hours, minutes, seconds; gettime(hours, minutes, seconds); format(output, sizeof(output), "It's %02d:%02d %s", hours > 12 ? hours - 12 : hours, minutes, hours < 12 ? ("AM") : ("PM")); SendClientMessageToAll(0, output); ``` Din nou, am folosit doar funcția `gettime` pentru a stoca respectivele ore, minute și secunde pe variabilele lor, apoi le-am pus pe toate împreună într-un șir frumos formatat, am profitat de câmpul de lățime`% 02d` pentru a tampona valorile între 0 și 9 cu un alt zero pentru a se sustrage ieșirilor cum ar fi (`_Este 5: 9 PM_`), după cum puteți vedea. > Este ora 18:17 **Exemplul 3**: _Mesajul moarte - Afișarea unui mesaj când un jucător moare, având numele jucătorilor colorate în culorile lor_: ```cpp public OnPlayerDeath(playerid, killerid, WEAPON:reason) { // MAX_PLAYER_NAME is a predefined constant with the value of 24, we add 1 to take into account the null terminator, thanks to Pottus for pointing that out. new message[144], playerName[MAX_PLAYER_NAME + 1], killerName[MAX_PLAYER_NAME + 1]; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); GetPlayerName(killerid, killerName, MAX_PLAYER_NAME); format(message, sizeof(message), "{%06x}%s {000000}killed {%06x}%s", GetPlayerColor(killerid) >>> 8, killerName, GetPlayerColor(playerid) >>> 8, playerName); SendClientMessageToAll(0, message); return 1; } ``` Având în vedere următoarea listă de jucători conectați: | **ID** | **Jucator** | | ------ | ----------------------------------------------- | | 0 | <span style={{color: 'red'}}>Compton</span> | | 1 | <span style={{color: 'grey'}}>Dark</span> | | 5 | <span style={{color: 'red'}}>Player1</span> | | 6 | <span style={{color: 'blue'}}>Bartolomew</span> | | 11 | <span style={{color: 'grey'}}>unban_pls</span> | Spuneți, `playerid` `0` a ucis `playerid` `6` , mesajele formatate ar trebui să scrie `** {FF0000} Compton {000000} ucis> {0000FF} Bartolomew ** `, care va trimite următorul mesaj client tuturor pe server: > <span style={{color: 'red'}}>Compton</span> ­ <span style={{color: '#000000'}}>killed</span> ­ <span style={{color: 'blue'}}>Bartolomew</span> Îmi cer scuze dacă v-am confundat folosind [shift bit logic](https://en.wikipedia.org/wiki/Logical_shift), a fost pur și simplu folosit aici pentru a transforma numărul zecimal returnat de funcția `GetPlayerColor` în un număr hexazecimal care reprezintă o culoare, schimbarea în sine este utilizată pentru a omite spațiul -alfa-, pentru mai multe despre acest lucru, vă recomand cu tărie să verificați [acest tutorial](Binar) de **Kyosaur**. #### Specificatori personalizați Lucrul cu specificatorii de formatare prin care am trecut până acum este suficient, puteți face literalmente tot felul de lucruri cu acele instrumente magnifice, dar nimic nu ne împiedică să ne întrebați pentru mine, cât de lacomi de noi. Toate datorită lui ** Slice ** după ce a fost influențat de [sscanf](https://github.com/maddinat0r/sscanf), a venit cu o includere uimitoare, [formatex](https://github.com/Southclaws/formatex), care a adăugat mai mulți noi specificatori de utilizat, ceea ce a ușurat într-adevăr o mulțime de lucruri de pion în fiecare zi. Dar asta nu a fost, puteți crea propriile dvs. specificatori pentru a se potrivi nevoilor dvs. și, oricât de mișto ar părea, procesul este foarte ușor. Doar în scopuri de testare, să facem ceva prostesc, ceva la fel de simplu ca să dai un șir ca intrare și să-l returnăm sub forma unui link (_https://www.string.com_); ```cpp FormatSpecifier<'n'>(output[], const param[]) { format(output, sizeof(output), "https://www.%s.com", param); } ``` La fel de simplu, și, prin urmare, puternicul specificator `%n` (prescurtare pentru Newton, deoarece este foarte cool și știința rachetei complicată 😉 s-a născut, să testăm acest campion: ```cpp printf("%n", "samp"); ``` > https://www.samp.com :::note Nu lăsați acest exemplu să vă păstreze sau să vă limitați așteptările pentru ceea ce este posibil să realizați cu specificatorii personalizați, există exemple mai bune pe pagina principală de lansare, [vă rugăm să consultați acest lucru](https://github.com/Southclaws/formatex/blob/master/README.md). ::: ### linkuri externe #### Tutoriale similare - [String formatting](http://web-old.archive.org/web/20190419210950/https://forum.sa-mp.com/showthread.php?t=265433) de [krogsgaard20](http://web-old.archive.org/web/20190421052543/https://forum.sa-mp.com/member.php?u=126724) - [Understanding Strings](http://web-old.archive.org/web/20190420182625/https://forum.sa-mp.com/showthread.php?t=284112) de [\[HiC\]TheKiller](http://web-old.archive.org/web/20190419205839/https://forum.sa-mp.com/member.php?u=23565) - [How to use strcmp](http://web-old.archive.org/web/20190419172015/https://forum.sa-mp.com/showthread.php?t=199796) de [Ash.](http://web-old.archive.org/web/20190419205839/https://forum.sa-mp.com/member.php?u=78597) - [Beginner's Guide: Single/Two/Multi-dimensional Arrays](http://web-old.archive.org/web/20190419102936/https://forum.sa-mp.com/showthread.php?t=318212) de [iPLEAOMAX](http://web-old.archive.org/web/20190419112304/https://forum.sa-mp.com/member.php?u=122705) - [Tips and Tricks](http://web-old.archive.org/web/20190419112018/https://forum.sa-mp.com/showthread.php?t=216730) de [Slice](https://github.com/oscar-broman) - [Code optimization](http://web-old.archive.org/web/20190419205837/https://forum.sa-mp.com/showthread.php?t=571550) de [Misiur](http://web-old.archive.org/web/20190419111434/https://forum.sa-mp.com/member.php?u=55934) - [Packed strings](http://web-old.archive.org/web/20190419172431/https://forum.sa-mp.com/showthread.php?t=480529) de [Emmet\_](https://github.com/emmet-jones) - [IRC string formatting](https://github.com/myano/jenni/wiki/IRC-String-Formatting) de [myano](https://github.com/myano) - [String manupilation](https://web.archive.org/web/20190424140855/https://www.compuphase.com/pawn/String_Manipulation.pdf) de [CompuPhase](https://web.archive.org/web/20190424140855/http://www.compuphase.com/) - [Pawn-lang](https://github.com/pawn-lang/compiler/blob/master/doc/pawn-lang.pdf) - [An in-depth look at binary and binary operators](http://web-old.archive.org/web/20190419095051/https://forum.sa-mp.com/showthread.php?t=177523) de [Kyosaur](http://web-old.archive.org/web/20190419205838/https://forum.sa-mp.com/member.php?u=23990) #### Relatari/plugin-uri/contributii relatate - [Westie](http://web-old.archive.org/web/20190419205841/https://forum.sa-mp.com/member.php?u=56481)'s [strlib](http://web-old.archive.org/web/20200923234356/https://forum.sa-mp.com/showthread.php?t=85697) - [Slice](https://github.com/oscar-broman)'s [strlib](https://github.com/oscar-broman/strlib) - [Slice](https://github.com/oscar-broman)'s [formatex](https://github.com/Southclaws/formatex) - [corne](http://web-old.archive.org/web/20190419205840/https://forum.sa-mp.com/member.php?u=98345)'s [y_stringhash](http://web-old.archive.org/web/20190419205838/https://forum.sa-mp.com/showthread.php?t=571305) - [Y-Less](https://github.com/Y-Less)'s [sscanf](https://github.com/maddinat0r/sscanf) #### Referințe - [GTA San Andreas](https://www.rockstargames.com/sanandreas/) - [Textdraw](../scripting/resources/textdraws#what-is-a-textdraw) - [Gametext](../scripting/functions/GameTextForPlayer) - [Limitations](../scripting/resources/limits) - [ASCII](https://en.wikipedia.org/wiki/ASCII) - [ASCII table](https://www.asciitable.com/) - [Pawn Tutorial](https://wiki.alliedmods.net/Pawn_Tutorial) - [Control Structures](../scripting/language/ControlStructures) - [Null character](https://en.wikipedia.org/wiki/Null_character) - [RGBA color space](https://en.wikipedia.org/wiki/RGBA_color_space) - [Color picker](https://www.webpagefx.com/web-design/color-picker/) - [TextDrawColor](../scripting/functions/TextDrawColor) - [Gametext styles](../scripting/resources/gametextstyles) - [Color list](../scripting/resources/colorslist) - [Escape sequence](https://en.wikipedia.org/wiki/Escape_sequence) - [r/programmerhumor](https://www.reddit.com/r/ProgrammerHumor/) - [Newline](https://en.wikipedia.org/wiki/Newline) - [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) - [Bobby table](https://bobby-tables.com/about) - [strfind](../scripting/functions/strfind) - [format](../scripting/functions/format) - [Bitwise logical shift](https://en.wikipedia.org/wiki/Logical_shift)
openmultiplayer/web/docs/translations/ro/tutorials/stringmanipulation.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ro/tutorials/stringmanipulation.md", "repo_id": "openmultiplayer", "token_count": 43898 }
401
--- title: AddSimpleModelTimed description: Добавляет сторонний объект для скачивания. tags: [] --- <VersionWarn version='SA-MP 0.3.DL R1' /> ## Описание Аналог AddSimpleModel, только с дополнительными крайними двумя параметрами времени. Добавляет сторонний объект для скачивания. Файл модели будет помещен в папку на компьютер игрока Documents\GTA San Andreas User Files\SAMP\cache под названием IP и Порта сервера в виде CRC. | Параметр | Описание | | ------------ | --------------------------------------------------------------------------------------------------------------------------- | | virtualworld | Виртуальный мир, в котором объект доступен. Используйте -1 для всех миров. | | baseid | ID существующего объекта ( для замены объекта при ошибке загрузки ) | | newid | ID нового объекта в пределах от -1000 до -30000 (29000 слотов) для использования в CreateObject или CreatePlayerObject. | | dffname | Название .dff файла колизии модели, расположенного стандартно в папке models (параметр настройки artpath). | | txdname | Название .txd файла текстур модели, расположенного стандартно в папке models (параметр настройки artpath). | | timeon | Время игрового мира (часы), со скольки объект виден. | | timeoff | Время игрового мира (часы), когда объект пропадает. | ## Возвращаемые данные 1: Функция выполнена успешно. 0: Функция не выполнена. ## Примеры ```c public OnGameModeInit() { AddSimpleModelTimed(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd", 9, 18); // Объект будет виден с 9:00 до 18:00 return 1; } ``` ## Примечания :::tip `useartwork` должна быть включена ( 1 ) в настройках сервера, чтобы данная функция работала. В случае если установлен виртуальный мир (virtualworld), модель будет скачана когда игрок попадёт в указанный виртуальный мир. ::: :::warning В данный момент нет ограничений для вызова данной функции, но учтите, что если вы вызываете функцию НЕ в OnFilterScriptInit/OnGameModeInit, то у игроков, которые находяться на сервере, могут не быть скачаны данные файлы модели. ::: ## Связанные функции - [OnPlayerFinishedDownloading](../callbacks/OnPlayerFinishedDownloading): Вызывается когда игрок закончил скачивание сторонних файлов. - [AddSimpleModel](AddSimpleModel): Добавляет стороннюю модель объекта для скачивания.
openmultiplayer/web/docs/translations/ru/scripting/functions/AddSimpleModelTimed.md/0
{ "file_path": "openmultiplayer/web/docs/translations/ru/scripting/functions/AddSimpleModelTimed.md", "repo_id": "openmultiplayer", "token_count": 2246 }
402
--- title: OnClientMessage description: Ta "callback" se pokliče vsakič, ko NPC vidi "ClientMessage" tags: [] --- ## Opis Ta "callback" se pokliče vsakič, ko NPC vidi "ClientMessage" (sporočilo, ki ga pošlje "client"). To bo vsakič, ko se prikliče funkcijo `SendClientMessageToAll` in vsakič, ko se funkcijo" SendClientMessage "pošlje NPC. Ta povratni klic ne bo poklican, ko nekdo nekaj reče. Za besedilno različico predvajalnika glejte funkcijo NPC: "OnPlayerText". | Ime | Opis | | ------ | ------------------------------------ | | color | Barva "ClientMessage" sporočila . | | text[] | Pravo sporočilo. | ## Returns Ta "callback" se ne obdeluje (return). ## Primeri ```c public OnClientMessage(color, text[]) { if (strfind(text,"Stanje na banki : $0") != -1) { SendClientMessage(playerid, -1, "Reven sem :("); } } ``` ## Povezane Funkcijo
openmultiplayer/web/docs/translations/sl/scripting/callbacks/OnClientMessage.md/0
{ "file_path": "openmultiplayer/web/docs/translations/sl/scripting/callbacks/OnClientMessage.md", "repo_id": "openmultiplayer", "token_count": 405 }
403
--- title: OnClientMessage description: Овај колбек је позван када год NPC види клијент поруку (ClientMessage). tags: [] --- ## Опис Овај колбек је позван када год NPC види клијент поруку (ClientMessage). Ово ће увек бити када је SendClientMessageToAll функција позвана и сваки пут када је SendClientMessage позвана NPC-у. Овај колбек неће бити позиван када неко каже нешто. За верзију овога погледајте: NPC:OnPlayerText. | Име | Опис | | ------ | ------------------- | | color | Боја ClientMessage. | | text[] | Порука. | ## Узвраћања Овај колбек нема узвраћања. ## Примери ```c public OnClientMessage(color, text[]) { if (strfind(text,"Bank Balance: $0") != -1) { SendClientMessage(playerid, -1, "I am poor :("); } } ``` ## Сродне функције
openmultiplayer/web/docs/translations/sr/scripting/callbacks/OnClientMessage.md/0
{ "file_path": "openmultiplayer/web/docs/translations/sr/scripting/callbacks/OnClientMessage.md", "repo_id": "openmultiplayer", "token_count": 578 }
404
--- title: การมีส่วนร่วม description: วิธีการมีส่วนร่วมกับเอกสาร SA-MP Wiki และ open.mp --- แหล่งที่มาของเอกสารนี้เปิดให้ทุกคนมีส่วนร่วมในการ เปลี่ยนแปลง!! พวกคุณ ต้องมีบัญชี [GitHub](https://github.com) และเวลาว่างสักเล็กน้อย คุณไม่จำเป็นต้องรู้ เกี่ยวกับ Git ด้วยซ้ำ คุณสามารถทำได้ทั้งหมดจากหน้าเว็บ! ## การแก้ไขเนื้อหา ในแต่ละหน้า มีปุ่มที่จะพาคุณไปยังหน้า Github เพื่อทำการแก้ไข: ![มีลิงค์อยู่ในแต่ละหน้า Wiki เขียนว่า Edit this page](images/contributing/edit-this-page.png) ยกตัวอย่างเช่น คลิกไปที่ [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) มันจะพาคุณไป [หน้านี้](https://github.com/openmultiplayer/web/edit/master/docs/scripting/functions/SetVehicleAngularVelocity.md) ซึ่งจะแสดงเครื่องมือในการแก้ไขข้อความเพื่อทำการเปลี่ยนแปลง ไฟล์ (สมมติหาก คุณเข้าสู่ระบบ Github) ทำการแก้ไขในส่วนของคุณและส่ง "Pull Request" ซึ่งหมายถึงผู้ดูแล Wiki และ สมาชิกคอมมูนิตี้คนอื่น ๆ สามารถตรวจสอบการเปลี่ยนแปลงของคุณ และพูดคุยกันว่ามันจำเป็น หรือไม่กับการเปลี่ยนแปลงนี้แล้วรวมเข้าด้วยกัน ## การเพิ่มเนื้อหาใหม่ การเพิ่มเนื้อหาใหม่มีอาจมีความยุ่งยากเล็กน้อย คุณสามารถทำได้สองวิธี: ### หน้าอินเตอร์เฟซของ GitHub เมื่อเรียกดูไดเรกทอรีบน GitHub จะมีปุ่ม Add file อยู่ด้านบน มุมขวาของรายการไฟล์: ![ปุ่ม Add file](images/contributing/add-new-file.png) คุณสามารถอัปโหลดไฟล์ Markdown ที่คุณเขียนไว้แล้วหรือเขียนมันโดยตรงผ่านเครื่องมือแก้ไขข้อความของ Github ไฟล์ _ควร_ มีสกุล `.md` และมี Markdown สำหรับข้อมูลเพิ่มเติม เกี่ยวกับ Markdown ลองดูที่ [คู่มือนี้](https://guides.github.com/features/mastering-markdown/) เมื่อเสร็จแล้วให้กด "Propose new file" จากนั้น Pull Request จะเปิดขึ้นมาเพื่อ ตรวจสอบ ### Git หากต้องการใช้ Git สิ่งที่คุณต้องทำคือโคลนที่เก็บ Wiki ด้วย: ```sh git clone https://github.com/openmultiplayer/wiki.git ``` เปิดมันด้วยเครื่องมือแก้ไขไฟล์ที่คุณชอบ ผมแนะนำให้ใช้ Visual Studio Code เพราะมันมี เครื่องมือดี ๆ สำหรับการแก้ไขและจัดรูปแบบไฟล์ Markdown อย่างที่คุณเห็น ผม เขียนมันด้วย Visual Studio Code! ![ภาพตัวอย่าง Markdown จาก Visual Studio Code](images/contributing/vscode.png) ผมแนะนำให้ใช้ส่วนขยายสองตัวนี้เพื่อเพิ่มประสบการณ์ของคุณให้ดียิ่งขึ้น: - [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) โดย David Anson - นี่คือส่วนขยายที่ทำให้แน่ใจว่า Markdown ของคุณ มีรูปแบบที่ถูกต้อง มันป้องกันความผิดพลาดทางไวยากรณ์และความหมาย ไม่ใช่ คำเตือนทั้งหมดจะมีความสำคัญ แต่บางคำเตือนสามารถช่วยปรับปรุงความสามารถในการอ่านได้ ใช้ วิจารณญาณที่ดีที่สุด และหากมีข้อสงสัยเพียงแค่ถามผู้วิจารณ์! - [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) โดยทีม Prettier.js - นี่คือตัวที่สามารถจัดรูปแบบไฟล์ Markdown ของคุณโดยอัตโนมัติ ดังนั้นพวกเขา ใช้สไตล์ที่สอดค้ลองกัน ก็คือที่เก็บ Wiki มีการตั้งค่าบางอย่างใน `package.json` ที่ส่วนขยายนี้เรียกใช้โดยอัตโนมัติ อย่าลืมเปิดใช้งาน "Format On Save" ในการตั้งค่าตัวแก้ไขเพื่อให้ไฟล์ Markdown ของคุณได้รับการจัดรูปแบบโดยอัตโนมัติทุกครั้งที่คุณบันทึก! ## บันทึก เคล็ดลับ และกระบวนการ ### ลิงค์ภายใน อย่าใช้ URL แบบเต็มสำหรับการเชื่อมต่อภายในเว็บไซต์เดียวกัน ใช้เส้นทางที่อยู่ในเครือเดียวกัน - ❌ ```md ใช้กับ [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer) ``` - ✔ ```md ใช้กับ [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer) ``` `../` ความหมายคือ "ย้อนกลับไปหนึ่งไดเรกทอรี" ดังนั้นหากไฟล์ที่คุณกำลังแก้ไขอยู่ใน ไดเรกทอรี `functions` และคุณจะเชื่อมต่อไปหา `callbacks` คุณสามารถใช้ `../` เพื่อกลับไป ยัง `scripting/` จากนั้นก็ `callbacks/` เพื่อเข้าไปยังไดเรกทอรีของ callbacks จากนั้น ชื่อไฟล์ callback (ไม่มี `.md`) ที่คุณต้องการเชื่อมต่อ ### รูปภาพ รูปภาพจะอยู่ในไดเร็กทอรีย่อยด้านใน `/static/images` จากนั้นเมื่อคุณต้องการโยงไฟล์ รูปภาพใน `![]()` คุณแค่ใช้ `/images/` เป็นฐาน (ไม่จำเป็นต้อง `static` นั้นเป็นเส้นทางสำหรับที่เก็บ) หากมีข้อสงสัย โปรดอ่านหน้าอื่นที่ใช้รูปภาพเหมือนกันและก๊อปปี้วิธีการทำที่นั้นมาได้เลย ### Metadata สิ่งแรกในเอกสาร _ใด ๆ_ ที่นี่ควรเป็น metadata: (Metadata หมายถึงข้อมูลที่อธิบายถึงความเป็นมาของข้อมูลนั้น ๆ) ```mdx --- title: เอกสารของฉัน description: นี่คือหน้าเกี่ยวกับทีมงานและอะไรบางอย่างเกี่ยวกับอากะตะ --- ``` ทุก ๆ หน้าควรมี title และ description สำหรับรายการแบบเต็มว่าใช้อะไรได้บ้างในระหว่าง `---` ลองดูที่ [เอกสาร Docusaurus](https://v2.docusaurus.io/docs/markdown-features#markdown-headers). ### หัวเรื่อง อย่าสร้างหัวข้อระดับ 1 (`<h1>`) ด้วย `#` ซึ่งมันจะสร้างขึ้น โดยอัตโนมัติ หัวข้อแรกของคุณ _ทุกครั้ง_ ควรเป็น `##` - ❌ ```md # หัวข้อของฉัน เอกสารนี้เกี่ยวกับ ... # หัวข้อย่อย ``` - ✔ ```md เอกสารนี้เกี่ยวกับ ... ## หัวข้อย่อย ``` ### ใช้ `โค้ด` สำหรับการอ้างอิงทางเทคนิค เมื่อเขียนย่อหน้าที่มี ชื่อฟังก์ชัน, ตัวเลข, นิพจน์ หรืออะไรก็ตามที่ไม่ใช่ภาษาเขียนมาตรฐานให้ล้อมรอบด้วย \`pBongWeed\` แบบนี้ ทำให้ง่ายต่อการแยกภาษาสำหรับอธิบายสิ่งต่าง ๆ จากการอ้างอิงถึงองค์ประกอบทางเทคนิคเช่น ชื่อฟังก์ชั่น และส่วนของโค้ด - ❌ > ฟังก์ชั่น fopen จะส่งค่ากลับมาพร้อมแท็กประเภท File: มันไม่มี ปัญหาอะไรในบรรทัดนั้นเนื่องจากค่าส่งกลับจะถูกเก็บไว้ในตัวแปรนั้นพร้อม แท็กประเภท File: (กรณีนี้ก็เช่นกัน) อย่างไรก็ตามใน บรรทัดถัดไปค่า 4 ได้ถูกเพิ่มเข้าไปในตัวควบคุมไฟล์ 4 ไม่มีแท็ก [...] - ✔ > ฟังก์ชั่น `fopen` จะส่งค่ากลับมาพร้อมแท็กประเภท `File:` มัน ปัญหาอะไรในบรรทัดนั้นเนื่องจากค่าส่งกลับจะถูกเก็บไว้ในตัวแปรนั้นพร้อม แท็กประเภท `File:` (กรณีนี้ก็เช่นกัน) อย่างไรก็ตามใน บรรทัดถัดไปค่า `4` ได้ถูกเพิ่มเข้าไปในตัวควบคุมไฟล์ `4` ไม่มีแท็ก ในตัวอย่างข้างต้น `fopen` คือชื่อฟังก์ชั่น ไม่ใช่ศัพท์ภาษาอังกฤษ ดังนั้นล้อมรอบด้วยเครื่องหมายตัวอย่าง `โค้ด` ช่วยแยกความแตกต่างจากเนื้อหาอื่น นอกจากนี้ หากย่อหน้านั้นอ้างอิงถึงโค้ดตัวอย่าง สิ่งนี้ก็สามารถช่วย ให้ผู้อ่านสามารถเชื่อมโยงความเข้าใจกับโค้ดได้ง่ายขึ้น ### ตาราง หากตารางนั้นมีหัวข้อ เขียนให้อยู่ในส่วนบนสุด: - ❌ ```md | | | | ------- | ----------------------------- | | สภาพ | สถานะเครื่องยนต์ | | 650 | ไม่มีความเสียหาย | | 650-550 | ควันขาว | | 550-390 | ควันเทา | | 390-250 | ควันดำ | | < 250 | ติดไฟ (จะระเบิดในวินาทีต่อมา) | ``` - ✔ ```md | สภาพ | สถานะเครื่องยนต์ | | ------- | ----------------------------- | | 650 | ไม่มีความเสียหาย | | 650-550 | ควันขาว | | 550-390 | ควันเทา | | 390-250 | ควันดำ | | < 250 | ติดไฟ (จะระเบิดในวินาทีต่อมา) | ``` ## การย้ายจาก SA-MP Wiki เนื้อหาส่วนใหญ่ได้ถูกย้ายแล้ว แต่หากคุณพบหน้าที่ขาดหายไป นี่คือคำแนะนำสั้น ๆ เกี่ยวกับการแปลงเนื้อหาเป็น Markdown ### รับไฟล์ HTML 1. คลิกปุ่มนี้ (Firefox) ![image](images/contributing/04f024579f8d.png) (Chrome) ![image](images/contributing/f62bb8112543.png) 2. หากเมาส์ที่ด้านบนซ้ายของหน้าหลักใน wiki ในมุมหรือขอบด้านซ้าย จนกว่าคุณจะเห็น `#content` ![image](images/contributing/65761ffbc429.png) หรือค้นหา `<div id=content>` ![image](images/contributing/77befe2749fd.png) 3. คัดลอกองค์ประกอบภายใน HTML นั้น ![image](images/contributing/8c7c75cfabad.png) ตอนนี้คุณมี _เพียง_ โค้ด HTML สำหรับ _เนื้อหา_ ที่เห็นของหน้านี้แล้ว เลือก สิ่งที่เราสนใจ และคุณสามารถแปลงมันเป็น Markdown ได้ ### แปลง HTML เป็น Markdown สำหรับการแปลงโค้ด HTML แบบพื้น ๆ (ไม่ใช่ตาราง) เป็น Markdown ใช้: https://domchristie.github.io/turndown/ ![image](images/contributing/77f4ea555bbb.png) ^^ สังเกตได้เลยว่าตอนนี้ มันทำตารางเละหมดแล้ว... ### ตาราง HTML เป็นตาราง Markdown เพราะเครื่องมือด้านบนไม่รองรับการแปลงตาราง ใช้เครื่องมือนี้: https://jmalarcon.github.io/markdowntables/ และคัดลอกแค่องค์ประกอบใน `<table>`: ![image](images/contributing/57f171ae0da7.png) ### ทำความสะอาด การแปลงมันไม่สมบูรณ์แบบ ดังนั้นคุณจะต้องแก้ไขด้วยตัวเองเล็กน้อย ส่วนขยายที่ทำการจัดรูปแบบด้านบนจะช่วยเหลือคุณ แต่คุณ ยังคงต้องใช้เวลาทำด้วยตัวเองอีกสักเล็กน้อย หากคุณไม่มีเวลา ไม่ต้องกังวลไป! ส่งแบบร่างที่ยังไม่เสร็จแล้วให้คนอื่นมาทำต่อ จากจุดที่คุณทำค้างไว้!
openmultiplayer/web/docs/translations/th/meta/Contributing.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/meta/Contributing.md", "repo_id": "openmultiplayer", "token_count": 10799 }
405
--- title: OnPlayerCommandText description: This callback is called when a player enters a command into the client chat window. tags: ["player"] --- ## คำอธิบาย This callback is called when a player enters a command into the client chat window. Commands are anything that start with a forward slash, e.g. /help. | Name | Description | | --------- | ----------------------------------------------------------- | | playerid | The ID of the player that entered a command. | | cmdtext[] | The command that was entered (including the forward slash). | ## ส่งคืน It is always called first in filterscripts so returning 1 there blocks other scripts from seeing it. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/help", true)) { SendClientMessage(playerid, -1, "SERVER: This is the /help command!"); return 1; // Returning 1 informs the server that the command has been processed. // OnPlayerCommandText won't be called in other scripts. } return 0; // Returning 0 informs the server that the command hasn't been processed by this script. // OnPlayerCommandText will be called in other scripts until one returns 1. // If no scripts return 1, the 'SERVER: Unknown Command' message will be shown to the player. } ``` ## บันทึก :::tip NPC สามารถเรียก Callback นี้ได้ ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SendRconCommand](../../scripting/functions/SendRconCommand.md): Sends an RCON command via the script.
openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerCommandText.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerCommandText.md", "repo_id": "openmultiplayer", "token_count": 633 }
406
--- title: OnPlayerLeaveCheckpoint description: This callback is called when a player leaves the checkpoint set for them by SetPlayerCheckpoint. tags: ["player", "checkpoint"] --- ## คำอธิบาย This callback is called when a player leaves the checkpoint set for them by SetPlayerCheckpoint. Only one checkpoint can be set at a time. | Name | Description | | -------- | ------------------------------------------------ | | playerid | The ID of the player that left their checkpoint. | ## ส่งคืน มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ ## ตัวอย่าง ```c public OnPlayerLeaveCheckpoint(playerid) { printf("Player %i left a checkpoint!", playerid); return 1; } ``` ## บันทึก :::tip NPC สามารถเรียก Callback นี้ได้ ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetPlayerCheckpoint](../../scripting/functions/SetPlayerCheckpoint.md): Create a checkpoint for a player. - [DisablePlayerCheckpoint](../../scripting/functions/DisablePlayerCheckpoint.md): Disable the player's current checkpoint. - [IsPlayerInCheckpoint](../../scripting/functions/IsPlayerInRaceCheckpoint.md): Check if a player is in a checkpoint. - [SetPlayerRaceCheckpoint](../../scripting/functions/SetPlayerRaceCheckpoint.md): Create a race checkpoint for a player. - [DisablePlayerRaceCheckpoint](../../scripting/functions/DisablePlayerRaceCheckpoint.md): Disable the player's current race checkpoint. - [IsPlayerInRaceCheckpoint](../../scripting/functions/IsPlayerInRaceCheckpoint.md): Check if a player is in a race checkpoint.
openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerLeaveCheckpoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerLeaveCheckpoint.md", "repo_id": "openmultiplayer", "token_count": 642 }
407
--- title: OnPlayerWeaponShot description: This callback is called when a player fires a shot from a weapon. tags: ["player"] --- ## คำอธิบาย This callback is called when a player fires a shot from a weapon. Only bullet weapons are supported. Only passenger drive-by is supported (not driver drive-by, and not sea sparrow / hunter shots). | Name | Description | |-------------------------|-----------------------------------------------------------------------------------------------------------| | playerid | The ID of the player that shot a weapon. | | WEAPON:weaponid | The ID of the [weapon](../resources/weaponids) shot by the player. | | BULLET_HIT_TYPE:hittype | The [type](../resources/bullethittypes) of thing the shot hit (none, player, vehicle, or (player)object). | | hitid | The ID of the player, vehicle or object that was hit. | | Float:fX | The X coordinate that the shot hit. | | Float:fY | The Y coordinate that the shot hit. | | Float:fZ | The Z coordinate that the shot hit. | ## ส่งคืน 0 - Prevent the bullet from causing damage. 1 - Allow the bullet to cause damage. It is always called first in filterscripts so returning 0 there also blocks other scripts from seeing it. ## ตัวอย่าง ```c public OnPlayerWeaponShot(playerid, WEAPON:weaponid, BULLET_HIT_TYPE:hittype, hitid, Float:fX, Float:fY, Float:fZ) { new szString[144]; format(szString, sizeof(szString), "Weapon %i fired. hittype: %i hitid: %i pos: %f, %f, %f", weaponid, hittype, hitid, fX, fY, fZ); SendClientMessage(playerid, -1, szString); return 1; } ``` ## บันทึก :::tip This callback is only called when lag compensation is enabled. If hittype is: - `BULLET_HIT_TYPE_NONE`: the fX, fY and fZ parameters are normal coordinates, will give 0.0 for coordinates if nothing was hit (e.g. far object that the bullet can't reach); - Others: the fX, fY and fZ are offsets relative to the hitid. ::: :::tip [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors) can be used in this callback for more detailed bullet vector information. ::: :::warning Known Bug(s): - Isn't called if you fired in vehicle as driver or if you are looking behind with the aim enabled (shooting in air). - It is called as `BULLET_HIT_TYPE_VEHICLE` with the correct `hitid` (the hit player's vehicleid) if you are shooting a player which is in a vehicle. It won't be called as `BULLET_HIT_TYPE_PLAYER` at all. - Partially fixed in SA-MP 0.3.7: If fake weapon data is sent by a malicious user, other player clients may freeze or crash. To combat this, check if the reported weaponid can actually fire bullets. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors): Retrieves the vector of the last shot a player fired.
openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerWeaponShot.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerWeaponShot.md", "repo_id": "openmultiplayer", "token_count": 1501 }
408
--- title: AddMenuItem description: Adds an item to a specified menu. tags: ["menu"] --- ## คำอธิบาย Adds an item to a specified menu. | Name | Description | | ------- | -------------------------------- | | menuid | The menu id to add an item to. | | column | The column to add the item to. | | title[] | The title for the new menu item. | ## ส่งคืน The index of the row this item was added to. ## ตัวอย่าง ```c new Menu:examplemenu; public OnGameModeInit() { examplemenu = CreateMenu("Your Menu", 2, 200.0, 100.0, 150.0, 150.0); AddMenuItem(examplemenu, 0, "item 1"); AddMenuItem(examplemenu, 0, "item 2"); return 1; } ``` ## บันทึก :::tip Crashes when passed an invalid menu ID. You can only have 12 items per menu (13th goes to the right side of the header of column name (colored), 14th and higher not display at all). You can only use 2 columns (0 and 1). You can only add 8 color codes per one item (~r~, ~g~ etc.). Maximum length of menu item is 31 symbols. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [CreateMenu](../../scripting/functions/CreateMenu.md): Create a menu. - [SetMenuColumnHeader](../../scripting/functions/SetMenuColumnHeader.md): Set the header for one of the columns in a menu. - [DestroyMenu](../../scripting/functions/DestroyMenu.md): Destroy a menu. - [OnPlayerSelectedMenuRow](../../scripting/callbacks/OnPlayerSelectedMenuRow.md): Called when a player selected a row in a menu. - [OnPlayerExitedMenu](../../scripting/callbacks/OnPlayerExitedMenu.md): Called when a player exits a menu.
openmultiplayer/web/docs/translations/th/scripting/functions/AddMenuItem.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/AddMenuItem.md", "repo_id": "openmultiplayer", "token_count": 606 }
409
--- title: AttachCameraToObject description: You can use this function to attach the player camera to objects. tags: [] --- ## คำอธิบาย You can use this function to attach the player camera to objects. | Name | Description | | -------- | -------------------------------------------------------------------- | | playerid | The ID of the player which will have your camera attached on object. | | objectid | The object id which you want to attach the player camera. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/attach", false)) { new object = CreateObject(1245, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0); AttachCameraToObject(playerid, object); SendClientMessage(playerid, 0xFFFFFFAA, "Your camera is attached on object now."); return 1; } return 0; } ``` ## บันทึก :::tip You need to create the object first, before attempting to attach a player camera for that. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [AttachCameraToPlayerObject](../../scripting/functions/AttachCameraToPlayerObjecy.md): Attaches the player's camera to a player object.
openmultiplayer/web/docs/translations/th/scripting/functions/AttachCameraToObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/AttachCameraToObject.md", "repo_id": "openmultiplayer", "token_count": 538 }
410
--- title: ChangeVehiclePaintjob description: Change a vehicle's paintjob (for plain colors see ChangeVehicleColor). tags: ["vehicle"] --- ## คำอธิบาย Change a vehicle's paintjob (for plain colors see ChangeVehicleColor). | Name | Description | | ---------- | ------------------------------------------------------------ | | vehicleid | The ID of the vehicle to change the paintjob of. | | paintjobid | The ID of the Paintjob to apply. Use 3 to remove a paintjob. | ## ส่งคืน This function always returns 1 (success), even if the vehicle passed is not created. ## ตัวอย่าง ```c new rand = random(3); // Will either be 0 1 or 2 (all valid) ChangeVehiclePaintjob(GetPlayerVehicleID(playerid), rand); // changes the paintjob of the player's current vehicle to a random one ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [ChangeVehicleColor](../../scripting/functions/ChangeVehicleColor.md): Set the color of a vehicle. - [OnVehiclePaintjob](../../scripting/callbacks/OnVehiclePaintjob.md): Called when a vehicle's paintjob is changed.
openmultiplayer/web/docs/translations/th/scripting/functions/ChangeVehiclePaintjob.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ChangeVehiclePaintjob.md", "repo_id": "openmultiplayer", "token_count": 442 }
411
--- title: DeletePVar description: Deletes a previously set player variable. tags: ["pvar"] --- ## คำอธิบาย Deletes a previously set player variable. | Name | Description | | -------- | ----------------------------------------------------- | | playerid | The ID of the player whose player variable to delete. | | varname | The name of the player variable to delete. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. Either the player specified isn't connected or there is no variable set with the given name. ## ตัวอย่าง ```c SetPVarInt(playerid, "SomeVarName", 69); // Later on, when the variable is no longer needed... DeletePVar(playerid, "SomeVarName"); ``` ## บันทึก :::tip Once a variable is deleted, attempts to retrieve the value will return 0 (for integers and floats and NULL for strings. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetPVarInt](../../scripting/functions/SetPVarInt.md): Set an integer for a player variable. - [GetPVarInt](../../scripting/functions/GetPVarInt.md): Get the previously set integer from a player variable. - [SetPVarString](../../scripting/functions/SetPVarString.md): Set a string for a player variable. - [GetPVarString](../../scripting/functions/GetPVarString.md): Get the previously set string from a player variable. - [SetPVarFloat](../../scripting/functions/SetPVarFloat.md): Set a float for a player variable. - [GetPVarFloat](../../scripting/functions/GetPVarFloat.md): Get the previously set float from a player variable.
openmultiplayer/web/docs/translations/th/scripting/functions/DeletePVar.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/DeletePVar.md", "repo_id": "openmultiplayer", "token_count": 586 }
412
--- title: DisableRemoteVehicleCollisions description: Disables collisions between occupied vehicles for a player. tags: ["vehicle"] --- :::warning ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้! ::: ## คำอธิบาย Disables collisions between occupied vehicles for a player. | Name | Description | | -------- | ------------------------------------------------------------- | | playerid | The ID of the player for whom you want to disable collisions. | | disable | 1 to disable collisions, 0 to enable collisions. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. The player specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/collision", true)) { new string[64]; format(string, sizeof(string), "Vehicle collision for you is now '%s'", (GetPVarInt(playerid, "vehCollision") != 1) ? ("Disabled") : ("Enabled")); SendClientMessage(playerid, 0xFFFFFFFF, string); SetPVarInt(playerid, "vehCollision", !GetPVarInt(playerid, "vehCollision")); DisableRemoteVehicleCollisions(playerid, GetPVarInt(playerid, "vehCollision")); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน
openmultiplayer/web/docs/translations/th/scripting/functions/DisableRemoteVehicleCollisions.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/DisableRemoteVehicleCollisions.md", "repo_id": "openmultiplayer", "token_count": 669 }
413
--- title: GangZoneCreate description: Create a gangzone (colored radar area). tags: ["gangzone"] --- ## คำอธิบาย Create a gangzone (colored radar area). | Name | Description | | ---- | ---------------------------------------------------- | | minx | The X coordinate for the west side of the gangzone. | | miny | The Y coordinate for the south side of the gangzone. | | maxx | The X coordinate for the east side of the gangzone. | | maxy | The Y coordinate for the north side of the gangzone. | ## ส่งคืน The ID of the created zone, returns -1 if not created ## ตัวอย่าง ```c new gangzone; gangzone = GangZoneCreate(1248.011, 2072.804, 1439.348, 2204.319); ``` ``` MinY v MinX > *------------- | | | gangzone | | center | | | -------------* < MaxX ^ MaxY ``` ## บันทึก :::tip This function merely CREATES the gangzone, you must use GangZoneShowForPlayer or GangZoneShowForAll to show it. ::: :::warning There is a limit of 1024 gangzones. Putting the parameters in the wrong order results in glitchy behavior. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GangZoneDestroy](../functions/GangZoneDestroy): Destroy a gangzone. - [GangZoneShowForPlayer](../functions/GangZoneShowForPlayer): Show a gangzone for a player. - [GangZoneShowForAll](../functions/GangZoneShowForAll): Show a gangzone for all players. - [GangZoneHideForPlayer](../functions/GangZoneHideForPlayer): Hide a gangzone for a player. - [GangZoneHideForAll](../functions/GangZoneHideForAll): Hide a gangzone for all players. - [GangZoneFlashForPlayer](../functions/GangZoneFlashForPlayer): Make a gangzone flash for a player. - [GangZoneFlashForAll](../functions/GangZoneFlashForAll): Make a gangzone flash for all players. - [GangZoneStopFlashForPlayer](../functions/GangZoneStopFlashForPlayer): Stop a gangzone flashing for a player. - [GangZoneStopFlashForAll](../functions/GangZoneStopFlashForAll): Stop a gangzone flashing for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/GangZoneCreate.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GangZoneCreate.md", "repo_id": "openmultiplayer", "token_count": 897 }
414
--- title: GetConsoleVarAsBool description: Get the boolean value of a console variable. tags: [] --- ## คำอธิบาย Get the boolean value of a console variable. | Name | Description | | --------------- | ----------------------------------------------------- | | const varname[] | The name of the boolean variable to get the value of. | ## ส่งคืน The value of the specified console variable. 0 if the specified console variable is not a boolean or doesn't exist. ## ตัวอย่าง ```c public OnGameModeInit() { new queryEnabled = GetConsoleVarAsBool("query"); if (!queryEnabled) { print("WARNING: Querying is disabled. The server will appear offline in the server browser."); } return 1; } ``` ## บันทึก :::tip Type 'varlist' in the server console to display a list of available console variables and their types. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GetConsoleVarAsString](../functions/GetConsoleVarAsString): Retreive a server variable as a string. - [GetConsoleVarAsInt](../functions/GetConsoleVarAsInt): Retreive a server variable as an integer.
openmultiplayer/web/docs/translations/th/scripting/functions/GetConsoleVarAsBool.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetConsoleVarAsBool.md", "repo_id": "openmultiplayer", "token_count": 462 }
415
--- title: GetPlayerAmmo description: Gets the amount of ammo in a player's current weapon. tags: ["player"] --- ## คำอธิบาย Gets the amount of ammo in a player's current weapon. | Name | Description | | -------- | --------------------------------------- | | playerid | The ID of the player whose ammo to get. | ## ส่งคืน The amount of ammo in the player's current weapon. ## ตัวอย่าง ```c ShowPlayerAmmo(playerid) { new ammo = GetPlayerAmmo(playerid); new infoString[16]; format(infoString, sizeof(infoString), "Ammo: %i", ammo); SendClientMessage(playerid, -1, infoString); } ``` ## บันทึก :::warning The ammo can hold 16-bit values, therefore values over 32767 will return erroneous values. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetPlayerAmmo](../functions/SetPlayerAmmo): Set the ammo of a specific player's weapon. - [GetPlayerWeaponData](../functions/GetPlayerWeaponData): Find out information about weapons a player has.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerAmmo.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerAmmo.md", "repo_id": "openmultiplayer", "token_count": 424 }
416
--- title: GetPlayerDistanceFromPoint description: Calculate the distance between a player and a map coordinate. tags: ["player"] --- ## คำอธิบาย Calculate the distance between a player and a map coordinate. | Name | Description | | -------- | ---------------------------------------------------- | | playerid | The ID of the player to calculate the distance from. | | Float:X | The X map coordinate. | | Float:Y | The Y map coordinate. | | Float:Z | The Z map coordinate. | ## ส่งคืน The distance between the player and the point as a float. ## ตัวอย่าง ```c /* when the player types '/vend' into the chat box, they'll see this.*/ public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/vend", true) == 0) { new Float: fDistance = GetPlayerDistanceFromPoint(playerid, 237.9, 115.6, 1010.2), szMessage[44]; format(szMessage, sizeof(szMessage), "You're %0.2f meters away from the vending machine.", fDistance); SendClientMessage(playerid, 0xA9C4E4FF, szMessage); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [IsPlayerInRangeOfPoint](../functions/IsPlayerInRangeOfPoint): Check whether a player is in range of a point. - [GetVehicleDistanceFromPoint](../functions/GetVehicleDistanceFromPoint): Get the distance between a vehicle and a point. - [GetPlayerPos](../functions/GetPlayerPos): Get a player's position.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerDistanceFromPoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerDistanceFromPoint.md", "repo_id": "openmultiplayer", "token_count": 694 }
417
--- title: GetPlayerObjectRot description: Use this function to get the object's current rotation. tags: ["player"] --- ## คำอธิบาย Use this function to get the object's current rotation. The rotation is saved by reference in three RotX/RotY/RotZ variables. | Name | Description | | -------- | ------------------------------------------------------------- | | playerid | The player you associated this object to. | | objectid | The objectid of the object you want to get the rotation from. | | &Float:X | The variable to store the X rotation, passed by reference. | | &Float:Y | The variable to store the Y rotation, passed by reference. | | &Float:Z | The variable to store the Z rotation, passed by reference. | ## ส่งคืน The object's rotation is stored in the specified variables. ## ตัวอย่าง ```c GetPlayerObjectRot(playerid, objectid, RotX, RotY, RotZ); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - CreatePlayerObject: Create an object for only one player. - DestroyPlayerObject: Destroy a player object. - IsValidPlayerObject: Checks if a certain player object is vaild. - MovePlayerObject: Move a player object. - StopPlayerObject: Stop a player object from moving. - SetPlayerObjectPos: Set the position of a player object. - SetPlayerObjectRot: Set the rotation of a player object. - GetPlayerObjectPos: Locate a player object. - AttachPlayerObjectToPlayer: Attach a player object to a player. - CreateObject: Create an object. - DestroyObject: Destroy an object. - IsValidObject: Checks if a certain object is vaild. - MoveObject: Move an object. - StopObject: Stop an object from moving. - SetObjectPos: Set the position of an object. - SetObjectRot: Set the rotation of an object. - GetObjectPos: Locate an object. - GetObjectRot: Check the rotation of an object. - AttachObjectToPlayer: Attach an object to a player.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerObjectRot.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerObjectRot.md", "repo_id": "openmultiplayer", "token_count": 653 }
418
--- title: GetPlayerVelocity description: Get the velocity (speed) of a player on the X, Y and Z axes. tags: ["player"] --- ## คำอธิบาย Get the velocity (speed) of a player on the X, Y and Z axes. | Name | Description | | -------- | ----------------------------------------------------------------------------------- | | playerid | The player to get the speed from. | | &Float:x | A float variable in which to store the velocity on the X axis, passed by reference. | | &Float:y | A float variable in which to store the velocity on the Y axis, passed by reference. | | &Float:z | A float variable in which to store the velocity on the Z axis, passed by reference. | ## ส่งคืน The function itself doesn't return a specific value. The X, Y and Z velocities are stored in the specified variables. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp("/velocity", cmdtext)) { new Float:Velocity[3], string[80]; GetPlayerVelocity(playerid, Velocity[0], Velocity[1], Velocity[2]); format(string, sizeof(string), "You are going at a velocity of X: %f, Y: %f, Z: %f", Velocity[0], Velocity[1], Velocity[2]); SendClientMessage(playerid, 0xFFFFFFFF, string); return 1; } } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerVelocity: Set a player's velocity. - SetVehicleVelocity: Set a vehicle's velocity. - GetVehicleVelocity: Get a vehicle's velocity.
openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerVelocity.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerVelocity.md", "repo_id": "openmultiplayer", "token_count": 647 }
419
--- title: GetVehicleTrailer description: Get the ID of the trailer attached to a vehicle. tags: ["vehicle"] --- ## คำอธิบาย Get the ID of the trailer attached to a vehicle. | Name | Description | | --------- | -------------------------------------------- | | vehicleid | The ID of the vehicle to get the trailer of. | ## ส่งคืน The vehicle ID of the trailer or 0 if no trailer is attached. ## ตัวอย่าง ```c new trailerid = GetVehicleTrailer(vehicleid); DetachTrailerFromVehicle(trailerid); ``` ## บันทึก :::warning This function does not work for trains. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - AttachTrailerToVehicle: Attach a trailer to a vehicle. - DetachTrailerFromVehicle: Detach a trailer from a vehicle. - IsTrailerAttachedToVehicle: Check if a trailer is attached to a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleTrailer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleTrailer.md", "repo_id": "openmultiplayer", "token_count": 370 }
420
--- title: IsPlayerConnected description: Checks if a player is connected (if an ID is taken by a connected player). tags: ["player"] --- ## คำอธิบาย Checks if a player is connected (if an ID is taken by a connected player). | Name | Description | | -------- | ------------------------------ | | playerid | The ID of the player to check. | ## ส่งคืน 0: Player is NOT connected. 1: Player IS connected. ## ตัวอย่าง ```c KillPlayer(playerid) { if (!IsPlayerConnected(playerid)) { printf("Player ID %i is not connected!", playerid); } else { SetPlayerHealth(playerid, 0); } } ``` ## บันทึก :::tip This function can be omitted in a lot of cases. Many other functions already have some sort of connection check built in. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [IsPlayerAdmin](../../scripting/functions/IsPlayerAdmin.md): Checks if a player is logged into RCON. - [OnPlayerConnect](../../scripting/callbacks/OnPlayerConnect.md): Called when a player connects to the server. - [OnPlayerDisconnect](../../scripting/callbacks/OnPlayerDisconnect.md): Called when a player leaves the server.
openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerConnected.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerConnected.md", "repo_id": "openmultiplayer", "token_count": 475 }
421
--- title: KillTimer description: Kills (stops) a running timer. tags: [] --- ## คำอธิบาย Kills (stops) a running timer. | Name | Description | | ------- | ----------------------------------------------------------------- | | timerid | The ID of the timer to kill (returned by SetTimer or SetTimerEx). | ## ส่งคืน This function always returns 0. ## ตัวอย่าง ```c new connect_timer[MAX_PLAYERS]; public OnPlayerConnect(playerid) { print("Starting timer..."); connect_timer[playerid] = SetTimerEx("WelcomeTimer", 5000, true, "i", playerid); return 1; } public OnPlayerDisconnect(playerid) { KillTimer(connect_timer[playerid]); return 1; } forward WelcomeTimer(playerid); public WelcomeTimer(playerid) { SendClientMessage(playerid, -1, "Welcome!"); } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [SetTimer](../../scripting/functions/SetTimer.md): Set a timer. - [SetTimerEx](../../scripting/functions/SetTimerEx.md): Set a timer with parameters.
openmultiplayer/web/docs/translations/th/scripting/functions/KillTimer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/KillTimer.md", "repo_id": "openmultiplayer", "token_count": 455 }
422
--- title: PlayAudioStreamForPlayer description: Play an 'audio stream' for a player. tags: ["player"] --- :::warning This function was added in SA-MP 0.3d and will not work in earlier versions! ::: ## คำอธิบาย Play an 'audio stream' for a player. Normal audio files also work (e.g. MP3). | Name | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------- | | playerid | The ID of the player to play the audio for. | | url[] | The url to play. Valid formats are mp3 and ogg/vorbis. A link to a .pls (playlist) file will play that playlist. | | Float:PosX | The X position at which to play the audio. Default 0.0. Has no effect unless usepos is set to 1. | | Float:PosY | The Y position at which to play the audio. Default 0.0. Has no effect unless usepos is set to 1. | | Float:PosZ | The Z position at which to play the audio. Default 0.0. Has no effect unless usepos is set to 1. | | Float:distance | The distance over which the audio will be heard. Has no effect unless usepos is set to 1. | | usepos | Use the positions and distance specified. Default disabled (0). | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. The player specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp("/radio", cmdtext, true) == 0) { PlayAudioStreamForPlayer(playerid, "http://somafm.com/tags.pls"); return 1; } if (strcmp("/radiopos", cmdtext, true) == 0) { new Float:X, Float:Y, Float:Z, Float:Distance = 5.0; GetPlayerPos(playerid, X, Y, Z); PlayAudioStreamForPlayer(playerid, "http://somafm.com/tags.pls", X, Y, Z, Distance, 1); return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - StopAudioStreamForPlayer: Stops the current audio stream for a player. - PlayerPlaySound: Play a sound for a player.
openmultiplayer/web/docs/translations/th/scripting/functions/PlayAudioStreamForPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayAudioStreamForPlayer.md", "repo_id": "openmultiplayer", "token_count": 1044 }
423
--- title: PlayerTextDrawSetPreviewVehCol description: Set the color of a vehicle in a player-textdraw model preview (if a vehicle is shown). tags: ["player", "textdraw", "playertextdraw"] --- ## คำอธิบาย Set the color of a vehicle in a player-textdraw model preview (if a vehicle is shown). | Name | Description | | -------- | ----------------------------------------------------- | | playerid | The ID of the player whose player-textdraw to change. | | text | The ID of the player's player-textdraw to change. | | color1 | The color to set the vehicle's primary color to. | | color2 | The color to set the vehicle's secondary color to. | ## ส่งคืน This function does not return any specific values. ## บันทึก :::warning The textdraw MUST use the font TEXT_DRAW_FONT_MODEL_PREVIEW and be showing a vehicle in order for this function to have effect. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - PlayerTextDrawSetPreviewModel: Set model ID of a 3D player textdraw preview. - PlayerTextDrawSetPreviewRot: Set rotation of a 3D player textdraw preview. - PlayerTextDrawFont: Set the font of a player-textdraw. - OnPlayerClickPlayerTextDraw: Called when a player clicks on a player-textdraw.
openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawSetPreviewVehCol.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawSetPreviewVehCol.md", "repo_id": "openmultiplayer", "token_count": 470 }
424
--- title: ResetPlayerWeapons description: Removes all weapons from a player. tags: ["player"] --- ## คำอธิบาย Removes all weapons from a player. | Name | Description | | -------- | --------------------------------------------- | | playerid | The ID of the player whose weapons to remove. | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. This means the player specified does not exist. ## ตัวอย่าง ```c public OnPlayerDeath(playerid, killerid, WEAPON:reason) { // Remove the killer's weapons ResetPlayerWeapons(killerid); return 1; } ``` ## บันทึก :::tip To remove individual weapons from a player, set their ammo to 0 using SetPlayerAmmo. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [GivePlayerWeapon](../functions/GivePlayerWeapon.md): Give a player a weapon. - [GetPlayerWeapon](../functions/GetPlayerWeapon.md): Check what weapon a player is currently holding.
openmultiplayer/web/docs/translations/th/scripting/functions/ResetPlayerWeapons.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ResetPlayerWeapons.md", "repo_id": "openmultiplayer", "token_count": 399 }
425
--- title: SetCameraBehindPlayer description: Restore the camera to a place behind the player, after using a function like SetPlayerCameraPos. tags: ["player"] --- ## คำอธิบาย Restore the camera to a place behind the player, after using a function like SetPlayerCameraPos. | Name | Description | | -------- | ---------------------------------------------- | | playerid | The player you want to restore the camera for. | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. This means the player specified does not exist. ## ตัวอย่าง ```c SetCameraBehindPlayer(playerid); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerCameraPos: Set a player's camera position. - SetPlayerCameraLookAt: Set where a player's camera should face.
openmultiplayer/web/docs/translations/th/scripting/functions/SetCameraBehindPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetCameraBehindPlayer.md", "repo_id": "openmultiplayer", "token_count": 320 }
426
--- title: SetPlayerArmedWeapon description: Sets which weapon (that a player already has) the player is holding. tags: ["player"] --- ## คำอธิบาย Sets which weapon (that a player already has) the player is holding. | Name | Description | | -------- | ---------------------------------------------------------- | | playerid | The ID of the player to arm with a weapon. | | weaponid | The ID of the weapon that the player should be armed with. | ## ส่งคืน 1: The function was executed successfully. Success is returned even when the function fails to execute (the player doesn't have the weapon specified, or it is an invalid weapon). 0: The function failed to execute. The player is not connected. ## ตัวอย่าง ```c public OnPlayerUpdate(playerid) { SetPlayerArmedWeapon(playerid,0); // disables weapons return 1; } // SMG driveby by [03]Garsino public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate) { if (newstate == PLAYER_STATE_DRIVER || newstate == PLAYER_STATE_PASSENGER) { new weapon, ammo; GetPlayerWeaponData(playerid, 4, weapon, ammo); // Get the players SMG weapon in slot 4 SetPlayerArmedWeapon(playerid, weapon); // Set the player to driveby with SMG } return 1; } ``` ## บันทึก :::tip This function arms a player with a weapon they already have; it does not give them a new weapon. See GivePlayerWeapon. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GivePlayerWeapon: Give a player a weapon. - GetPlayerWeapon: Check what weapon a player is currently holding.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerArmedWeapon.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerArmedWeapon.md", "repo_id": "openmultiplayer", "token_count": 626 }
427
--- title: SetPlayerName description: Sets the name of a player. tags: ["player"] --- ## คำอธิบาย Sets the name of a player. | Name | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------ | | playerid | The ID of the player to set the name of. | | const name[] | The name to set. Must be 1-24 characters long and only contain valid characters (0-9, a-z, A-Z, [], (), \$ @ . \_ and = only). | ## ส่งคืน 1 The name was changed successfully 0 The player already has that name -1 The name can not be changed (it's already in use, too long or has invalid characters) ## ตัวอย่าง ```c // Command simply sets the player's name to to "Superman" if possible, with no error checking or messages. if (strcmp(cmdtext, "/superman", true) == 0) { SetPlayerName(playerid, "Superman"); return 1; } // Command sets the players name to "Superman" if possible, informs the player of // any errors using a "switch" statement. if (strcmp(cmdtext, "/superman", true) == 0) { switch (SetPlayerName(playerid, "Superman")) { case -1: { SendClientMessage(playerid, 0xFF0000FF, "Unable to change your name, someone else is known as 'Superman' already."); } case 0: { SendClientMessage(playerid, 0xFF0000FF, "You are already known as 'Superman'"); } case 1: { SendClientMessage(playerid, 0x00FF00FF, "You are now known as 'Superman'"); } } return 1; } ``` ## บันทึก :::warning Changing the players' name to the same name but with different character cases (e.g. "John" to "JOHN") will not work. If used in OnPlayerConnect, the new name will not be shown for the connecting player. Passing a null string as the new name will crash the server. Player names can be up to 24 characters when using this function, but when joining the server from the SA-MP server browser, players' names must be no more than 20 and less than 3 characters (the server will deny entry). This allows for 4 characters extra when using SetPlayerName. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetPlayerName: Get a player's name.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerName.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerName.md", "repo_id": "openmultiplayer", "token_count": 1014 }
428
--- title: SetPlayerVelocity description: Set a player's velocity on the X, Y and Z axes. tags: ["player"] --- ## คำอธิบาย Set a player's velocity on the X, Y and Z axes. | Name | Description | | -------- | ----------------------------------- | | playerid | The player to apply the speed to. | | Float:X | The velocity (speed) on the X axis. | | Float:Y | The velocity (speed) on the Y axis. | | Float:Z | The velocity (speed) on the Z axis. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. This means the player is not connected. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp("/jump", cmdtext)) { SetPlayerVelocity(playerid, 0.0, 0.0, 0.2); // Forces the player to jump (Z velocity + 0.2) return 1; } return 0; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetPlayerVelocity: Get a player's velocity. - SetVehicleVelocity: Set a vehicle's velocity. - GetVehicleVelocity: Get a vehicle's velocity.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerVelocity.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerVelocity.md", "repo_id": "openmultiplayer", "token_count": 444 }
429
--- title: SetVehicleParamsCarWindows description: Allows you to open and close the windows of a vehicle. tags: ["vehicle"] --- :::warning ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้! ::: ## คำอธิบาย Allows you to open and close the windows of a vehicle. | Name | Description | | --------- | ------------------------------------------------------------------------- | | vehicleid | The ID of the vehicle to set the window state of | | driver | The state of the driver's window. 0 to open, 1 to close. | | passenger | The state of the passenger window. 0 to open, 1 to close. | | backleft | The state of the rear left window (if available). 0 to open, 1 to close. | | backright | The state of the rear right window (if available). 0 to open, 1 to close. | ## ส่งคืน [edit] ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetVehicleParamsCarDoors: Open and close the doors of a vehicle. - GetVehicleParamsCarDoors: Retrive the current state of a vehicle's doors. - GetVehicleParamsCarWindows: Retrive the current state of a vehicle's windows
openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleParamsCarWindows.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleParamsCarWindows.md", "repo_id": "openmultiplayer", "token_count": 595 }
430
--- title: StartRecordingPlayerData description: Starts recording a player's movements to a file, which can then be reproduced by an NPC. tags: ["player"] --- ## คำอธิบาย Starts recording a player's movements to a file, which can then be reproduced by an NPC. | Name | Description | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | playerid | The ID of the player to record. | | recordtype | The [type](../resources/recordtypes.md) of recording. | | recordname[] | The name of the file which will hold the recorded data. It will be saved in the scriptfiles directory, with an automatically added .rec extension, you will need to move the file to npcmodes/recordings to use for playback. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c if (!strcmp("/recordme", cmdtext)) { if (GetPlayerState(playerid) == PLAYER_STATE_ONFOOT) { StartRecordingPlayerData(playerid, PLAYER_RECORDING_TYPE_ONFOOT, "MyFile"); } else if (GetPlayerState(playerid) == PLAYER_STATE_DRIVER) { StartRecordingPlayerData(playerid, PLAYER_RECORDING_TYPE_DRIVER, "MyFile"); } SendClientMessage(playerid, 0xFFFFFFFF, "All your movements are now being recorded!"); return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [StopRecordingPlayerData](../functions/StopRecordingPlayerData.md): Stops recording player data.
openmultiplayer/web/docs/translations/th/scripting/functions/StartRecordingPlayerData.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/StartRecordingPlayerData.md", "repo_id": "openmultiplayer", "token_count": 1093 }
431
--- title: TextDrawSetOutline description: Sets the thickness of a textdraw's text's outline. tags: ["textdraw"] --- ## คำอธิบาย Sets the thickness of a textdraw's text's outline. TextDrawBackgroundColor can be used to change the color. | Name | Description | | ---- | -------------------------------------------------------------- | | text | The ID of the text draw to set the outline thickness of. | | size | The thickness of the outline, as an integer. 0 for no outline. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new Text:MyTextdraw; public OnGameModeInit() { MyTextDraw = TextDrawCreate(100.0, 33.0, "Example TextDraw"); TextDrawSetOutline(MyTextDraw, 1); return 1; } ``` ## บันทึก :::tip If you want to change the outline of a textdraw that is already shown, you don't have to recreate it. Simply use TextDrawShowForPlayer/TextDrawShowForAll after modifying the textdraw and the change will be visible. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw. - [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw. - [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw. - [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw. - [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw. - [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw. - [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw. - [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw. - [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box. - [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw. - [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio. - [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not. - [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw. - [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player. - [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players. - [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetOutline.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetOutline.md", "repo_id": "openmultiplayer", "token_count": 924 }
432
--- title: UnBlockIpAddress description: Unblock an IP address that was previously blocked using BlockIpAddress. tags: [] --- ## คำอธิบาย Unblock an IP address that was previously blocked using BlockIpAddress. | Name | Description | | ---------- | -------------------------- | | ip_address | The IP address to unblock. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c public OnGameModeInit() { UnBlockIpAddress("127.0.0.1"); return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [BlockIpAddress](../functions/BlockIpAddress.md): Block an IP address from connecting to the server for a set amount of time. - [OnIncomingConnection](../callbacks/OnIncomingConnection.md): Called when a player is attempting to connect to the server.
openmultiplayer/web/docs/translations/th/scripting/functions/UnBlockIpAddress.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/UnBlockIpAddress.md", "repo_id": "openmultiplayer", "token_count": 334 }
433
--- title: fblockwrite description: Write data to a file in binary format, while ignoring line brakes and encoding. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Write data to a file in binary format, while ignoring line brakes and encoding. | Name | Description | | -------------------- | ------------------------------------------ | | handle | The File handle to use, opened by fopen(). | | const buffer[] | The data to write to the file. | | size = sizeof buffer | The number of cells to write. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c // Define "some_enum" enum _:some_enum { some_data1, some_data2[20], Float:some_data3 } // Declare "some_data" new some_data[some_enum]; // ... // Open "file.bin" in "write only" mode new File:handle = fopen("file.bin", io_write); // Check, if "file.bin" is open if (handle) { // Success // Write "some_data" into "file.bin" fblockwrite(handle, some_data); // Close "file.bin" fclose(handle); } else { // Error print("Failed to open \"file.bin\"."); } ``` ## บันทึก :::warning Using an invalid handle will crash your server! Get a valid handle by using fopen or ftemp. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [fopen](../functions/fopen): Open a file. - [fclose](../functions/fclose): Close a file. - [ftemp](../functions/ftemp): Create a temporary file stream. - [fremove](../functions/fremove): Remove a file. - [fwrite](../functions/fwrite): Write to a file. - [fread](../functions/fread): Read a file. - [fputchar](../functions/fputchar): Put a character in a file. - [fgetchar](../functions/fgetchar): Get a character from a file. - [fblockwrite](../functions/fblockwrite): Write blocks of data into a file. - [fblockread](../functions/fblockread): Read blocks of data from a file. - [fseek](../functions/fseek): Jump to a specific character in a file. - [flength](../functions/flength): Get the file length. - [fexist](../functions/fexist): Check, if a file exists. - [fmatch](../functions/fmatch): Check, if patterns with a file name matches.
openmultiplayer/web/docs/translations/th/scripting/functions/fblockwrite.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fblockwrite.md", "repo_id": "openmultiplayer", "token_count": 892 }
434
--- title: floatsin description: Get the sine from a given angle. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Get the sine from a given angle. The input angle may be in radians, degrees or grades. | Name | Description | | ----------- | ------------------------------------------------------ | | Float:value | The angle from which to get the sine. | | anglemode | The angle mode to use, depending on the value entered. | ## ส่งคืน The sine of the value entered. ## ตัวอย่าง ```c GetPosInFrontOfPlayer(playerid, Float:distance, &Float:x, &Float:y, &Float:z) { if (GetPlayerPos(playerid, x, y, z)) // this functions returns 0 if the player is not connected { new Float:z_angle; GetPlayerFacingAngle(playerid, z_angle); x += distance * floatsin(-z_angle, degrees); // angles in GTA go counter-clockwise, so we need to reverse the retrieved angle y += distance * floatcos(-z_angle, degrees); return 1; // return 1 on success, the actual coordinates are returned by reference } return 0; // return 0 if the player isn't connected } ``` ## บันทึก :::warning GTA/SA-MP use degrees for angles in most circumstances, for example GetPlayerFacingAngle. Therefore, it is most likely you'll want to use the 'degrees' angle mode, not radians. Also note that angles in GTA are counterclockwise; 270° is East and 90° is West. South is still 180° and North still 0°/360°. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [floattan](../functions/floattan): Get the tangent from a specific angle. - [floatcos](../functions/floatcos): Get the cosine from a specific angle.
openmultiplayer/web/docs/translations/th/scripting/functions/floatsin.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatsin.md", "repo_id": "openmultiplayer", "token_count": 682 }
435
--- title: setproperty description: Add a new property or change an existing property. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Add a new property or change an existing property. | Name | Description | | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | id | The virtual machine to use, you should keep this zero. | | name[] | Used in combination with value when storing integers; don't use this if you want to store a string. | | value | The integer value to store or the property's unique ID if storing a string. Use the hash-function to calculate it from a string. | | string[] | The value of the property, as a string. Don't use this if you want to store an integer. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c setproperty(.name = "MyInteger", .value = 42); new value = getproperty(.name = "MyInteger"); printf("Value that was stored is: %d", value); setproperty(0, "", 123984334, ":)"); new value[4]; getproperty(0, "", 123984334, value); strunpack(value, value, sizeof(value)); // we need to unpack the string first print(value); //should print :) setproperty(.value = 123984334, .string = ":)"); // The rest is the same as above. ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - Getproperty: Get the value of a property. - Deleteproperty: Delete a property. - Existproperty: Check if a property exists.
openmultiplayer/web/docs/translations/th/scripting/functions/setproperty.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/setproperty.md", "repo_id": "openmultiplayer", "token_count": 767 }
436
--- title: valstr description: Convert an integer into a string. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Convert an integer into a string. | Name | Description | | --------------- | ------------------------------------------------- | | dest | The destination of the string. | | value | The value to convert to a string. | | pack (optional) | Whether to pack the destination (off by default). | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new string[4]; new iValue = 250; valstr(string,iValue); // string is now "250" // valstr fix by Slice stock FIX_valstr(dest[], value, bool:pack = false) { // format can't handle cellmin properly static const cellmin_value[] = !"-2147483648"; if (value == cellmin) pack && strpack(dest, cellmin_value, 12) || strunpack(dest, cellmin_value, 12); else format(dest, 12, "%d", value), pack && strpack(dest, dest, 12); } #define valstr FIX_valstr ``` ## บันทึก :::warning Passing a high value to this function can cause the server to freeze/crash. Fixes are available. Below is a fix that can be put straight in to your script (before valstr is used anywhere). fixes.inc includes this fix. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - strval: Convert a string into an integer. - strcmp: Compare two strings to check if they are the same.
openmultiplayer/web/docs/translations/th/scripting/functions/valstr.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/valstr.md", "repo_id": "openmultiplayer", "token_count": 633 }
437
--- title: Light States --- To be used with [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus) and [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus). The lights on vehicles with 2 wheels (and thus 2 lights) can not be changed. The two back lights of a vehicle can not be changed separately. Here is a visual representation of the light states. Vehicle viewed from a top-down perspective, the top is the front of the vehicle. **o = enabled light** **x = disabled light** 0: (0000 0000) ```c o-o | | o-o ``` 1: (0000 0001) ```c x-o | | o-o ``` 4: (0000 0100) ```c o-x | | o-o ``` 5: (0000 0101) ```c x-x | | o-o ``` 64: (0100 0000) ```c o-o | | x-x ``` 65: (0100 0001) ```c x-o | | x-x ``` 68: (0100 0100) ```c o-x | | x-x ``` 69: (0100 0101) ```c x-x | | x-x ``` Other values not listed here can change the lights, but they are just repeats of other values. For example 15 has the same outcome as 5. After 255 the values will wrap around, 256 will be set as 0, 257 as 1 and so on. **Example Usage:** To disable the back two lights of a vehicle while keeping the front the same state: ```c new Panels, Doors, Lights, Tires; GetVehicleDamageStatus(vehicleid, Panels, Doors, Lights, Tires); UpdateVehicleDamageStatus(vehicleid, Panels, Doors, (Lights | 0b01000000), Tires); //The '0b' part means that the following number is in binary. Just the same way that '0x' indicates a hexadecimal number. ```
openmultiplayer/web/docs/translations/th/scripting/resources/lightstates.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/lightstates.md", "repo_id": "openmultiplayer", "token_count": 602 }
438
--- title: Shop Names --- :::note To be used with [SetPlayerShopName](../functions/SetPlayerShopName). ::: | Internal Shop name | What is it? | Coordinates | | ------------------ | ------------- | ------------------------------ | | "FDPIZA" | Pizza Stack | 374.0000, -119.6410, 1001.4922 | | "FDBURG" | Burger Shot | 375.5660, -68.2220, 1001.5151 | | "FDCHICK" | Cluckin' Bell | 368.7890, -6.8570, 1001.8516 | | "AMMUN1" | Ammunation 1 | 296.5395, -38.2739, 1001.515 | | "AMMUN2" | Ammunation 2 | 295.7359, -80.6865, 1001.5156 | | "AMMUN3" | Ammunation 3 | 290.2011, -109.5698, 1001.5156 | | "AMMUN4" | Ammunation 4 | 308.1619, -141.2549, 999.6016 | | "AMMUN5" | Ammunation 5 | 312.7883, -166.0069, 999.6010 |
openmultiplayer/web/docs/translations/th/scripting/resources/shopnames.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/shopnames.md", "repo_id": "openmultiplayer", "token_count": 421 }
439
--- title: OnPlayerClickPlayerTextDraw description: This callback is called when a player clicks on a player-textdraw. tags: ["player", "textdraw", "playertextdraw"] --- ## Açıklama Bu callback, bir oyuncu bir player-textdrawa tıkladığı zaman çağırılır. Oyuncu seçim modunu ESC ile iptal ettiğinde çağırılmaz ancak OnPlayerClickTextDraw'da çağırılır. | İsim | Açıklama | | ------------ | ----------------------------------- | | playerid | Textdrawa tıklayan oyuncunun ID'si. | | playertextid | Tıklanan player-textdrawın ID'si. | ## Çalışınca vereceği sonuçlar Filterscriptlerde her zaman ilk çağırılır, 1 değerini döndürmek diğer filterscriptlerin görmesini engeller. ## Örnekler ```c new PlayerText:gPlayerTextDraw[MAX_PLAYERS]; public OnPlayerConnect(playerid) { // Textdraw oluştur. gPlayerTextDraw[playerid] = CreatePlayerTextDraw(playerid, 10.000000, 141.000000, "MyTextDraw"); PlayerTextDrawTextSize(playerid, gPlayerTextDraw[playerid], 60.000000, 20.000000); PlayerTextDrawAlignment(playerid, gPlayerTextDraw[playerid],0); PlayerTextDrawBackgroundColor(playerid, gPlayerTextDraw[playerid],0x000000ff); PlayerTextDrawFont(playerid, gPlayerTextDraw[playerid], 1); PlayerTextDrawLetterSize(playerid, gPlayerTextDraw[playerid], 0.250000, 1.000000); PlayerTextDrawColor(playerid, gPlayerTextDraw[playerid], 0xffffffff); PlayerTextDrawSetProportional(playerid, gPlayerTextDraw[playerid], 1); PlayerTextDrawSetShadow(playerid, gPlayerTextDraw[playerid], 1); // Oluşturulan textdrawı seçilebilir yap. PlayerTextDrawSetSelectable(playerid, gPlayerTextDraw[playerid], 1); // Textdrawı oyuncuya göster. PlayerTextDrawShow(playerid, gPlayerTextDraw[playerid]); return 1; } public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys) { if (newkeys == KEY_SUBMISSION) { SelectTextDraw(playerid, 0xFF4040AA); } return 1; } public OnPlayerClickPlayerTextDraw(playerid, PlayerText:playertextid) { if (playertextid == gPlayerTextDraw[playerid]) { SendClientMessage(playerid, 0xFFFFFFAA, "Bir textdrawa tıkladınız."); CancelSelectTextDraw(playerid); return 1; } return 0; } ``` ## Notlar :::warning Bir oyuncu textdraw seçimini ESC'ye basarak iptal ettiğinde 'INVALID_TEXT_DRAW' ID'si ile OnPlayerClickTextDraw çağırılır. OnPlayerClickPlayerTextDraw çağırılmaz. ::: ## Bağlantılı Fonksiyonlar - [PlayerTextDrawSetSelectable](../functions/PlayerTextDrawSetSelectable.md): Bir player-textdrawın seçilebilir olup olmayacağını ayarlar. - [OnPlayerClickTextDraw](OnPlayerClickTextDraw.md): Oyuncu bir textdrawa tıkladığında çağırılır. - [OnPlayerClickPlayer](OnPlayerClickPlayer.md): Bir oyuncu başka bir oyuncuya tıkladığında çağırılır.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickPlayerTextDraw.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerClickPlayerTextDraw.md", "repo_id": "openmultiplayer", "token_count": 1145 }
440
--- title: OnPlayerInteriorChange description: Oyuncu interior değiştirdiğinde çalışır. tags: ["player"] --- ## Açıklama Oyuncu interior değiştirdiğinde çalışır. SetPlayerInterior tarafından ya da oyuncu bir interiora girip/çıktığı zaman tetiklenebilir. | İsim | Açıklama | | ------------- | -------------------------------------- | | playerid | Interioru değişen oyuncu. | | newinteriorid | Oyuncunun şu an bulunduğu interior. | | oldinteriorid | Oyuncunun daha önce bulunduğu interior.| ## Çalışınca Vereceği Sonuçlar Her zaman öncelikle oyun modunda çağrılır. ## Örnekler ```c public OnPlayerInteriorChange(playerid, newinteriorid, oldinteriorid) { new string[42]; format(string, sizeof(string), "%d interiorundan %d interioruna gittiniz!", oldinteriorid, newinteriorid); SendClientMessage(playerid, COLOR_ORANGE, string); return 1; } ``` ## Bağlantılı Fonksiyonlar - [SetPlayerInterior](../functions/SetPlayerInterior): Oyuncunun interiorunu ayarla. - [GetPlayerInterior](../functions/GetPlayerInterior): Oyuncunun mevcut interior bilgisini öğren. - [LinkVehicleToInterior](../functions/LinkVehicleToInterior): Aracın görülebileceği interioru değiştirin. - [OnPlayerStateChange](OnPlayerStateChange): Oyuncunun durumu değiştiğinde çağrılır.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerInteriorChange.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerInteriorChange.md", "repo_id": "openmultiplayer", "token_count": 571 }
441
--- title: OnPlayerText description: Fonksiyon, oyuncu sohbet mesajı gönderdiğinde çağrılır. tags: ["player"] --- ## Açıklama Fonksiyon, oyuncu sohbet mesajı gönderdiğinde çağrılır. | Parametre | Açıklama | | --------- | ---------------------------------------- | | playerid | Sohbet mesajı gönderen oyuncunun ID'si. | | text[] | Oyuncunun yazdığı metin. | ## Çalışınca Vereceği Sonuçlar Her zaman Filterscript komutlarında ilk olarak çağrılır, bu nedenle 0 döndürmek diğer scriptlerin görmesini engeller. ## örnekler ```c public OnPlayerText(playerid, text[]) { new pText[144]; format(pText, sizeof (pText), "(%d) %s", playerid, text); SendPlayerMessageToAll(playerid, pText); return 0; // varsayılan metni yoksay ve özel olanı gönder } ``` ## Notlar <TipNPCCallbacks /> ## Bağlantılı Fonksiyonlar - [SendPlayerMessageToPlayer](../functions/SendPlayerMessageToPlayer): Bir oyuncuyu bir oyuncu için metin göndermeye zorlama. - [SendPlayerMessageToAll](../functions/SendPlayerMessageToAll): Bir oyuncuyu tüm oyunculara metin göndermeye zorlama.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerText.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerText.md", "repo_id": "openmultiplayer", "token_count": 516 }
442
--- title: AddCharModel description: İndirmek için yeni bir özel karakter modeli ekler. tags: [] --- :::warning Bu işlev SA-MP 0.3.DL R1'e eklenmiştir ve önceki sürümlerde çalışmayacaktır! ::: ## Açıklama İndirmek için yeni bir özel karakter modeli ekler. Model dosyaları oynatıcının belgelerinde saklanır. Belgelerim\Gta San Andreas User Files\SAMP\cache | İsim | Açıklama | | ------- | -------------------------------------------------------------------------------------------------------------- | | baseid | Kullanılacak temel cilt modeli kimliği. (karakterin ve orijinal karakterin ne zaman kullanılacağı) | | newid | "Öncesinde, yeni model ID'leri 20000 ve 30000 arasinda (10000 slot) değişiklik göstermekteydi. | | dffname | Varsayılan olarak modeller sunucu klasöründe bulunan .dff modeli çarpışma dosyasının adı (çalışma yolu ayarı). | | txdname | Modeller sunucu klasöründe varsayılan olarak bulunan .txd model kaplama dosyasının adı (çalışma yolu ayarı). | ## Çalışınca Vereceği Sonuçlar 1: İşlev başarıyla yürütüldü. 0: İşlev yürütülemedi. ## Örnekler ```c public OnGameModeInit() { AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd"); AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd"); return 1; } ``` ```c AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd"); AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd"); ``` ## Notlar :::tip Bunun işe yaraması için kullanılabilir resmin öncelikle sunucu ayarlarında etkinleştirilmesi gerekir. ::: :::warning Şu anda bu fonksiyonu ne zaman arayabileceğiniz konusunda herhangi bir kısıtlama yoktur, ancak OnFilterScriptInit/OnGameModeInit içinde aramamanız durumunda, halihazırda sunucuda bulunan bazı oyuncuların modelleri indirmemiş olma riskini çalıştırdığınızı unutmayın. ::: ## Bağlantılı Fonksiyonlar - [SetPlayerSkin](SetPlayerSkin.md): Bir oyuncunun cildini ayarlayın.
openmultiplayer/web/docs/translations/tr/scripting/functions/AddCharModel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddCharModel.md", "repo_id": "openmultiplayer", "token_count": 858 }
443
--- title: Attach3DTextLabelToPlayer description: Oyuncuya bir 3D Text Label bağlayın. tags: ["player", "3dtextlabel"] --- ## Açıklama Oyuncuya 3D Text Label bağlama fonksiyonu. | Parametre | Açıklama | | --------- | --------------------------------------------------------------------------------| | Text3D:textid | Create3DTextLabel ile oluşturulmuş label ID'si. | | playerid | Label'ın bağlanacağı oyuncunun ID'si. | | OffsetX | Oyuncunun X-ofset koordinatı. (oyuncunun ortasından başlar, '0.0, 0.0, 0.0'dır) | | OffsetY | Oyuncunun Y-ofset koordinatı. (oyuncunun ortasından başlar, '0.0, 0.0, 0.0'dır) | | OffsetZ | Oyuncunun Z-ofset koordinatı. (oyuncunun ortasından başlar, '0.0, 0.0, 0.0'dır) | ## Çalışınca Vereceği Sonuçlar 1: Fonksiyon başarıyla çalıştı. 0: Fonksiyon çalışamadı. Oyuncu veya label yok. ## Örnekler ```c public OnPlayerConnect(playerid) { new Text3D:textLabel = Create3DTextLabel("Merhaba, ben buralarda yeniyim!", 0x008080FF, 30.0, 40.0, 50.0, 40.0, 0); // 3D text labelimizi yaratıyoruz Attach3DTextLabelToPlayer(textLabel, playerid, 0.0, 0.0, 0.7); // Oyuncu oyuna girdiğinde Text Label'ı ona bağlıyoruz return 1; } ``` ## Bağlantılı Fonksiyonlar - [Create3DTextLabel](Create3DTextLabel): 3D text label oluşturun. - [Delete3DTextLabel](Delete3DTextLabel): 3D text label silin. - [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): Bir 3D text labeli araca bağlayın. - [Update3DTextLabelText](Update3DTextLabelText): Bir 3D text labelin metnini değiştirin. - [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): Sadece bir oyuncuya özel 3D text label oluşturun. - [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): Oyuncuya bağlı 3D text labeli silin. - [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): Oyuncuya özel 3D text labelin metnini değiştirin.
openmultiplayer/web/docs/translations/tr/scripting/functions/Attach3DTextLabelToPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/Attach3DTextLabelToPlayer.md", "repo_id": "openmultiplayer", "token_count": 932 }
444
--- title: ClearAnimations description: Oyuncunun uyguladığı bütün animasyonları ipta eder. tags: [] --- ## Açıklama Oyuncunun uyguladığı bütün animasyonları ipta eder. (Aynı zamanda jetpackteyken, paraşütle atlarken, araca binerken, araç kullanırken, yüzerken yapılan animasyonlarda bu duruma dahildir.) | Parametre | Açıklama | | --------- | ------------------------------------------------------------------------------------------------------------------------- | | playerid | Animasyonu bozulacak oyuncunun ID'si. | | forcesync | Oyuncunun animasyon akışını etrafındaki diğer oyuncularla senkronize etmeye zorlamak için 1'e ayarlayın (isteğe bağlı) | ## Çalışınca Vereceği Sonuçlar Bu fonksiyon her zaman belirtilen ID oyunda olmasa bile her zaman 1 döner. ## Örnekler ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/animclear", true)) { ClearAnimations(playerid); return 1; } return 0; } ``` ## Notlar :::tip ApplyAnimation'da freeze parametresi için 1 olarak girilirse, animasyon bittiğinde ClearAnimations hiçbir şey yapmaz. ::: :::tip Oyuncuyu bir araçtan çıkarmanın diğer bazı yollarının aksine, bu aynı zamanda aracın hızını sıfırlayarak aracı anında durdurur. Oyuncu, araba koltuğu ile aynı konumda aracın üstünde görünecektir. ::: ## Bağlantılı Fonksiyonlar - [ApplyAnimation](ApplyAnimation): Oyuncuya animasyon uygulatma.
openmultiplayer/web/docs/translations/tr/scripting/functions/ClearAnimations.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/ClearAnimations.md", "repo_id": "openmultiplayer", "token_count": 809 }
445
--- title: SetPlayerAmmo description: Oyuncunun silah mermisini ayarlama. tags: ["player"] --- ## Açıklama Bir oyuncunun silahındaki mermi sayısını ayarlar. | Parametre | Açıklama | | -------- | -------------------------------------------------------------------------------- | | playerid | Silahının mermisi ayarlanacak oyuncunun ID'si. | | weaponid | Mermisi ayarlanacak silahın ID'si. (silah slotu değil) | | ammo | Ayarlanacak merminin miktarı. | ## Çalışınca Vereceği Sonuçlar 1: Fonksiyon başarıyla çalıştı. Silah ID'si geçersiz olsa bile sonuç döndürülür. (0-12 silah ID'leri hariç) 0: Girilen ID oyunda olmadığı için fonksiyon çalışmadı. ## Örnekler ```c SetPlayerAmmo(playerid, WEAPON_SHOTGUN, 100); // Shotgun mermilerini 100 olarak ayarlıyoruz. ``` ## Notlar :::tip 'weaponslot' parametresi SA:MP include'una ait bir yazım hatasıdır. Mermisini değiştirmek istediğiniz silahın slot'u yerine silahın ID'sini girmelisiniz. ::: :::tip Bir oyuncunun silahını silmek/elinden almak için mermi değerini 0 olarak girmelisiniz. Silahın GetPlayerWeaponData'da hala görüneceğini unutmayın. ::: ## Bağlantılı Fonksiyonlar - [GetPlayerAmmo](GetPlayerAmmo): Bir oyuncunun belirtilen silahında ne kadar mermisi olduğunu kontrol eder. - [GivePlayerWeapon](GivePlayerWeapon): Oyuncuya silah verir. - [SetPlayerArmedWeapon](SetPlayerArmedWeapon): Oyuncunun kuşandığı(eline aldığı) silahı değiştirir.
openmultiplayer/web/docs/translations/tr/scripting/functions/SetPlayerAmmo.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/SetPlayerAmmo.md", "repo_id": "openmultiplayer", "token_count": 807 }
446
--- title: OnActorStreamIn description: 当演员被玩家的客户端流入时,就会调用这个回调。 tags: [] --- <VersionWarnCN name='回调' version='SA-MP 0.3.7' /> ## 描述 当演员被玩家的客户端流入时,就会调用这个回调。 | 参数名 | 描述 | | ----------- | ------------------------- | | actorid | 已为玩家流入的演员的 ID。 | | forplayerid | 让演员流入的玩家的 ID。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnActorStreamIn(actorid, forplayerid) { new string[40]; format(string, sizeof(string), "演员 %d 现在正为你流入。", actorid); SendClientMessage(forplayerid, 0xFFFFFFFF, string); return 1; } ``` ## 相关回调 <TipNPCCallbacksCN />
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnActorStreamIn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnActorStreamIn.md", "repo_id": "openmultiplayer", "token_count": 445 }
447
--- title: OnNPCModeInit. description: This callback is called when a NPC script is loaded. tags: [] --- ## 描述 This callback is called when a NPC script is loaded. ## 案例 ```c public OnNPCModeInit() { print("NPC script loaded."); return 1; } ``` ## 相关回调 - [OnNPCModeExit](../callbacks/OnNPCModeExit): Gets called when a NPC script unloaded.
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCModeInit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCModeInit.md", "repo_id": "openmultiplayer", "token_count": 141 }
448
--- title: OnPlayerExitVehicle description: 当玩家开始离开载具时,这个回调函数被调用。 tags: ["player", "vehicle"] --- ## 描述 当玩家开始离开载具时,这个回调函数被调用。 | 参数名 | 描述 | | --------- | --------------------- | | playerid | 离开载具的玩家的 ID。 | | vehicleid | 玩家离开的载具的 ID。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerExitVehicle(playerid, vehicleid) { new string[35]; format(string, sizeof(string), "信息: 您正在离开载具 %i", vehicleid); SendClientMessage(playerid, 0xFFFFFFFF, string); return 1; } ``` ## 要点 :::warning 如果玩家从自行车上摔下来或被其他函数从载具上移除,例如使用 SetPlayerPos 函数时,则不调用。 你必须使用 OnPlayerStateChange 回调并检查它们的旧状态是 PLAYER_STATE_DRIVER 还是 PLAYER_STATE_PASSENGER。它们现在的新状态是 PLAYER_STATE_ONFOOT。 ::: ## 相关函数 - [RemovePlayerFromVehicle](../functions/RemovePlayerFromVehicle): 把一个玩家丢出载具外。 - [GetPlayerVehicleSeat](../functions/GetPlayerVehicleSeat): 检查玩家的座位。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerExitVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerExitVehicle.md", "repo_id": "openmultiplayer", "token_count": 669 }
449
--- title: OnPlayerSpawn description: 这个回调函数在玩家重生时被调用。 tags: ["player"] --- ## 描述 这个回调函数在玩家重生时被调用。(即调用 SpawnPlayer 函数后) | 参数名 | 描述 | | -------- | ----------------- | | playerid | 重生的玩家的 ID。 | ## 返回值 0 - 将阻止其他过滤脚本接收到这个回调。 1 - 表示这个回调函数将被传递给下一个过滤脚本。 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerSpawn(playerid) { new PlayerName[MAX_PLAYER_NAME], string[40]; GetPlayerName(playerid, PlayerName, sizeof(PlayerName)); format(string, sizeof(string), "%s 已成功重生。", PlayerName); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## 要点 :::tip 有时游戏会在玩家重生后扣除\$100。 ::: ## 相关函数 - [SpawnPlayer](../functions/SpawnPlayer): 强制玩家重生。 - [AddPlayerClass](../functions/AddPlayerClass): 添加一个类。 - [SetSpawnInfo](../functions/SetSpawnInfo): 设置玩家的重生设置。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerSpawn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerSpawn.md", "repo_id": "openmultiplayer", "token_count": 589 }
450
--- title: OnVehiclePaintjob description: 当玩家在改装店里预览车辆油漆涂鸦样式时调用。 tags: ["vehicle"] --- ## 描述 当玩家在改装店里预览车辆油漆涂鸦样式时调用。注意,当玩家购买油漆涂鸦样式时,这个回调函数不会被调用。 | 参数名 | 描述 | | ---------- | ----------------------------- | | playerid | 改变车辆油漆涂鸦的玩家的 ID。 | | vehicleid | 更换了油漆涂鸦的车辆 ID。 | | paintjobid | 新的油漆涂鸦样式 ID。 | ## 返回值 它总是在游戏模式中先被调用,所以返回 0 也会阻止其他过滤脚本看到它。 ## 案例 ```c public OnVehiclePaintjob(playerid, vehicleid, paintjobid) { new string[128]; format(string, sizeof(string), "你把你的车辆油漆涂鸦改为了 %d!", paintjobid); SendClientMessage(playerid, 0x33AA33AA, string); return 1; } ``` ## 要点 :::tip 这个回调不被 ChangeVehiclePaintjob 函数调用。 你可以从 vSync 中使用 OnVehicleChangePaintjob 回调来了解玩家何时购买了新的油漆涂鸦。 ::: ## 相关函数 - [ChangeVehiclePaintjob](../functions/ChangeVehiclePaintjob): 改变车辆的油漆涂鸦样式。 - [ChangeVehicleColor](../functions/ChangeVehicleColor): 改变车辆的颜色。 ## 相关回调 - [OnVehicleRespray](OnVehicleRespray): 当车辆的油漆涂鸦样式被改变时调用。 - [OnVehicleMod](OnVehicleMod): 当车辆被改装时调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehiclePaintjob.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehiclePaintjob.md", "repo_id": "openmultiplayer", "token_count": 913 }
451
--- title: AllowAdminTeleport description: 这个函数将决定RCON管理员在设置导航点时是否会被传送。 tags: [] --- :::warning 从 0.3d 版本开始,这个函数已被废弃。请看[OnPlayerClickMap](../callbacks/OnPlayerClickMap). ::: ## 描述 这个函数将决定 RCON 管理员在设置导航点时是否会被传送。 | 参数名 | 说明 | | ------ | ---------------- | | allow | 0 禁用,1 启用。 | ## 返回值 该函数不返回任何特定的值。 ## 案例 ```c public OnGameModeInit() { AllowAdminTeleport(1); // 其他的代码 return 1; } ``` ## 相关函数 - [IsPlayerAdmin](IsPlayerAdmin): 检查玩家是否已经登录到 RCON。 - [AllowPlayerTeleport](AllowPlayerTeleport): 为玩家启用/禁用在地图上点击右键传送的功能。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AllowAdminTeleport.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AllowAdminTeleport.md", "repo_id": "openmultiplayer", "token_count": 465 }
452
--- title: DeletePlayer3DTextLabel description: 删除由CreatePlayer3DTextLabel创建的三维文本标签。 tags: ["player", "3dtextlabel"] --- ## 描述 删除由 CreatePlayer3DTextLabel 创建的三维文本标签。 | 参数名 | 说明 | | --------------- | --------------------------------- | | playerid | 要删除的三维文本标签的玩家的 ID。 | | PlayerText3D:textid | 要删除的玩家的三维文本标签的 ID。 | ## 返回值 1:函数执行成功。 0:函数执行失败。这意味着指定的标签不存在。 ## 案例 ```c new PlayerText3D:labelid = CreatePlayer3DTextLabel(...); // 晚些时候... DeletePlayer3DTextLabel(playerid, labelid); ``` ## 相关函数 - [Create3DTextLabel](Create3DTextLabel): 创建一个三维文本标签。 - [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): 将三维文本标签附加到玩家身上。 - [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): 将一个三维文本标签附加到载具。 - [Update3DTextLabelText](Update3DTextLabelText): 改变三维文本标签的文本内容和颜色。 - [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): 为玩家创建一个三维文本标签。 - [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): 改变玩家的三维文本标签的文本内容和颜色。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/DeletePlayer3DTextLabel.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/DeletePlayer3DTextLabel.md", "repo_id": "openmultiplayer", "token_count": 710 }
453
--- title: Update3DTextLabelText description: 更新一个三维文本标签的文本内容和颜色。 tags: ["3dtextlabel"] --- ## 描述 更新一个三维文本标签的文本内容和颜色。 | 参数名 | 说明 | | --------- | ---------------------------------- | | Text3D:textid | 你想更新的三维文本标签 ID。 | | color | 从现在起,三维文本标签的颜色。 | | text[] | 从现在起,三维文本标签的文本内容。 | ## 返回值 该函数不返回任何特定的值。 ## 案例 ```c public OnGameModeInit() { new Text3D: mylabel; mylabel = Create3DTextLabel("我在坐标:\n30.0,40.0,50.0", 0x008080FF, 30.0, 40.0, 50.0, 40.0, 0); Update3DTextLabelText(mylabel, 0xFFFFFFFF, "新的文本内容。"); return 1; } ``` ## 要点 :::warning 如果 text[] 参数是空的,服务端或位于文本标签旁的玩家客户端可能会崩溃! ::: ## 相关函数 - [Create3DTextLabel](Create3DTextLabel): 创建一个三维文本标签。 - [Delete3DTextLabel](Delete3DTextLabel): 删除一个三维文本标签。 - [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): 将三维文本标签附加到玩家身上。 - [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): 将一个三维文本标签附加到载具。 - [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): 为玩家创建一个三维文本标签。 - [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): 删除一个为玩家创建的三维文本标签。 - [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): 改变玩家的三维文本标签的文本内容和颜色。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/Update3DTextLabelText.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/Update3DTextLabelText.md", "repo_id": "openmultiplayer", "token_count": 931 }
454
--- title: 常見問題 --- ## 內容 ## 用戶端 ### 出現錯誤訊息 "San Andreas cannot be found" open.mp **並不是** 一個包含遊戲的獨立軟體,它只是GTASA的一個連線模組,所以需要先安裝原版GTASA才可以執行open.mp。這個模組需要在 GTASA **EU/US v1.0 (歐美 1.0版)** 版本下才可以運行,其他版本,像是Steam上的版本或是其他平台版本皆無法正確運行。 [可以點擊這裡下載 歐美1.0版本 的執行程式來進行降級](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661) ### 在伺服器列表上沒有任何伺服器 若在 Host 或是 Internet 標籤出現該問題,請確認網路連線狀態以及防火牆狀態,防火牆請允許用戶端連接,若仍然沒有,可能為主伺服器故障,請查看有無任何公告。假如是在 Favorites 標籤,代表尚未加入任何伺服器進該列表,請添加伺服器至該列表。 ### 用戶端開啟後變成單人模式 :::warning 正常情況下並不會變為單人模式(例如出現 New Game 等選項),一般會直接讀取用戶端並進入伺服器。 ::: 導致這樣的原因比較有可能是因為使用了錯誤的GTASA主程式版本,或是用戶端安裝錯誤。若為GTASA主程式版本問題,[可以點擊這裡下載 歐美1.0版本 的執行程式來進行降級](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661)。 另外一種比較不常發生的情況,有可能是用戶端已經讀取完成,但是仍跳出了單人模式的選單,這時只要選擇任一選項後按ESC關閉選單即可。 ### 當進入伺服器時出現錯誤訊息 "Unacceptable Nickname (暱稱不允許使用)" 請確認暱稱都是允許的字元 ( 可使用的字符有 0-9, a-z, \[\], (), \$, @, ., \_ = ),以及請確認暱稱不超過 20 字元。當伺服器內有玩家和你暱稱一樣的話,也會造成這個問題發生。(通常會發生在超時當機後,再重新連線進伺服器)。在 Windows 下的伺服器,若伺服器連續執行超過 50天 亦有可能造成該問題的發生。 ### 畫面卡在 "Connecting to IP:Port... (正在連接至 IP:端口)" 這個訊息代表無法連接至伺服器,通常有可能是因為伺服器已經關閉或是網路中斷,不過也有可能是本機的網路已經中斷,或是被防火牆擋下,請多方面確認後再進行重試。 ### 我的GTASA有裝模組/修改器,用戶端無法正常啟用 請把模組/修改器砍了再試試。 ### 啟動用戶端時並沒有正常啟動 刪除我的文件->GTA San Andreas User Files資料夾裡的gta_sa.set,以及刪除修改器和模組通常即可解決。 ### 當交通工具爆炸時遊戲就當機了 這裡有三種方法可以解決問題: 1. 當電腦使用多螢幕時請不要連接其他螢幕,請使用單螢幕遊玩。 2. 請調整設定內的 Visual FX quality(特效品質) 至 low(低) 。 (Esc > Options > Display Setup > Advanced) 3. 重新命名GTASA的遊戲資料夾,比如重新命名為 GTA San Andreas2 之類的,大部分情況下會解決該問題,但是有可能會再發生,屆時需再重新命名。 ### 我的滑鼠在關閉ESC選單後無法移動 如果滑鼠常常無法移動,可能是因為用戶端的多核心執行造成的,請至 我的文件->GTA San Andreas User Files->SAMP資料夾裡打開 sa-mp.cfg 編輯,將 multicore=1 改為 multicore=0 即可解決該問題。 ### 出現錯誤 The file dinput8.dll is missing (遺失檔案 dinput8.dll) 請下載並安裝 DirectX 並重新啟動電腦即可解決。若還是會發生該問題,請至 C:\\Windows\\System32 資料夾內複製 dinput.dll 該檔案至GTASA的資料夾內便可解決問題。 ### 我看不到其他玩家頭頂的暱稱標籤 有可能是伺服器關閉了頭頂的暱稱標籤顯示,除非電腦使用的是 Intel HD內建顯示卡 亦有可能造成該問題,可以試著更新驅動程式,若還是有該問題,可以試著更換成獨立顯示卡亦可解決該問題。
openmultiplayer/web/docs/translations/zh-tw/client/CommonClientIssues.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-tw/client/CommonClientIssues.md", "repo_id": "openmultiplayer", "token_count": 2783 }
455
--- title: String Manipulation description: Beginner friendly tutorial about everything string manipulation. --- ## Introduction ### Tutorial description Hello everyone, it surely is a nice quiet night, or at least it is at the composition of this tutorial. So, hey, what about tagging along to both enrich and/or engage with the main focus of this article, this is and as the title suggests, going to be focused on “_String manipulation_” in pawn, we will go through the absolute intermediate stuff that everybody should be aware of to some sort of advanced, clever and effective tips. ### What is string formatting? In general, formatting a text is the act of manipulating it to visually improve its readability, be it changing the font’s family, color, weight and so on. Strings being an array of characters (_alphabets, numbers, symbols_), which we wouldn’t specifically call a text on itself but is referred as such when displayed, can be processed with the same approach, but unfortunately, SA-MP’s interpretation of pawn does not allow for much (_yet? Maybe never_), generally speaking changing the color is as far as we can get, yes, you can still change/customize the font, but that’s client-sided only, and yes, [GTA San Andreas](https://www.rockstargames.com/sanandreas/) (_the parent game_) does provide some extra fonts, but that only works on [textdraws](../scripting/resources/textdraws) and [gametext](../scripting/functions/GameTextForPlayer), this does cause limitations concerning text presentation, but hey, it’s been over a decade now, and we survived just fine. ### String declaration As I said before, strings are basically arrays of characters, so they are used the same way arrays are, and so as we would create an array, we would do for strings following this format; `string_name[string_size]`. :::info **string_name**: the name of the character array (_e.g. string, str, message, text...etc. as long as it’s a valid variable name (begins with a character or an underscore)_). **string_size**: the maximum characters this string would have. ::: ```cpp // declaring a string of 5 characters new str_1[5]; // declaring a string of 100 characters new str_2[100]; ``` You can also predefine constant values so you can use them multiple times as string sizes. ```cpp // declaring a constant #define STRING_SIZE 20 // declaring a string with the size of STRING_SIZE's value new str_3[STRING_SIZE]; ``` :::note On compilation time, the compiler will replace all occurrences of `STRING_SIZE` with the value `20`, this method is both time-saving and more readable on most cases, keep in mind that the value you assign to the `STRING_SIZE` constant must be an integer or else it will give a compilation error. ::: In addition to predefined constants, you can perform basic operations, the modulo operator (`%`) however will give compilation errors if used, you can still get away with division calculations (`/`) but keep in mind, dividing by `0` will trigger errors, the bonus here is all floating results will be automatically rounded for you. ```cpp // declaring a constant #define STRING_SIZE 26 // declaring strins with the use of the STRING_SIZE constant and some calculations new str_4[STRING_SIZE + 4], str_5[STRING_SIZE - 6], str_6[STRING_SIZE * 2], str_7[9 / 3]; ``` Theoretically, you can create somewhat ridiculously huge arrays, but SA-MP puts few restrictions on the length of strings you can work with, depending on what you’re working on, it limits the number of characters you can normally output. #### Length limits SA-MP limits characters that can be stored in a single string and keeps scripters from going overboard with working with text, luckily, it’s not as bad as it might seem, the list below breaks down some of these limits; | | | | | ------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---- | | **Text input** | The text you input on the chat. | 128 | | **Text output** | Text that output on the client's screen. | 144 | | **Name** | Player nickname / Username. | 24 | | **Textdraw string** | Pretty self-explanatory. | 1024 | | **Dialog info** | The text displayed on all dialogs of the type `DIALOG_STYLE_MSGBOX`, `DIALOG_STYLE_INPUT` and `DIALOG_STYLE_PASSWORD`. | 4096 | | **Dialog caption** | The caption/title on top of the dialog. | 64 | | **Dialog input** | The input box on `DIALOG_STYLE_INPUT` and `DIALOG_STYLE_PASSWORD`. | 128 | | **Dialog column** | The characters on each column of `DIALOG_STYLE_TABLIST_HEADER` and `DIALOG_STYLE_TABLIST`. | 128 | | **Dialog row** | The characters on each column of `DIALOG_STYLE_TABLIST_HEADER`, `DIALOG_STYLE_TABLIST` and `DIALOG_STYLE_LIST`. | 256 | | **Chat bubble** | The chat bubble that displays above the player's name tag. | 144 | | **Menu title** | The GTA San Andreas native menu (_mostly used for shops_) header. | 31 | | **Menu item** | The GTA San Andreas native menu (_mostly used for shops_) item/row. | 31 | If somehow these limits have been exceeded, few inconveniences might occur, it can even crash/freeze the server in some cases (_e.g. long textdraw strings_), in some other cases, the text would just truncate like the Menu title (_if it reaches 32 characters, it truncates back to 30_) and items. Besides the strict limits put on strings, there are many others concerning different stuff, you can view the complete list [here](../scripting/resources/limits). #### Assigning values Assigning values to strings can be done via many methods, some assign them upon their creation, others after, there are people who use loops, other use functions, and yes, there are who do this process manually, slot by slot, there is no exact right or wrong way for doing so, some methods are often more effective in few cases than others some are not, at the end of the day all that matters is performance, optimization, and readability. In most cases you’d want to give a default value to the string upon its creation, you can go through this simply as follows; ```cpp new message_1[6] = "Hello", message_2[] = "This is another message"; ``` Make sure the string’s size is greater than the number of characters you assigned them for, having a smaller or equal string size to that, will trigger compilation errors, leaving the size slot between the two brackets empty (like on the `message_2` example), will automatically give the array the size of the text you’ve assigned it to plus `1`, in this case, `23 + 1 = 24`, why? It reserves a slot for the null character (_aka the null-terminator_), more on that later, the word “_Hello_” has 5 characters, so in order to store it on a string, it should have 6 cells, 5 cells for the word’s character count, and one for the **null character**. Let’s take a look at doing the same process slot by slot manually, first, we define a new array, you can determine its size or leave that empty for the compiler to fill, both would work just fine, we will fill the array with characters to create the string “_Hello_”. ```cpp // Including the string' size on its declaration, or it won't work otherwise new message_3[6]; message_3[0] = 'H'; message_3[1] = 'e'; message_3[2] = 'l'; message_3[3] = 'l'; message_3[4] = 'o'; message_3[5] = '\0'; ``` There, we assigned for each slot on the `message_3` array a character, this won’t work if you were to declare a sting with no definitive size, note that to represent a single character, it ought to be written between two single quotations (`'`), also, notice how we started with slot 0, and it’s only natural, considering how I emphasised on how a string is an array of characters, meaning, that the first slot is always 0, and the last one is its size minus 1 (_the null character does not count_), which in this case is 4, counting from 0 to 4, that makes it 5 characters, with the sixth being the null terminator, more on that comes later. You can also assign strings numbers which will be viewed as **ASCII** (_a system representing character numerically, it covers 128 characters ranging from 0 to 127, more on that [here](https://en.wikipedia.org/wiki/ASCII)_) code for a character, the same message “_Hello_” can be assigned using _ASCII_ code like this; ```cpp new message_4[6]; message_4[0] = 72; // ASCII representation of capitalized h, “H” message_4[1] = 101; // ASCII representation of “e” message_4[2] = 108; // ASCII representation of “l” message_4[3] = 108; // ASCII representation of “l” message_4[4] = 111; // ASCII representation of “o” message_4[5] = 0; // ASCII representation of the null terminator ``` And yes, you can perform numeric operations with these codes the same you do with normal numbers, after all, the machine views characters as just mere numbers. ```cpp new message_5[1]; message_5[0] = 65 + 1; ``` If you were to output `message_5[0]`, you would get **B**, weird right? Well, no, not really, you can perform other basic operations (_subtraction, multiplication, division, and even the modulo_), floating numbers will get auto-rounded for you, let’s see how this works. You have `65 + 1`, that returns `66`, checking the _ASCII_ table, you will find that `66` is the numeric representation of the character “_B_” (_capitalized_). So, the snippet above is basically the same as doing: `message_5[0] = 'B'`; For reference, use [this ASCII table](http://www.asciitable.com/). You can also perform the same operation between multiple characters or a mix of both, them and numbers, here are few examples; ```cpp new message_6[3]; message_6[0] = 'B' - 1; // Which is 66 - 1, returns 65, the numeric representation of “A” message_6[1] = 'z' - '&'; // Which is 122 - 38, returns 84, the numeric representation of “T” message_6[2] = '0' + '1'; // Which is 48 + 49, returns the numeric representation of “a”, note that '0' and '1' are not the numbers 0 and 1, but rather characters ``` It might get confusing sometimes if you never knew about the _ASCII_ system, all it takes is some practice, because understanding how it works, is very handy. _ASCII_ code is not exclusive to decimal numbers only, you can also use hexadecimal or binary numbers the same way. ```cpp new numString[4]; numString[0] = 0x50; // The decimal number 80 in hexadecimal, capitalized p, “P” numString[1] = 0b1000001; // The decimal number 65 in binary, capitalized a, “A” numString[2] = 0b1010111; // The decimal number 87 in binary, capitalized w, “W” numString[3] = 0x4E; // The decimal number 78 in hexadecimal, capitalized n, “N” ``` Now let’s see something else, assigning values through loops, it’s literally the same as filling an array through loops, you can use all sorts of looping methods as well, goes as follow; ```cpp // Let's fill this string with capitalized alphabets new message_7[26]; // The for loop for (new i = 0; i < 26; i++) message_7[i] = 'A' + i; // The while loop while (i++ < 'Z') message_7[i - 'A'] = i; // The do-while loop new j = 'A'; do { message_7[j - 'A'] = j; } while (j++ < 'Z'); // You can even use goto to simulate a loop, but it's not recommended. ``` All three of them will output the same exact string, _ABCDEFGHIJKLMNOPQRSTUVWXYZ_. If you found the loops above confusing, you might want to take a deeper look into how loops work, more on that can be found [here](../scripting/language/ControlStructures#loops) and [here](https://wiki.alliedmods.net/Pawn_Tutorial#Looping). Notice how I used characters in some logical conditions, like `j++ < 'Z'` that easily translates to `j++ < 90`, again, characters are treated like numbers, don’t feel strange, you’re welcome to check the _ASCII_ table whenever you’d like. Say, you want to fill a string with a number of one specific character, (e.g. “_AAAAAA_”, “_TTTTTT_”, “_vvvvvv_”, “_666_” (_no, it’s not a coincidence_)), the typical idea that might cross most of the scripters, is hard-coding it, but what about long strings, well, what about using a loop, that’s fine too, but what if I told you there is an even more efficient way, just like you’d fill an array with the same value, you’d do the same for strings. ```cpp new message_8[100] = {'J', ...}; ``` The code above declares a new string called `message_8` with 100 cells (_ranging from 0 to 99_) and gives each slot the value `'J'`, which of course can be used both as a character **J**, or number **74** according to the _ASCII_ system. One other thing you can do with this is filling the string with characters whom values based on intervals, see the example of the capitalized alphabets from _A_ to _Z_ above? Let’s create the same string using this method. ```cpp new message_9[26] = {'A', 'B', ...}; ``` How easy is that?! this is both more optimized and easy to read, and provides the same results as the 3 examples done using loop methods above, so how does it exactly work? Well, we gave the string initial values, `'A'` and `'B'`, which they respectively are _65_ and _66_, the compiler calculates the interval between the two values, which in this case is _1_, and completes filling the empty cells with values based on that interval until it fills up the whole array, you can put as many initial values as you want, but it will only regard the interval between the last two values, and work based on it, keep in mind that the initial values are treated as _ASCII_ code, so trying to output numeric intervals using this method on a string will result in something inconvenient, say you declared some random string like this; ```cpp new rand_str[5] = {'1', '5', ...}; ``` Ideally, this should have output **151520** (_more specifically “1 5 15 20”_), but instead, it output; **159=A**, which is actually the correct output, why? Because remember, this is _ASCII_ code, '_1_' is _49_ and '_5_' is _53_, the interval between the two is _4 (53 - 49)_, the string accepts 5 characters, we already occupied two cells when we included initial catalog, so that makes it 3 left empty cells that have to be filled respecting the interval of 4, so this is how it goes **[ 49 | 53 | 57 | 61 | 65 ]**, let’s replace each number value with its _ASCII_ code match. **[ '1' | '5' | '9' | '=' | 'A']**, makes more sense huh?! ## The null terminator I referred to this on early sections of this tutorial, I hope it wasn’t that confusing at first, but even if it was, let’s peal the confusion off already, don’t you worry, it’s nothing hard or even that advances, just a basic fact that you should be aware of, I’ll keep it as short as possible, but if you want a deeper view on this, you can visit [this article](https://en.wikipedia.org/wiki/Null_character). So, the null terminator (_aka the null character_), is a character present on all strings, its role is to indicate that a string has ended, you can think of it as a period mark (.) anything that comes after this character is not accounted for and completely ignored. You can’t type it using your keyboard, but you can refer to its value while coding, it’s present on the _ASCII_ table though, referred to as _NUL_, represented by the number 0. In _pawn_, you can type it as its numeric value, or as a character '_\0_'. The backslash there acts as an escaping character, it’s there to tell the machine that that character is the null character with the value of 0 and **NOT** the character `'0'` that has the value `48`. There is a symbol used in _pawn_, **EOS**, short for **E**nd **O**f **S**tring, it’s a predefined macro for the null terminator, you can set the null terminator in a lot of different ways; ```cpp message_9[0] = 0; message_9[0] = '\0'; message_9[0] = 0b; // The decimal number 0 in binary message_9[0] = 0x00; // The decimal number 0 in hexadecimal message_9[0] = _:0.0; // The floating number 0.0, we have to prefix it with the detag '_' to avoid compilation errors message_9[0] = false; message_9[0] = EOS; ``` As I said earlier on the tutorial, you can ignore assigning the null character, but it’s always there at empty cells, when you declare a new string, all of its cells are automatically occupied by the null terminator, so for instance, if I go ahead and declare this string `text[3]`, all of its cells are assigned the value of `0` by default, here’s a simple visual representation of the string’s content; | | | | | | ---------- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | | ASCII code | 0 | 0 | 0 | | Characters | '\0' | '\0' | '\0' | Here is another example of a pre-filled string. ```cpp new text_1[8] = "Hello"; ``` Here's the string's content per cell; | | | | | | | | | | | ---------- | --- | --- | --- | --- | --- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | ASCII code | 72 | 101 | 108 | 108 | 111 | 0 | 0 | 0 | | Characters | 'H' | 'e' | 'l' | 'l' | 'o' | '\0' | '\0' | '\0' | If you, for instance, wanted to delete the content of this string, you can simply do so using one of the three examples below; ```cpp text_1[0] = 0; text_1[0] = EOS; text_1[0] = '\0'; ``` Passing the string through an X-Ray scan will print out the following; | | | | | | | | | | | ---------- | ---- | --- | --- | --- | --- | ---- | ---- | ---- | | Cells | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | ASCII code | 0 | 101 | 108 | 108 | 111 | 0 | 0 | 0 | | Characters | '\0' | 'e' | 'l' | 'l' | 'o' | '\0' | '\0' | '\0' | If you try to output this string, everything beyond the slot number 0 will be ignored, and thus labeled as an empty string, even the `strlen` function will return 0 as it depends on the placement of the null character to retrieve the string’s length. ## String manipulation functions When it comes to working with multiple chunks of text, _pawn_ has got you covered, it provides some very basic functions that do the job efficiently, no need to create your own when you’ve got native support that assures speed and optimization. These are some natively supported functions (_taken from string.inc_); ```cpp native strlen(const string[]); native strpack(dest[], const source[], maxlength=sizeof dest); native strunpack(dest[], const source[], maxlength=sizeof dest); native strcat(dest[], const source[], maxlength=sizeof dest); native strmid(dest[], const source[], start, end, maxlength=sizeof dest); native bool: strins(string[], const substr[], pos, maxlength=sizeof string); native bool: strdel(string[], start, end); native strcmp(const string1[], const string2[], bool:ignorecase=false, length=cellmax); native strfind(const string[], const sub[], bool:ignorecase=false, pos=0); native strval(const string[]); native valstr(dest[], value, bool:pack=false); native bool: ispacked(const string[]); native uudecode(dest[], const source[], maxlength=sizeof dest); native uuencode(dest[], const source[], numbytes, maxlength=sizeof dest); native memcpy(dest[], const source[], index=0, numbytes, maxlength=sizeof dest); ``` We will take a closer look at few of them, the ones are more often used. - The `strlen` function (this and `sizeof` are completely different things), that takes a string as a parameter, returns the length of that string (the number of characters it has), but pay attention as this is a bit tricky on how it works, I’ve said it earlier in the tutorial, this function depends on the position of the null character to determine the length of the string, so any other valid non-null character that comes after will not be counted, as soon as the first null character is reached, the function returns the number of cells from the beginning to that null character. - The `strcat` concatenates strings with each other, it takes 3 parameters. ```cpp new str_dest[12] = "Hello", str_source[7] = " World"; strcat(str_dest,str_source); ``` If we were to output `str_dest`, it will show **Hello World**, the two strings were added to each other, and the result was stored in `str_dest`, _“Hello” + “ World” = “Hello World”_, notice how we included that space in the second string, yes, spaces are character themselves, according to the _ASCII_ table, their value is `32`, hadn't we add the space, the resulting string would have been **HelloWorld**. - The `strval` function will convert a string to a number, for instance, the following string, `"2017"` will be converted to the number `2017`, this works on signed and unsigned numbers, if the string has no numeric characters, the function will return `0`, the same happens if the string has a numeric character but begins with non-numeric ones, if a string begins with numeric characters but includes non-numeric characters as well, the numeric characters will still get retrieved and converted, here are some use cases; ```cpp strval("2018"); // Returns “2018”. strval("-56"); // Returns “-56”. strval("17.39"); // Returns “17”, the floating number 17.39 was auto floored for us. strval("no number here"); // Returns “0”. strval("6 starts"); // Returns “6”. strval("here we go, 2018"); // Returns “0”. strval("2017 ended, welcome 2018"); // Returns “2017”. ``` :::tip There are many community-made libraries you can download that have to do with string manipulation, I can’t think of a better include than [strlib](https://github.com/oscar-broman/strlib). ::: ### The format function This is probably the most used string-related function in the community, very simple and user-friendly, all it does, is format chunks of text and pieces them together, it can be implemented in various situations, like linking variables and strings together, embedding colors, adding line-breaks... etc. ```cpp format(output[], len, const format[], {Float, _}:...) ``` The format function takes as parameters the output array, its size (_number of its cells_), the formatting string (_this can be pre-stored on another array, or directly assigned from inside the function_), and finally some optional parameters, those can be variables from different types. Let’s use this function to assign a value to an empty string. ```cpp new formatMsg[6]; format(formatMsg, 6, "Hello"); ``` The output of `formatMsg` is **Hello**, keep in mind that this is a bad way of assigning values to strings, mostly because of its speed, there are better methods for doing this, we already discussed some of them on early stages of this tutorial. Remember to always put the correct array size, otherwise, it will still work, but it delivers some unwanted behavior, the format function will over-flow your array size, and trust me on that, you don’t want that to happen, if you don’t want to bother putting the correct string size every time you want to work with this function, you can simply use the `sizeof` function (_it’s not a function per se, but rather a compiler directive_), we’ve seen earlier a function called `strlen` that returns the number of characters a string has (_excluding and stopping at the null-character_), but this one, returns the array’s size, in other words, the number of cells this array has, be them filled with valid character or not, in this case, 6. ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), "Hello"); ``` Text must always be included in double quotation marks, however, there is an uncommon way of inputting text, that’s rarely ever used, it uses the Number sign `#` symbol, and works as follows: ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), #Hello); ``` It supports spaces, escaped characters, and you can even use the mix of both double quotations and the number sign; ```cpp new formatMsg[6]; format(formatMsg, sizeof(formatMsg), "Hello "#World); ``` The code above will input **Hello World**, this method of inputting strings is more known to be used with predefined constants. Let’s take a look at this example of using two different predefined constants, one being an integer `2017`, the other being a string `"2018"`. ```cpp #define THIS_YEAR 2018 // Thisconstant has an integer as its value #define NEW_YEAR "2019" // This constant has a string as its value new formatMsg[23]; format(formatMsg, sizeof(formatMsg), "This is "#THIS_YEAR", not"NEW_YEAR); ``` This will output **This is 2018, not 2019**, the reason why I emphasised on the two constants being from different types is the use of the number sign `#`, if the value is **NOT** a string, then you must prefix it with the number sign `#THIS_YEAR` so it will be treated like `"2018"`, or else you’ll get some compilation errors, as for a string value, you can choose to include or omit the number sign, because it will work either way (`NEW_YEAR` is the same as `#NEW_YEAR`). You can only use this to retrieve values from predefined constants, it will not work with regular variables, or arrays/strings, as treating those can be done using placeholders, more on this later. You can also line up as much double quotations as you want one next to each other, although it doesn’t make sense, as it’s more natural to just write a sentence into a single pair of double quotations, here’s an example of the same sentence written in both concepts; ```cpp new formatMsg[29]; // One single pair of double quotations format(formatMsg, sizeof(formatMsg), "This is reality...or is it?!"); // Multiple pairs of double quotations format(formatMsg, sizeof(formatMsg), "This is reality""...""or is it?!"); ``` Both will output the same sentence, **This is reality... or is it?!**. ## Optimization tips Now, that we’ve seen some basic stuff about string declaration, manipulation ...etc. some of us would just jump into practicing with no regards to some general guidelines followed by the community if only more people cared about readability, optimization, and performance the world would have been a better place. a code that compiles fine, doesn’t mean it works fine, most bugs come from those little things we overlooked or created in such a way that they wouldn’t interact friendly with other systems. a well-written code will survive the ordeal of time, how? You can always come back to it, and debug, fix, review it with ease, optimization will reflect result on the performance too, always try to get the best of your machine, and optimized code is the way to go. The first thing that must be brought up, and that personally triggers me, is seeing how large strings are being created when not nearly half of the cells declared are even used, only declare strings the size you’ll use, extra cells will only task more memory, let’s take a look at a supposedly unoptimized way of declaring a string. ```cpp new badString[100]; badString ="Hello :)"; ``` We declared a string with _100 cells_, _1 cell_ takes up _4 bytes_, let’s do some basic math, _100 \* 4 = 400_ bytes, that’s roughly _0.0004 Megabyte_, nothing for today’s standards I know, but supposedly, on a huge script, obviously you will have to use more than one string, _60_, _70_, heck _100_ more strings? (_possibly more_), those tiny numbers will stack up on each other resulting in a much bigger number, and cause you serious trouble later on, and believe me when I tell you, the string we declared doesn’t come as near to looking stupid when compared to the likes of those with a size five times bigger or more. What I come across more, something that’s stereotypically vague, is the usage of the mysterious string size -256-, just why people? Why? Keep in mind the limits SA-MP puts when dealing with strings, where does the _256-long_ string come into play? What are you going to do with a string this long (_except for formatting a dialog/textdraw string_)? The maximum string input is _128è characters long, that’s half the size, \_512 bytes_ just went into waste, say what? You intended to use it for output, not input? That’s still way too large, output strings are not to pass _144_ characters, see where I’m going? Let’s try and see how we’d correct our fault, we have this sentence, “Good string”, it contains _11_ characters (_the space is counted as a character too_) + _1_ for the null terminator (_got to always have this dude in mind_), that makes it _12_ characters in total. ```cpp new goodString[12]; goodString="Good string"; ``` See how we preserved memory? A mere **48** bytes, and no extra weigh that would cause trouble later, feels much better. But hey, what if I told you, you can get an even more optimized code, that’s right, have you ever heard of **packed strings**? A string is typically formed from multiple cells, and as we said earlier, each cell represents 4 bytes, so strings are made up of multiple sets of _4 bytes_. A single character takes up 1 byte, and each cell allows only a single character to be stored, meaning, that on each cell 3 bytes go to waste, ```cpp new upkString[5]; upkString = "pawn"; ``` The string above takes up 5 cells (_that is approximately 20 bytes_), can be narrowed down to only 8 bytes, a mere 2 cells. ```cpp new pkString_1[5 char]; pkString_1 = !"pawn"; // or pkString_1 = !#pawn; ``` That’s simply how it works, you declare a string with the size that it would normally take (_counting the null-terminator of course_), then suffix it with the with keyword `char`, each character will be stored in bytes rather than cells, meaning that every cell will have 4 characters stored, remember that when assigning values to packed strings, prefix them with an exclamation mark `!`, this, however, doesn’t apply for a single character. This is an approximate visual representation of `upkString`'s content; | | | | | | | | ---------- | -------------------- | -------------------- | -------------------- | -------------------- | ----------------- | | Cell | 0 | 1 | 2 | 3 | 4 | | Bytes | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | | Characters | \0 . \0 . \0 . **p** | \0 . \0 . \0 . **a** | \0 . \0 . \0 . **w** | \0 . \0 . \0 . **n** | \0 . \0 . \0 . \0 | And this is what `pkString_1` would be like in the second example; | | | | | ---------- | ----------------------------- | ----------------- | | Cell | 0 | 1 | | Bytes | 0 . 1 . 2 . 3 | 0 . 1 . 2 . 3 | | Characters | **p** . **a** . **w** . **n** | \0 . \0 . \0 . \0 | You can also access a packed string’s indexers, as follows; ```cpp new pkString_2[5 char]; pkString_2{0} = 'p'; pkString_2{1} = 97; // ASCII code for the character “a”. pkString_2{2} = 0b1110111; // The decimal number 199 in binary, translates to the character “w”. pkString_2{3} = 0x6E; // The decimal number 110 in hexadecimal, translates to the character “n”. pkString_2{4} = EOS; // EOS (End Of String), has the value of 0, which is the ASCII code for \0 (NUL), the null character. ``` The result will be the same as `pkString_1` in this case, as you can see, _ASCII_ code is still being taken into considerations, take notes that when accessing indexers on packed strings, we use **curly brackets** instead of **brackets**. That means we’re indexing the bytes themselves, and not the cells. :::info In spite of their effectiveness in preserving memory, SA-MP’s implementation of pawn doesn’t 100% support packed strings, but you can still use them in infrequently used strings/arrays. ::: ## String output #### Console ##### `print` The following function is probably the most basic function in not only pawn but a lot of other programming languages too, it simply accepts one parameter and outputs it on the console. ```cpp print("Hello world"); ``` ``` Hello world ``` You can also pass predeclared strings or predefined constants as well as merging multiple of them together, or use the number sign `#` too, much like we used to do with the format function, but keep in mind, that doesn’t include multiple parameters, we can only pass one and only parameter. ```cpp #define HAPPY_STRING "I'm happy today" // String constant. #define NEW_YEAR 2019 // Integer constant. new stylishMsg[12] = "I'm stylish"; print(HAPPY_STRING); print(stylishMsg); print(#2019 is beyond the horizon); print("I'm excited for "#NEW_YEAR); print("What ""about"" you""?"); ``` ``` I'm happy today I'm stylish 2019 is beyond the horizon I'm excited for 2019 What about you? ``` Notice how we used the number symbol here the same way we did with the format function, if the value is an integer, you prefix it with `#` so it’s treated as a string. Also keep in mind that the `print` function does support packed strings, however only accepts string type variables (_array of characters_), passing anything that’s not an array, a string (_be it between double quotations or prefixed by the number symbol_) will give compilation errors, so doing any of the following will not work; ```cpp // Case 1 new _charA = 'A'; print(_charA); // Case 2 new _charB = 66; print(_charB); // Case 3 print('A'); // Case 4 print(66); ``` Let’s see how we can fix that; ```cpp // Case 1 new _charA[2] = "A"; print(_charA); ``` We change the single quotation mark to the double quotation mark and give the array two cells, one of the A character, and the second one for the null terminator because anything between the double quotation marks is a string, the output is **A**. ```cpp // Case 2 new _charB[2] = 66; print(_charB); ``` We change the `_charB` to an array with one cell and set the cell labelled 0 to the value of `66`, which translates to **B** according to the _ASCII_ table, the output is **B**, we preserve an additional cell for the null-terminator (_how much is there so it's not funny anymore?_). ```cpp // Case 3 print("A"); ``` Not much can be said, all it took is switching from the single quotation marks to a pair of double quotation marks. As for the fourth case, there’s not much we can do while working with the `print` function, but it can simply be resolved using another similar function, called... ##### `printf` Short for “_print formatted_”, I can simply put, this is a more diverse version of the previous `print` function, more specifically, it’s like a combination between the `format` function and the `print` function, meaning that it also prints characters on the server’s console, but with the benefit of formatting the output text. Unlike `print`, `printf` accepts multiple parameters, and with different types too, however it does not support packed strings, in order to expand on its functionality, we use these sequences called “_format specifiers_”, more on them later, outputting anything more than **1024** characters will <u>crash the server</u>, so take notes on that. ```cpp #define RANDOM_STRING "Vsauce" #define RANDOM_NUMBER 2018 printf("Hey "RANDOM_STRING", Micheal here! #"#RANDOM_NUMBER); ``` Notice how we similarly to the `print` and the `format` functions, we nested those strings into one, which outputs the following; ``` Hey Vsauce, Micheal here! #2018 ``` The `printf` function as I said before, really shines when **format specifiers** are used, it’s what distinguishes it and sets it apart, you can attach as many variables as you want, and output simple and complex strings with ease, we will have a much deeper look on that when we’re introduced to those specifiers later on. #### Client messages Apart from the other doll texts you can print on the server’s console, who are mainly used for debugging, there are messages that are printed on the client’s screen, on the chat section, those ones can be formatted the same way too, but they also support color embedding, which makes for a wonderful presentation for texts (_if used correctly of course_). Keep in mind the that SA-MP’s restrictions on displaying strings apply for this type of messages too, being like the previous ones, limited to smaller than _144 characters_, or else the message won’t be sent, sometimes they will even crash some commands. There are two functions that natively print text on the client’s screen, the only difference between them is the scoop, the first takes three parameters, the id of the player you want to print the text on their screen, the text’s color, and the text itself. ```cpp SendClientMessage(playerid, color, const message[]) ``` Say, you want to send a text to the player whose id’s 1, telling them “Hello there!”; ```cpp SendClientMessage(1, -1, "Hello there!"); ``` Simple, just like that, the player with the ID of 1 will be sent a text saying **Hello there!**, the `-1` is the color parameter, in this case, it’s the color **white**, more on colors later. Obviously, you can also pass an array of characters, formatted strings...etc. And as we saw with other function, you can use the number sign `#`. ```cpp #define STRING_MSG "today" new mornMsg[] = "Hello!"; SendClientMessage(0, -1, mornMsg); SendClientMessage(0, -1, "How are you ",STRING_MSG#?); ``` As you can see at the example above, this will send the player with the id _0_ two messages colored in white, the first messages will say “_Hello!_”, and the second will say, “_How are you today?_”, pretty similar to how other functions work. Keep in mind that predefined constant integers must be prefixed with the `#` symbol. ```cpp #define NMB_MSG 3 SendClientMessage(3, -1, "It's "#NMB_MSG" PM"); ``` Pretty self-explanatory, the text will be sent to the player with the id _3_, colored in white, saying “_It’s 3 PM_”. Now that you know how to send someone a message, you can use the same approach to send the same message to everyone, child’s play really, you can just put the function in a loop that goes through all connected players, and risk showing your code in public and call it a day, but hey, there is already a native function that does the exact same thing, the same rules apply, the only thing that differ between the two is a slight change in their syntax. ```cpp SendClientMessageToAll(color, const message[]); ``` pretty self-explanatory too, exposed by its name, now let’s send everyone on the server a greeting message. ```cpp SendClientMessageToAll(-1, "Hello everyone!"); ``` Just like that, you can play with it the same way you do with its other sibling, two toys from the same brand really, just try not to bypass the 144 characters limit. #### Textdraws One of SA-MP’s most powerful functionalities, just unleash your imagination, textdraws are basically graphic shapes/texts/sprites/preview models...etc. that can be displayed on clients’ screens, they make the UI especially much more lively and interactive (_to an extent_). But hey, there are limitations here too, for example, you cannot display a string that’s more than 1024 characters long, to be honest, that’s more than enough. Nothing special can be said here, even with their wide functionality, strings that can be displayed are poor on formatting, you can’t do as much as you could with other output functions, it feels a little narrow when it comes to this, but it certainly does make up for the lack of formatting with other exciting stuff, more on textdraws [here](../scripting/resources/textdraws). #### Dialogs Dialogs can be thought of as “_message boxes_”, they, of course, come in different types, accept few different inputs, and more importantly, accept all types of formatting that a normal string does, with makes them much easier to use than textdraw. There are limitations concerning them too, like string sizes and being able to only synchronously display them on the client’s screen, SA-MP only provides one native function for dealing with dialogs, and honestly, that would be one of your last concerns, as the lone function does its job, and does it efficiently, more on dialogs [here](../scripting/functions/ShowPlayerDialog). ### Color interpretation #### Client messages and dialogs ##### RGBA **RGBA** (_short for red green blue alpha_), is a simple use of the **RGB** model with an extra channel, the alpha channel, basically, a form of representing colors digitally, by mixing variations of red, green, blue and alpha (_opacity_), more on that [here](https://en.wikipedia.org/wiki/RGBA_color_space). In SA-MP’s implementation of pawn, we use hexadecimal numbers to represent these color spaces, red, green, blue and alpha are noted by 2 bits each, resulting in an 8 bits long hexadecimal number, for example; (_FF0000FF = red_), (_00FF00FF = green_), (_0000FFFF = blue_), (_000000FF = black_), (_FFFFFFFF = white_), here’s a clearer visualization on this notation: > <span style={{ color: 'red' }}>FF</span><span style={{ color: 'green' }}>FF</span><span style={{ color: 'blue' }}>FF</span><span style={{ color: 'grey' }}>FF</span> A lot of programming/scripting languages prefix hexadecimal numbers with the number sign `#`, In pawn, however, we prefix them with `0x`, so the following hexadecimal number _8060C1FF_, becomes _0x8060C1FF_. We can, of course, use decimal numbers to represent colors, but it’s much clearer to use the hexadecimal notation, as it’s the more readable between the two, let’s look the following example; ```cpp // Representing the color white with decimal numbers SendClientMessageToAll(-1, "Hello everyone!"); // Representing the color white with hexadecimal numbers SendClientMessageToAll(0xFFFFFFFF, "Hello everyone!"); // A client message colored in white will be sent to everybody ``` Keep in mind that assigning all bits to the same value will result in variations of shades of grey (_no pun intended_), assigning the alpha channel to 0 will make the text invisible. :::tip It’s possible to format texts with multicolor simultaneously, but for that, we embed the simpler **RGB** notation. ::: ##### RGB This is exactly like the **RGBA** color spaces, but with no alpha channel, just a mixture of red, green and blue, noted as a hexadecimal number of 6 bits, in pawn, this notation is used mostly to embed colors into texts, simply wrap your 6 bits hexadecimal number between a pair of curly brackets, and you’re set up to go, for example; (**{FF0000} = red**), (**{00FF00} = green**), (**{0000FF} = blue**), (**{000000} = black**), (**{FFFFFF} = white**), here’s a clearer visualization on this notation: `{FFFFFF}`. Let’s look at this quick example here; ```cpp SendClientMessageToAll(0x00FF00FF, "I'm green{000000}, and {FF0000}I'm red"); ``` This will send the following message to everyone (_and I'm no Italian_): > <span style={{color: '#00ff00ff'}}>I’m green</span><span style={{color: '#ffffff'}}>, and </span><span style={{color: '#ff0000'}}>I’m red</span> Keep in mind that the hexadecimal notation is case insensitive, so typing `0xFFC0E1FF` is the same as typing `0xfFC0e1Ff`, the same goes for embedded colors, `{401C15}` is the same as `{401c15}`. Sometimes, working with colors can prove to be quite the labor, It’s not that easy to go around remembering all of those long hexadecimal numbers like no big deal, You should always have a reference to go back to, there are plenty of online color pickers you can use, you can simply google “_color picker_”, and choose between thousands of them, let me do that on you if you don’t mind, [here’s a simple tool](https://www.webpagefx.com/web-design/color-picker/) that I recommend using when working with colors. One of the problems that people find, is managing their workflow, which if done right, it facilitates the work pacing, and makes it less painful to work around your projects, while color picker tools are of a great help, you can still waste plenty of time going on and off to it every time you need to pick a color, the frustration of that can be as annoying as a pizza with pineapples, luckily, you can take advantage of predefined constants, and define your most used colors for later usage, here’s a simple example; ```cpp #define COLOR_RED 0xFF0000FF #define COLOR_GREEN 0xFF0000FF #define COLOR_BLUE 0xFF0000FF SendClientMessageToAll(COLOR_RED, "I'm a red text"); SendClientMessageToAll(COLOR_GREEN, "I'm a green text"); SendClientMessageToAll(COLOR_BLUE, "I'm a blue text"); ``` The latter can be done on embedded colors too; ```cpp #define COL_RED "{FF0000}" #define COL_GREEN {FF0000} #define COL_BLUE "{FF0000}" SendClientMessageToAll(-1, ""COL_RED"I'm a red text"); SendClientMessageToAll(-1, "{"COL_GREEN}"I'm a green "COL_BLUE"and blue"); ShowPlayerDialog(playerid, 0, DIALOG_STYLE_MSGBOX, "Notice", "{"COL_GREEN"}Hello! "COL_RED"what's up?", "Close", ""); ``` At compilation time, all predefined constants will be replaced by their values, and thus, this `"COL_RED"I’m a red text` becomes this `”{FF0000}”I’m a red text`, notice how we used two methode to predifne those colors, `RRGGBB` and `{RRGGBB}`, it’ goes into personal preference which methode to go by, personaly, I find defining them as `RRGGBB` much cleared, as the usages of curly brackets is present, and thus makes it noticable that we’re embedding a color. That was the general approach on color embedding with dialog and client messages strings, it is possible to use colors within text in client messages, dialogs, 3D text labels, object material texts and vehicle number plates, but hey, SA-MP has also texdraws and gametexts functionalities, however those don’t support the RGB notation, and thus, adding colors is done differently. #### Textdraws and Gametexts as mentioned above, **RGB** notation is not supported, but luckily, we have other ways to work around this problem, for textdraws, you can use the native [TextDrawColor](../scripting/functions/TextDrawColor) function to change the textdraw's color, but this the same to textdraw as **RGBA** color spaces are to client messages and dialogs, they can’t be embedded, for that, we use special combination of characters to refer to colors and few other symbols, you can see them [here](../scripting/resources/gametextstyles). | | | | -------------- | ------ | | \~r\~ | Red | | \~g\~ | Green | | \~b\~ | Blue | | \~w\~ or \~s\~ | White | | \~p\~ | Purple | | \~l\~ | Black | | \~y\~ | Yellow | So, embedding colors can go in like this: **\~w\~Hello this is \~b\~blue \~w\~and this is \~r\~red** You can use another combination of characters to play with color mixes, **\~h\~**, it makes a certain color lighter, here are few examples: | | | | ------------------------------ | -------------- | | \~r\~\~h\~ | Lighter red | | \~r\~\~h\~\~h\~ | Red pink | | \~r\~\~h\~\~h~\~h\~ | Dark red | | \~r\~\~h\~~h~~h~~h\~ | Light red pink | | \~r\~\~h\~\~h\~\~h\~\~h\~\~h\~ | Pink | | \~g\~\~h\~ | Light green | You can find more information about this [here](../scripting/resources/colorslist). ### The escape character #### Description The escape character is a character in which when prefixed to some character or number, it creates its own constant character, in most programming/scripting languages like pawn, the backslash is used as the escape character (`\`), a combination of this and some other character/number will result in an [escape sequence](https://en.wikipedia.org/wiki/Escape_sequence) which has a certain meaning, you can find more about escape character [here](https://en.wikipedia.org/wiki/Escape_character). #### Escape sequences Escape sequences make it easier to express certain characters in the source code of your script, here is a table containing the escape sequences used in pawn: | | | | -------------------------------------------- | ------------ | | Audible beep (on server machines) | `\a` or `\7` | | Backspace | `\b` | | Escape | `\e` | | Form feed | `\f` | | New line | `\n` | | Carriage return | `\r` | | Horizontal tab | `\t` | | Vertical tab | `\v` | | Backslash | `\\` | | Single quote | `\'` | | Double quote | `\"` | | Character code with decimal values "ddd" | `\ddd;` | | Character code with hexadecimal values "hhh" | `\xhhh;` | Let’s look at each one of them, after all, the best way to learn these sort of stuff rests within practicing them. - **The “Audible beep” escape sequence - `\a`** Audible beep or a bell code (_sometimes bell character_) is a device control code originally sent to ring a small electromechanical bell on tickers and other teleprinters and teletypewriters to alert operators at the other end of the line, often of an incoming message. Using this on a computer will result in sending a bell/notification sound in the background, it can be used in some creative ways, to notify and/or alert users on certain activities, the escape sequence that represents it is `\a` (or `\7` noted as decimal code), fire off your pawn text editor, and write the following code; ```cpp print("\a"); ``` Upon executing the samp-server.exe, you will hear a beep notification sound, you can also use the decimal code; ```cpp print("This is a beep \7"); ``` - **The “Backspace” escape sequence - `\b`** This escape sequence is noted as `\b`, it simply moves your cursor backward, most people would expect it to act like the backspace button on your typical keyboard, but not entirely, it only moves the carriage one position backward without erasing what’s written there. This one doesn’t have that much usability in pawn unless you were clever enough to milk something useful out of it, here’s how it works. ```cpp print("Hello 2018"); ``` This will print **Hello 2018** in the console, the cursor remains on the null character’s position, more clearly, like this: ``` Hello 2018 ^ ``` As you can see, the cursor stops after the last visible character of the string, which is normal, now, let’s add a backspace escape sequence; ```cpp print("Hello 2018\b"); ``` That will result in; ``` Hello 2018 ^ ``` As you can see, the cursor is exactly in the position of the last visible character of the string, which is _8_, this is the same as toggling on the insert mode on your keyboard, now, let’s add some sorcery to this. ```cpp print("Hello 2018\b9"); ``` If you guessed it right, yes, this will print **Hello 2019**, so, let’s see how this works, the machine will process the string character by character, until it reaches the backspace escape sequence, then it moves the carriage one position backwards, which selects whatever character there, in this case 8, then, it inserts 9 in its place. ``` Hello 2019 ^ ``` The carriage is going to move backward as long as there is a backspace escape sequence in your string. ```cpp print("Hello 2018\b9\b\b\b"); ``` ``` Hello 2019 ^ ``` The cursor will stop at the first character’s position if the amount of backspace escape sequence exceeded that of the number of characters between the position of the first character (yes, arrays start at 0, head to [r/programmerhumor](https://www.reddit.com/r/ProgrammerHumor/) for some good memes) and the initial position of the cursor. ```cpp print("Hi\b\b\b\b\b\b\b\b\b\b\b\b\b\b"); ``` Will always result in this; ``` Hi ^ ``` - **The “Escape” escape sequence - `\e`** With the hexadecimal value of 1B in _ASCII_, it’s used for common non-standard code, let’s look for some programming languages like C as an example; a sequence such as `\z` is not a valid escape sequence according to the C standard. The C standard requires such invalid escape sequences to be diagnosed (the compiler must print an error message). Notwithstanding this fact, some compilers may define additional escape sequences, with implementation-defined semantics. An example is the `\e` escape sequence, represents the escape character. It wasn't however added to the C standard repertoire because it has no meaningful equivalent in some character sets. - **The “Form feed” escape sequence - `\f`** Form feed is a page breaking _ASCII_ code. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return, this doesn’t make any noticeable change in the _SA-MP_’s debugging console. - **The “New line” escape sequence - `\n`** The new line (also referred to as line ending, end of line (_EOL_), line feed, or line break) escape sequence is an _ASCII_ code that’s noted as `/n` with the decimal value of 10, it’s something that’s commonly used, text editors are inserting this character every time we press the Enter button on our keyboards. Here’s a simple message with a line break: ```cpp print("Hello, this is line 1\nAnd this is line 2"); ``` That will simply output: ``` Hello, this is line 1 And this is line 2 ``` Multiple line brakes are achievable of course; ```cpp print("H\n\n\ne\n\n\nl\nl\n\no"); ``` ``` H e l l o ``` This works differently when dealing with files, however, depending on your operating system, like for instance, in windows, a line break is typically a **CR** (_carriage return_) + **LF** (_line feed_), you can learn more about the differences [here](https://en.wikipedia.org/wiki/Newline). - **The “Carriage return” escape sequence - `\r`** The carriage return is an _ASCII_ code that’s often associated with the line feed, but it can serve as its own thing by itself, it simply moves the carriage to the beginning of the current line, equivalent of a specific case we discussed using multiple backspaces (`\b`) escape sequence, let’s look at the following example, without using this escape sequence, this is the normal output we would get: ```cpp print("Hello"); ``` ``` Hello ^ ``` The arrow represents the position of the cursor, which is placed after the last visible character of the string, again, that’s the normal expected behavior, now let’s add the carriage return into the mix: ```cpp print("Hello\r"); ``` ``` Hello ^ ``` The cursor is shifted to the beginning of the line, selecting the first character **“H”**, now inserting anything will change **“H”** to whatever we input, and then move to the next character while remaining on the insert mode: ```cpp print("Hello\rBo"); ``` ``` Hello ^ ``` As we’ve seen on the line feed section, line breaks work differently across different operating systems, windows, for instance, use a carriage return followed by a line feed to perform a line break, just like the classic typewriters. - **The “Horizontal tab” escape sequence - `\t`** Tabulation is something we use every day, from text/code indentation, to table display, that tabulator key that lays at the very side of your keyboard really is a time saver, it was such a pain and so much time consuming to excessively use many spaces, but this one cuts the cake easily, not only is it usefully practically, it really is strongly present in the field of programming, it’s noted as `\t`, people would argue on how many spaces a tab is worth, most would say it’s worth 4 spaces, but there are who say it’s worth 8 spaces, someone demonic creature would even prefer spaces to tabs, but that's another talk on inself, let as observe this simple example: ```cpp print("Hello\tWorld"); ``` ``` Hello World ``` Here is another one with multiple tabulations: ```cpp print("Hello\t\t\t\t\tWorld"); ``` ``` Hello World ``` - **The “Vertical tab” escape sequence - `\v`** During the old typewriter era, this had a more popular use, it was used to move to the next line vertically, but now, this is no longer the case, it doesn’t have any noticeable usage nowadays, and that includes modern printers and even programming languages, and pawn is no exception. - **\_The “Backslash” escape sequence - `\*`** As we’ve seen, the backslash is regarded as the escape character, so whenever the program spots it, it thinks of it as a starting point of some escape sequence, it doesn’t look at it as an independent character, and thus, will either give a compilation error (_if it wasn’t followed by a valid character_), or will not print it, in pawn’s case, the compilator will raise an error (_error 027: invalid character constant_). Luckily, we can solve this problem by escaping out backslash, and that’s done by prefixing yet another backslash to it: ```cpp print("Hello \\ World"); ``` ``` Hello \ World ``` :::caution ­Warning The output will disregard the first backslash, and print the second, as the first is escaping the second and tricking the program into viewing it as a raw character. A backslash can only escape one character at a time, so doing the following will raise a compilation error. ::: ```cpp print("Hello \\\ World"); ``` Think of it as pairs of backslashes, everyone is escaping the one after, and thus, it should always result in an even number of backslashes; ```cpp print("Hello \\\\\\ \\ World"); ``` ``` Hello \\\ \ World ``` As you surely noticed, escape sequences are never printed, they only serve as instructions that express certain events, if we want to force them into being printed, we can escape their escape character (`\`), then the program will not look at them as escape sequence: ```cpp print("This is the escape sequence responsible for tabulation: \\t"); ``` The first backslash escapes the second, and then it gets printed, then the **t** character is left alone, and thus regarded as an independent character: ``` This is the escape sequence responsible for tabulation: \t ``` - **The “Single quote” escape sequence - `\'`** This is hardly present when writing pawn code, I myself haven’t found myself using this in any coding situation, in other languages that treat text between single quotation marks as a string make great use of this to limit the confusion that happens when nesting single quotation marks into each other, it really makes no difference in pawn, here’s a simple example; ```cpp print("Single quote '"); // or print("Single quote \'"); ``` Either way, the output will be the same: ``` Single quote: ' ``` The only use I can think of concerning this is setting a variable the character “**'**”, so obviously doing the following will cause a compilation error; ```cpp new chr = '''; ``` Simply because the compiler will regard the first pair of single quotes as one entity, and the second as an unclosed quotation sequence, so to fix that, we will have to escape the middle one; ```cpp new chr = ''\'; ``` - **The “Double quote” escape sequence - `\"`** Unlike the single quotation mark, this one can cause problems when it comes to nesting them together, pawn treats anything between double quotations as a string, so what if you want to input a double quotation mark in your string, that will confuse the program, it wouldn’t know what each quotation mark is for, let’s take this as an example for instance: ```cpp print("Hello "world"); ``` As soon as the compilator spots the first quotation marks, it will treat everything that comes after as part of one string, and end up the process as soon as it hits another quotation mark, and thus, the compiler will pick up **“Hello “** as a string and will view **World”** as some none-sense filling up the holes of your code. To solve this, we need to escape the double quotation mark we want to print: ```cpp print("Hello \"world"); ``` Now, the compiler will treat the second quotation mark as an escape sequence as it’s prefixed by an escape character (**\\**): ``` Hello "world ``` Let’s add another quotation mark just for the heck of it: ```cpp print("Hello \"world\""); ``` ``` Hello "world" ``` It couldn’t be simpler. Throughout this section, we’ve seen how we can represent escape sequences by prefixing the escape character (`\\`) to a certain character, but that’s just one way to note those values, among other ways, we will take a look on two others; - **Escape sequences with character code (decimal code) - `\ddd;`** It doesn’t change anything about the escape sequences, it’s just a different way to express them, using decimal _ASCII_ codes, for instance, if you want to print A, but note it decimally, you can type it’s decimal _ASCII_ code like the following: ```cpp print("\65;"); ``` This doesn’t concern only alphanumeric characters, but also other ones, like the audible beep (`\a`), with its decimal value `7`, can be represented according to this notation as `\7`; The semicolon mark is optional and can be dropped, but it’s always better to go with the original approach, its purpose is to give the escape sequence an explicit termination symbol when it is used in a string constant. - **Escape sequences with character code (decimal code) - `\xhhh;`** Similar to the decimal _ASCII_ notation, we can also use the hexadecimal format, the character **A**, can either be written as `\65`;** or `\x41`;**, The _semi-colon_ can be omitted if you want, this applies both here and on the decimal notation. ```cpp print("\x41;"); ``` ``` A ``` You can find all of those values by simply googling “**ASCII table**”, and what’s cool about it is that it’s free. #### Custom escape character If you noticed, I’ve kept calling repeating the “**escape character**” multiple times throughout the last section where I could have referred to it simply as “**the backslash**”, or even shorted, (`\`), the reason for that is because the escape character is not an absolute constant character, but rather, it can be changed preferably, you can have it as _@, ^, \$_ and so on, by default it’s a backslash, but how it stays is only determined by you. n order to change it, we use the pre-processor directive `pragma`, this particular directive accepts different parameters, for each their specific task, and there is one that's responsible on setting the escape character which we will be focusing on, it's `ctrlchar`. ```cpp #pragma ctrlchar '$' main() { print("Hello $n World"); print("This is a backslash: \\"); print("The his a dollar sign: $$"); } ``` ``` Hello World This is a backslash: \ This is a dollar sign: $ ``` As you can see the line feed is noted as `$n` instead of `\n` now, and the backslash is no longer regarded as the escape character, and consequently, the dollar sign requires being escaped by another dollar sign. You can’t, however, change this to (`-`), but anything else is an acceptable practice, but it’s never ever accepted ethically, just how silly is this `#pragma ctrlchar '6'`, huh? Absolute mad lad. This portion here has absolutely nothing to do with escape sequences, but it is used in formatting textdraws and gametext, it’s better to put it here than anywhere else; | | | | ----- | ------------------------------------------------------------------------------------------------------------- | | `~u~` | Up arrow (gray) | | `~d~` | Down arrow (gray) | | `~<~` | Left arrow (gray) | | `~>~` | Right arrow (gray) | | `]` | Displays a `*` symbol (only in text style 3, 4, and 5) | | `~k~` | keyboard key mapping (e.g. `~k~~VEHICLE_TURRETLEFT~` and `~k~~PED_FIREWEAPON~`). Look here for a list of keys | keyboard key mapping (e.g. `~k~~VEHICLE_TURRETLEFT~` and `~k~~PED_FIREWEAPON~`). Look here for a list of keys ### Format specifier #### Description Placeholders or specifiers are characters escaped by a percent sign (`%`), the indicate the relative position and the output type of certain parameters, they serve as their name suggests “_Placeholders”_, they save a place for data that will later replace them inside the string, there are different types of specifiers, and they even follow a specific formula; ``` %[flags][width][.precision]type ``` The attributes between brackets are all optional and are up to you-the-user to either keep them or not, what really defines a specifier the wide known format of **%type**, the type part is replaced by a character to represent a certain output type; (_integer, float... etc_). Placeholders are only used on functions that accept parameters, thus functions like print will have no effect, an alternative to it is the more advanced `printf`. Let us look at the different output types that can be used: | | | | ------------- | ----------------------------------------------- | | **Specifier** | **Meaning** | | `%i` | Integer (_whole number_) | | `%d` | Integer (_whole number_) | | `%s` | String | | `%f` | Floating-point number (`Float: tag`) | | `%c` | ASCII character | | `%x` | Hexadecimal number | | `%b` | Binary number | | `%%` | Literal `'%'` | | `%q` | Escape a text for SQLite. (_Added in 0.3.7 R2_) | - **The integer specifiers - `%i` and `%d`** Let’s wrap the both together, in pawn, these two specifiers do the same exact thing, both output integers, even though `%i` stands for integer and `%d` stands for decimal, they are a synonym to the same thing. In other languages, however, the difference lays not in the output, but rather the input with functions like `scanf`, where `%d` scans an integer as a signed decimal, and %i defaults to decimal but also allows hexadecimal (_if preceded by `0x`_) and octal (_if preceded by `0`_). The usages of these two specifiers go as follows: ```cpp printf("%d is here", 2018); printf("%d + %i = %i", 5, 6, 5 + 6); ``` ``` printf("%d is here", 2018); printf("%d + %i = %i", 5, 6, 5 + 6); ``` The output also supports pre-defined constants, variables, and functions too. ```cpp #define CURRENT_YEAR 2018 new age = 19; printf("It’s %d", CURRENT_YEAR); printf("He is %d years old", age); printf("Seconds since midnight 1st January 1970: %d", gettime()); ``` ``` It's 2018 He is 19 years old Seconds since midnight 1st January 1970: 1518628594 ``` As you can see, any value we pass in the parameters of the `printf` function is being replaced by its respective placeholder, and remember, **order matters**, your placeholders should follow the same order as your parameters in the call, and always use the correct specifier type, not doing so, will not result in an error, but it may output in some unwanted results, but in some cases, those unwanted results are what we want. What do you think will happen if we tried to print a float or a string using an integer specifier? Let’s find out; ```cpp printf("%d", 1.12); printf("%d", "Hello"); printf("%d", 'H'); printf("%d", true); ``` ``` 1066359849 72 72 1 ``` How odd, totally unexpected, but not necessarily useless, this exact behavior is taken advantage of in so many situations. First of all, let’s see why did `1.12` output _1066359849_, well, that's something called undefined behavior, you can learn more about this [here](https://en.wikipedia.org/wiki/Undefined_behavior). Trying to output a string using an integer specifier will give its first character’s _ASCII_ code, in this case, the character H’s code, 72, the same happens to the output of a single character. And finally, outputting a Boolean will give 1 if it’s true, and 0 if it’s false. Strings are arrays in themselves, so outputting an array here will give the value of the first slot in that array, how it’s going to be output depends on which type it is (_integer, float, character, boolean_). - **The string specifiers - `%s`** This specifier, as it stands for string, is responsible for outputting strings (_obviously_): ```cpp printf("Hello, %s!", "World"); ``` ``` Hello, world! ``` Let’s also output non-string values using this too: ```cpp printf("%s", 103); printf("%s", true); printf("%s", 'H'); printf("%s", 1.12); ``` ``` g H ) ``` The number `103` was treated as the _ASCII_ code for _g_, and thus _g_ was printed, same goes for the strange symbol below it, the character with the value true, a.k.a _1_ was printed, more simply, the character `'H'` was printed as it is, but hey, what happened to the floating number `1.12`? remember the **undefined behavior**? Yeah, `1.12` resulted in a huge integer, which kept overflowing (its value divided by _255_) times, until it resulted in a number between _0_ and _254_, in this case, _40_, which is the _ASCII_ code of the character _(_. Again, just like the integer specifier, this accepts pre-defined constants, variables, and functions: ```cpp #define NAME "Max" new message[] = “Hello there!”; printf("His name is %s", NAME); printf("Hey, %s", message); printf("%s work", #Great); ``` ``` His name is Max Hey, Hello there! Great work ``` - **The float specifiers - `%f`** This specifier -short for float-, as its name suggests, it outputs floating numbers, on earlier sections, we tried to output floating numbers using the integer specifier, and then we got that undefined behavior, but now, that we know about this specifier, we can safely output floats with no problems; ```cpp printf("%f", 1.235); printf("%f", 5); printf("%f", 'h'); ``` The _1.235_ floating number got output just fine, with the addition of some padding, however, the rest of all output _0.000000_, basically _0_, that’s because the `%f` specifier will only output floating numbers, in other words, numbers that have no fixed number of digits before and after the decimal point; that is, the decimal point can float. To fix that issue, we simply add the fractional part: ```cpp printf("%f", 5.0); printf("%f", 'h' + 0.0); ``` ``` 5.000000 104.000000 ``` Although the `%f` is the most commonly used floating placeholder, the `%h` specifier does pretty much the same: ```cpp printf("%h", 5.0); ``` ``` 5.000000 ``` - **The character specifiers - `%c`** This specifier, short for character, works like the string placeholder, but it only outputs a single character, let’s observe the following example: ```cpp printf("%c", 'A'); printf("%c", "A"); printf("%c", "Hello"); printf("%c", 105); printf("%c", 1.2); printf("%c", true); ``` ``` A A H i s ``` As you can see, passing a string will output only the first character and passing a number will output the character whose _ASCII_ code matches that number (_Booleans are converted to 0 and 1 respectively_). - **The hexadecimal specifiers - `%x`** The following specifier outputs the value we pass as a hexadecimal number, simply put, a conversation of numbers from a given base to base 16. ```cpp printf("%x", 6); printf("%x", 10); printf("%x", 255); ``` ``` 6 A FF ``` Just like the cases we saw on earlier sections, passing values other than integers will convert them to their respective integer values, and output them as hexadecimal numbers; ```cpp printf("%x", 1.5); printf("%x", 'Z'); printf("%x", "Hello"); printf("%x", true); ``` ``` 3FC00000 5A 48 1 ``` The first value `1.5`, will result in an undefined behavior upon its conversion to an integer (_1069547520_), then the resulting integer will be output as a hexadecimal (_3FC00000_), The `'Z'` character, will have its _ASCII_ value (90) converted to hexadecimal (5A). The string `"Hello"` will only have its first character (H) with the _ASCII_ value of (72) converted to hexadecimal (48). And `true` outputs (1) as a hexadecimal, which is converts to (1), (false will output 0). - **The binary specifiers - `%b`** The following specifier, short for “_binary_” is used to print passed values as binary numbers, passing characters will convert its _ASCII_ code into binary, and so is the case for strings where only the first character is regarded, Booleans are regarded as true and false respectively, float numbers fall under the case of undefined behavior, as for integers and hexadecimal, they are converted to binary and output. ```cpp printf("%b", 0b0011); printf("%b", 2); printf("%b", 2.0); printf("%b", 0xE2); printf("%b", 'T'); printf("%b", "Hello"); printf("%b", true); ``` ``` 11 10 1000000000000000000000000000000 11100010 1010100 1001000 1 ``` - **The literal `%`** Much like the default escaping character (`\`), the compiler views (`%`) as a special character, and thus treats the sequence as a placeholder, as long as there is a character after the (`%`) it’s regarded as a specifier even if it’s not valid, let’s observe these two cases; ```cpp printf("%"); printf("Hello %"); printf("% World"); printf("Hello % World"); ``` ``` % Hello % World Hello World ``` As you can see, having (`%`) alone as an individual sequence will have it output, but not the same happens when it’s followed by space or any other character, thus it results in outputting a space character. To trespass this problem, we escape it using another percent sign as follows; ```cpp printf("This is a percent sign %%, we just had to escape it!"); ``` ``` This is a percent sign %, we just had to escape it! ``` Of course, this only concerns functions that support formatting, such as `printf` and `format`, for example, trying to output a percent sign using the `print` function will not require you to escape it. - **The `%q` specifier** This one doesn’t hold any big importance in our main topic, it’ widely used to escape sensitive strings when working with _SQLite_, and trust me, nobody wants to fall under the [Bobby table](http://bobby-tables.com/about) case. Back when we introduced the placeholders, we reference a specific formula concerning them, as a reminder, here it is; ``` %[flags][width][.precision]type ``` So far, we have only talked about the `%` sign and the type filed, the others are optional, but each one is effective on different cases, you can include them to better control how your values are treated when they are output. - **The width filed** This one is responsible for specifying the minimum character output, it can be omitted if needed, you just have to type its value as a numeric integer, let’s look at some examples; ```cpp printf("%3d", 5555); printf("%3d", 555); printf("%3d", 55); printf("%3d", 5); ``` ``` 5555 555 55 5 ``` We instructed the specifier to lock the output to 3 characters or more, at first, outputting 4 and 3 characters number long went fine, but the characters shorter than 3 characters were left padded with spaces to even the output width. There is also the ability to have dynamic width values, for that, we use the asterisk sign (`*`). ```cpp printf("%*d", 5, 55); ``` ``` 55 ``` First, we pass the width’s value which was `5`, then the value we want to output `55`, so the placeholder outputs a minimum of 5 characters, that’s 5 minus 2, which gives us 3 spaces of padding. - **The flags field** This one works really well with the width field, as the width specifies the minimum characters to outputs, this one pads the emptiness left behind with whatever you tell it to. In case there were to spaces left behind, there won’t be any pad. ```cpp printf("%3d", 55); printf("%5x", 15); printf("%2f", 1.5) ``` ``` 055 0000F 01.500000 ``` The first number 55, is short on one character because of the width of the decimal parameter, so it’s padded by one 0. As for 15, it’s converted to its respective hexadecimal value _F_, and padded with 4 0’s to validate the width of its placeholder. Notice how only the number before the decimal point was padded. The use of dynamic width values remains here too, we just have to include the asterisk, pass a value, and watch the magic happen; ```cpp printf("%0*d", 5, 55); ``` ``` 00055 ``` - **The precision field** The Precision field usually specifies a maximum limit on the output, depending on the particular formatting type. For floating point numeric types, it specifies the number of digits to the right of the decimal point that the output should be rounded. For the string type, it limits the number of characters that should be output, after which the string is truncated. ```cpp printf("%.2f", 1.5); printf("%.*f", 10, 1.5); printf("%.5s", "Hello world!"); printf("%.*s", 7, "Hello world!"); ``` ``` 1.50 1.5000000000 Hello Hello w ``` As you can see, dynamic precision values can be used both with the float and the string placeholders. A really cool trick we can pull off thanks to the precision field is get substrings, now, now, there are plenty of methods we can use to do that, and that without regarding the native [strfind](../scripting/functions/strfind) function, and let’s not forget the amazing functions we got at **Slice**’s [strlib](https://github.com/oscar-broman/strlib) include. Let’s see how we can get the same result using only the precision field. ```cpp substring(const source[], start = 0, length = -1) { new output[256]; format(output, sizeof(output), "%.*s", length, source[start]); return output; } ``` Let’s try to decipher this chunk of code, we simply pass the source string, (the string we are going to extract from), a starting position (the slot we are going to start extracting at), and the length of the characters we want to extract. Our return value will be formatted according to the following placeholder `%.*s`, we are including the precision field, and using it to determine a dynamic value that’s going to be the length of extracted characters, then we provide a starting point for the extraction by adding `source[start]` which skips starting from the first slot to the slot number `start` that we passed in the function’s parameters. Let’s call the function and see how it goes from here: ```cpp new message1[] = "Hello!", message2[] = "I want an apple!"; print(substring(.source = message1, .start = 1, .length = 3)); print(substring(.source = message2, .start = 7, .length = 8)); ``` ``` ell an apple ``` Simple right? Trivia bonus, passing a _negative value_ as the extraction length will result in outputting all the characters in your source string starting from the **start** slot. In the other hand, passing 0 as the extraction length returns a null value. Let’a take a look on these cases: ```cpp new message3[] = "Arrays start at 1, says the Lua developer!"; print(substring(message3)); // start = 0 by default, length = -1 by default print(substring(message3, .length = 6)); // start = 0 by default, length = 6 print(substring(message3, 7, 10)); // start = 7, length = 10 print(substring(message3, strlen(message3) - 14)); // start = 28, length = -1 by default print(substring(message3, strlen(message3) - 14, 3)); // start = 28, length = 3 ``` ``` Arrays start at 1, says the Lua developer! Arrays start at 1 Lua developer! Lua ``` #### Usage Putting all what we’ve seen so far to action, we can format our strings pretty match in anyway, so far we’ve worked in mainly in the console, utilizing the `print` and `printf` functions to output our data, well, mainly `printf` that is, thanks to its native support for formatting strings on the go, hence the f on the function’s name. But in the real world, most people don’t like looking at terminals, they are just too scary, and complicated to the average user, and as you all know, _client messages_ show up on the game’s screen, and not the console, however, those cannot be formatted on the go, they are more like a print function one might say, to bypass this limitation, we utilize and other very effective function, called `format`, we won’t go deeper on its definition, as we have already gone through explaining it on earlier parts, (refer to [this](../scripting/functions/format)), but, here is a reminder of its syntax; ```cpp format(output[], len, const format[], {Float,_}: ...} ``` Let’s take a look at these examples; **Example 1**: _Player name – Assuming there is some play on the server with the id of 9 called Player1_: ```cpp // MAX_PLAYER_NAME is a predefined constant with the value of 24, we add 1 to take into account the null terminator, thanks to Pottus for pointing that out. new playerName[MAX_PLAYER_NAME + 1], output[128], playerid = 9; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); format(output, sizeof(output), "[Info]: the player with the id of %d is called {EE11CC}%s.", playerid, playerName);SendClientMessageToAll(0, output); ``` > [Info]: the player with the id of 9 is called <span style={{color: '#ee11cc'}}>Player1</span>. Simply enough, we just get the player name and start formatting out the string, the `%d` placeholder is responsible on displaying the `playerid` variables, which holds the value `9`, the `%s` placeholder displays the `playerName` string that has the player name in it thanks to the `GetPlayerName` function. We then show the formatted string to everyone on the server using the `SendClientMessageToAll` function, notice that the `0` value on its first parameter indicating the color black, which is going to be the message’s color, the embedded hex value `{FFFF00}` is what resulted in the player name to be yellow. **Example 2**: _In-game Clock – Displaying the current time in game_: ```cpp new output[128], hours, minutes, seconds; gettime(hours, minutes, seconds); format(output, sizeof(output), "It's %02d:%02d %s", hours > 12 ? hours - 12 : hours, minutes, hours < 12 ? ("AM") : ("PM")); SendClientMessageToAll(0, output); ``` Again, we just utilized the `gettime` function to store the hours, minutes and seconds on their variables respectively, then put them all together into a nicely formatted string, we took advantage of the width field `%02d` to pad the values between 0 and 9 with another zero to evade outputs like (“_It’s 5:9 PM_”), as you can see. > It’s 06 :17 PM **Example 3**: _Death message - Outputting a message when a player dies, having the players names colored in their respective colors_: ```cpp public OnPlayerDeath(playerid, killerid, WEAPON:reason) { // MAX_PLAYER_NAME is a predefined constant with the value of 24, we add 1 to take into account the null terminator, thanks to Pottus for pointing that out. new message[144], playerName[MAX_PLAYER_NAME + 1], killerName[MAX_PLAYER_NAME + 1]; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); GetPlayerName(killerid, killerName, MAX_PLAYER_NAME); format(message, sizeof(message), "{%06x}%s {000000}killed {%06x}%s", GetPlayerColor(killerid) >>> 8, killerName, GetPlayerColor(playerid) >>> 8, playerName); SendClientMessageToAll(0, message); return 1; } ``` Given the following list of connected players: | | | | ------ | ----------------------------------------------- | | **ID** | **Player** | | 0 | <span style={{color: 'red'}}>Compton</span> | | 1 | <span style={{color: 'grey'}}>Dark</span> | | 5 | <span style={{color: 'red'}}>Player1</span> | | 6 | <span style={{color: 'blue'}}>Bartolomew</span> | | 11 | <span style={{color: 'grey'}}>unban_pls</span> | Say, `playerid` `0` killed `playerid` `6`, the formatted messages should spell “**{FF0000}Compton {000000}killed > {0000FF}Bartolomew**”, which will send the following client message to everybody on the server: > <span style={{color: 'red'}}>Compton</span> ­ <span style={{color: '#000000'}}>killed</span> ­ <span style={{color: 'blue'}}>Bartolomew</span> I apologize if I had you confused by using [bitwise logical shift](https://en.wikipedia.org/wiki/Logical_shift), it was simply used here in order to turn the decimal number returned by the `GetPlayerColor` function into a hexadecimal number representing a color, the shift itself is utilized to omit the -alpha- space, for more about this, I highly recommend checking out [this tutorial](Binary) by **Kyosaur**. #### Custom specifiers Working with the formatting specifiers we've gone through so far is sufficient, you can literally do all sort of stuff with those magnificent tools, but nothing is stopping us from asking for me, how greedy of us. All thanks to **Slice** after being influenced by [sscanf](https://github.com/maddinat0r/sscanf), he came up with an amazing include, [formatex](https://github.com/Southclaws/formatex), which added several new specifiers to use, which really eased a lot of every-day pawn stuff. But that wasn't it, you can also create your own specifiers to suit your needs, and as cool as it might sound, the process is very easy. Just for testing purposes, let's make something silly, something as basic as giving a string as an input, and return it on the form of a link (_https://www.string.com_); ```cpp FormatSpecifier<'n'>(output[], const param[]) { format(output, sizeof(output), "https://www.%s.com", param); } ``` As simple as that, and thus, the mighty `%n` specifier (short for Newton because it's very cool and rocket-science complicated 😉 was born, let's test this champ out: ```cpp printf("%n", "samp"); ``` > https://www.samp.com :::note Don't let this example gatekeep or limit your expectations for what is possible to achieve with custom specifiers, there are better examples at the main release page, [please go check it out](https://github.com/Southclaws/formatex/blob/master/README.md). ::: ### External links #### Similar tutorials - [String formatting](https://sampforum.blast.hk/showthread.php?tid=265433) by [krogsgaard20](https://sampforum.blast.hk/member.php?action=profile&uid=126724) - [Understanding Strings](https://sampforum.blast.hk/showthread.php?tid=284112) by [\[HiC\]TheKiller](https://sampforum.blast.hk/member.php?action=profile&uid=23565) - [How to use strcmp](https://sampforum.blast.hk/showthread.php?tid=199796) by [Ash.](https://sampforum.blast.hk/member.php?action=profile&uid=78597) - [Beginner's Guide: Single/Two/Multi-dimensional Arrays](https://sampforum.blast.hk/showthread.php?tid=318212) by [iPLEAOMAX](https://sampforum.blast.hk/member.php?action=profile&uid=122705) - [Tips and Tricks](https://sampforum.blast.hk/showthread.php?tid=216730) by [Slice](https://github.com/oscar-broman) - [Code optimization](https://sampforum.blast.hk/showthread.php?tid=571550) by [Misiur](https://sampforum.blast.hk/member.php?action=profile&uid=55934) - [Packed strings](https://sampforum.blast.hk/showthread.php?tid=480529) by [Emmet\_](https://github.com/emmet-jones) - [IRC string formatting](https://github.com/myano/jenni/wiki/IRC-String-Formatting) by [myano](https://github.com/myano) - [String manupilation](https://web.archive.org/web/20190424140855/https://www.compuphase.com/pawn/String_Manipulation.pdf) by [CompuPhase](https://web.archive.org/web/20190424140855/http://www.compuphase.com/) - [Pawn-lang](https://github.com/pawn-lang/compiler/blob/master/doc/pawn-lang.pdf) - [An in-depth look at binary and binary operators](https://sampforum.blast.hk/showthread.php?tid=177523) by [Kyosaur](https://sampforum.blast.hk/member.php?action=profile&uid=23990) #### Related includes/plugins/contributers - [Westie](https://sampforum.blast.hk/member.php?action=profile&uid=56481)'s [strlib](https://sampforum.blast.hk/showthread.php?tid=85697) - [Slice](https://github.com/oscar-broman)'s [strlib](https://github.com/oscar-broman/strlib) - [Slice](https://github.com/oscar-broman)'s [formatex](https://github.com/Southclaws/formatex) - [corne](https://sampforum.blast.hk/member.php?action=profile&uid=98345)'s [y_stringhash](https://sampforum.blast.hk/showthread.php?tid=571305) - [Y-Less](https://github.com/Y-Less)'s [sscanf](https://github.com/maddinat0r/sscanf) #### References - [GTA San Andreas](https://www.rockstargames.com/sanandreas/) - [Textdraw](../scripting/resources/textdraws#what-is-a-textdraw) - [Gametext](../scripting/functions/GameTextForPlayer) - [Limitations](../scripting/resources/limits) - [ASCII](https://en.wikipedia.org/wiki/ASCII) - [ASCII table](https://www.asciitable.com/) - [Pawn Tutorial](https://wiki.alliedmods.net/Pawn_Tutorial) - [Control Structures](../scripting/language/ControlStructures) - [Null character](https://en.wikipedia.org/wiki/Null_character) - [RGBA color space](https://en.wikipedia.org/wiki/RGBA_color_space) - [Color picker](https://www.webpagefx.com/web-design/color-picker/) - [TextDrawColor](../scripting/functions/TextDrawColor) - [Gametext styles](../scripting/resources/gametextstyles) - [Color list](../scripting/resources/colorslist) - [Escape sequence](https://en.wikipedia.org/wiki/Escape_sequence) - [r/programmerhumor](https://www.reddit.com/r/ProgrammerHumor/) - [Newline](https://en.wikipedia.org/wiki/Newline) - [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) - [Bobby table](https://bobby-tables.com/about) - [strfind](../scripting/functions/strfind) - [format](../scripting/functions/format) - [Bitwise logical shift](https://en.wikipedia.org/wiki/Logical_shift)
openmultiplayer/web/docs/tutorials/stringmanipulation.md/0
{ "file_path": "openmultiplayer/web/docs/tutorials/stringmanipulation.md", "repo_id": "openmultiplayer", "token_count": 28603 }
456
--- title: Timers module date: "2019-05-22T03:15:00" author: Y_Less --- Ovo je kratak pogled na jedan od poboljšanih modula koje smo uradili, za tajmere u open.mp: ```pawn native SetTimer(const func[], msInterval, bool:repeat) = SetTimerEx; native SetTimerEx(const func[], msInterval, bool:repeat, const params[], GLOBAL_TAG_TYPES:...); native KillTimer(timer) = Timer_Kill; // CreateTimer native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); // KillTimer native bool:Timer_Kill(Timer:timer); // Return time till next call. native Timer_GetTimeRemaining(Timer:timer); // Get number of calls left to make (0 for unlimited). native Timer_GetCallsRemaining(Timer:timer); // Get `repeatCount` parameter. native Timer_GetTotalCalls(Timer:timer); // Get `usInterval` parameter. native Timer_GetInterval(Timer:timer); // Reset time remaining till next call to `usInterval`. native bool:Timer_Restart(Timer:timer); ``` Prva dva služe samo za kompatibilnost unatrag, a ostala su poboljšani API: ```pawn native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); ``` - `func` - Fairly obvious; what to call. - `usDelay` - Again obvious, the delay before the call (in microseconds). - `usInterval` - What to reset `usDelay` to after the first call. So if you wanted a timer on the hour every hour, but it was 8:47am right now, the call would be `Timer_Create("OnTheHour", 780 SECONDS, 3600 SECONDS, 0);` - `repeatCount` - Unlike the old functions, which are just "once" or "forever", this instead takes the number of times to call the function. "once" would be `1`, `500` would stop after 500 calls, and (backwards from the old API) `0` means "forever". - `GLOBAL_TAG_TYPES` - Like `{Float, ...}`, but with more tags.
openmultiplayer/web/frontend/content/bs/blog/timers.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/bs/blog/timers.mdx", "repo_id": "openmultiplayer", "token_count": 640 }
457
--- title: Release Candidate 1 date: "2023-01-05T01:10:00" author: Y_Less --- It's here! It's finally here! After four years, two rewrites, arguments and drama, and countless other hurdles; it is finally here! Release Candidate 1 (RC1) of the open.mp server. This, hopefully, represents the final version of the code for our 1.0 release, and if everything goes smoothly with this version we will be able to finally **open** the so-called **open**.mp in just a few days from now. Before I get in to the meat of the release I want to first sincerely thank every member of the open.mp team for helping the mod get this far. It has not been easy, mostly because of how invested everyone truly was - we all wanted what was best for the mod, for the community, for SA:MP, for our servers, and for our players; we wouldn't have embarked on this journey if that wasn't the case. Unfortunately strong differing opinions on what is **best** sometimes causes friction. But we're here now. So to all, a huge thank you: * Amir * Cheaterman * Freaksken * Graber * Hual * Josh * JustMichael * kseny * Nexius * pkfin * Potassium * Southclaws * TommyB * Y_Less * Zeex * And probably more... Anyway, now the bit you actually care about... Now we're out of beta, we're (if all goes well this week) releasing on time. So along with the server itself, which you've seen a dozen times before, we have some new goodies for you: ## Pawn The download has the official includes, no more patching the old SA:MP includes with `omp.inc`, now we're doing it properly! It also has a new compiler. Ever wonder when 3.10.11 was coming? Well wait no longer (if you built it yourself, you could think of this one as 3.10.12)! With this combination you'll probably get loads of new warnings, but worry not - we have a tool for that as well, to automatically upgrade a load of code, adding well-defined symbol names, `const`, and more in all the right places. Maybe you already noticed this, you've been using it for months, but the virtual machine (the bit inside the server) has been updated as well! Oh, and all those string natives you know and love, like `SendClientMessage` and `AddMenuItem`? They all format now. All of them\*. A full list of what's available: * Symbol length limit increased to 64, no more `OnPlyrDoTheTing` to try and fit your names in. Leading to... * Multiple natives decompressed - is `Col` short for `Colour` or `Collision`? Now you know! * Tags. Tags everywhere. See the included documentation. * The official includes are finally const-correct. No more complaining that some people might not have them. * Compiler version updated: `__nameof`, `__addressof`, fixes, and too many more things to go in to here. * `switch` is way faster. * More warnings for previously undetected issues. The more problems the compiler can find, the fewer you need to. * An *upgrader* tool to add tags and `const` to user-code and fix several new warnings. * More consistent naming. Every native has been closely examined and compared to ensure the maximum level of similarity and intuitiveness in naming. * Added `{Float, _}:...` everywhere. What does this mean? It means no more `format()`\*\* - think y_va but natively. * `-O2`, the highest pawn optimisation level, works when using the new compiler and VM. Some includes may need to be updated, but some already have. To help with that... * The `__optimisation` macro was added so code can configure itself when compiled with `-O2`. Documentation on the updated includes: https://github.com/openmultiplayer/omp-stdlib Documentation on the new compiler: https://github.com/openmultiplayer/compiler/ https://github.com/pawn-lang/compiler/ Documentation on qawno: https://github.com/openmultiplayer/qawno/ Documentation on the upgrader tool: https://github.com/openmultiplayer/upgrade \* Almost all of them. \*\* Almost no more `format()`. ## SDK Pawn is the long-standing, and still official, way to write modes for your server. It isn't going away, but for those of you who want more control we are finally releasing the full SDK (the *S*oftware *D*evelopment *K*it). This is a C++ interface to the server, the same one used by all the components that make up the core open.mp code. Anything they can do you can do too (compared to plugins, which were only designed to provide functions to pawn, not write modes). We have some documentation under way, it takes time unfortunately. But in the meantime have several example components for those of you who want to get straight stuck in. These are all templates you can build upon, and go from basically nothing to a fully working component with most common features: https://github.com/openmultiplayer/empty-template https://github.com/openmultiplayer/basic-template https://github.com/openmultiplayer/pawn-template https://github.com/openmultiplayer/full-template A few terms to get you started, so you can start to understand what it is that you're reading: * *Component* - A logical individual piece of the server, like objects or pickups. Ones you don't need don't need to be loaded. * *Extension* - Code that extends another bit of code. You can write component extensions, but the most common ones are player extensions, which define some structure of data to be associated with a player in addition to all their normal data like health and weapons. * *UID* - *U*nique *ID*entifier, a number that represents your component, and your component alone. This ia always required and can be got here: http://open.mp/uid * *Entity* - A thing, usually a thing a player can interact with, and which you might have a lot of. Objects are entities, but other players are also entities, even commands in a processor could be called entities. * *Pool* - Something that holds entities. When you have a lot you need to be able to access them by name or ID in some way, this is what a pool does. * *Interface* - Components use an abstract base class as an interface. This declares which methods a component has, but doesn't contain the code for the methods. Interfaces are passed around so that components can communicate with each other, but implementations are kept private. * *SDK* - The collection of all the interfaces defined by the core server. * *ABI* - An *A*pplication *B*inary *I*nterface is the way compiled code talks to other compiled code. The interfaces exported by the SDK are *ABI stable*, which means that using two components compiled at different times will still work together. * *pawn-natives* - The library on which all native declarations are built. Useing a wrapper called `SCRIPT_API` around this library: https://github.com/openmultiplayer/pawn-natives * *Event* - Something that happens externally. Things like players connecting and typing commands are events. Any component can define events and tell other components when those events happen. * *Handler* - A component that wants to know when an event happens. If you have questions, the best place is probably the brand new (revived) forums: https://forum.open.mp/ ## Features Beside all the new features announced for pawn, there are several new (and newly announced) features in the server: * Per-player gang zones, as were in YSF. * Per-player pickups, also as in YSF. * `AttachPlayerObjectToPlayer`. * Better PawnPlus support. * `:memory:`, and other special names support in SQLite. * SQLite open flags. * `exclude` config option to not load certain components. * Show config parse errors, don't just silently fail. * SDK major version check, just in case we ever make major server changes (hopefully we won't). ## Fixes There were a few new bugs introduced in beta 11, and a few minor ones left over from before. The ones fixed include: * `funcidx` already registered warning. * GDK plugins (streamer etc) missing natives. * Random crash on GMX. * GDK callbacks sometimes not called. * No logging when requested in SQLite component. * Some settings not reset on GMX. * NPCs were connecting when there were a lot done at once. * `.so` was still needed in Linux legacy plugin names. ## Links Firstly, of course, is the new server version: https://github.com/openmultiplayer/open.mp/releases Secondly, the forums are back up. Head there for all your questions: https://forum.open.mp/ Or if you prefer: https://vk.com/open_mp Next, despite it being offered a few times, we have explicitly resisted any money up to this point; because we didn't feel it was right until we had proven ourselves with a release. With this post, that time is now, so if anyone wants to help support us (all donations will go towards infrastructure and future client dev work), it would be most appreciated: https://www.patreon.com/open_mp https://opencollective.com/openmultiplayer And of course everything is still in active development, so please do check all the links above regularly to see what's new that we have.
openmultiplayer/web/frontend/content/en/blog/release-candidate-1.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/en/blog/release-candidate-1.mdx", "repo_id": "openmultiplayer", "token_count": 2327 }
458