HU/Introduction to Scripting the GUI

From Multi Theft Auto: Wiki
Jump to navigation Jump to search

Egy fontos funkciója az MTAnak az egyedi GUI, azaz Graphic User Interface, magyarul Grafikus Felhasználói Felület létrehozása. A GUI állhat ablakokból, gombokból, beviteli mezőkből, illetve jelölőnégyzetekből. Majdnem minden standard formájú alkotórész a grafikus környezetből. Meglehetnek jelenítve, miközben a játékos játszik, és lehet őket használni bemenetre és kimenetre hagyományos parancsok helyett.

Admin Console GUI

Egy oktatás egy bejelentkező ablak létrehozásához

Ebben az oktatásban létre fogunk hozni egy sima bejelentkező ablakot, két bemeneti mezővel és egy gombbal. Az ablak akkor fog megjelenni, amikor a játékos belép a játékba, és amikor a gomb meglesz nyomva, a játékos lefog spawnolni. Ez az oktatás folytatni fogja azt a gamemodet, amit elkészítettünk a Bevezetés a scriptelésbe részlegben. (Ha használtad a Bevezetés a scriptelésbe részleget, kikell törölnöd, vagy kommentelned a spawnPlayer sort a "csatlakozasKezelo" funkcióban, mivel helyettesíteni fogjuk egy GUI alternatívával ebben az oktatásban.) Illetve befogunk tekinteni a kliens-oldali scriptelésbe is.

Az ablak "megrajzolása"

Minden GUIt csak kliens-oldalon tudunk elkészíteni. És amúgy egy jó gyakorlat, hogy minden kliens-oldali fájlt egy külön mappában tarstunk.

Menj az /MTA szerver/mods/deathmatch/resources/enszerverem/ könyvtárba, majd hozz létre egy mappát "kliens" néven. A /kliens/ könyvtárban hozz létre egy szöveges fájlt, majd nevezd el "gui.lua"-nak.

Ebben a fájlban fogunk megírni egy funkciót, ami az ablakot fogja megrajzolni. Ahhoz, hogy létrehozzunk egy ablakot a guiCreateWindow funkciót fogjunk használni:

function bejelentkezesiAblakLetrehozasa()
	-- Az X és az Y koordináta definiálása
	local X = 0.375
	local Y = 0.375
	-- A szélesség és a magasság definiálása
	local wSzelesseg = 0.25
	local wMagassag = 0.25
	-- Hozzuk létre az ablakot, és mentsük el az elementjét egy változóban amit nevezzünk el 'wLogin'-nak
	-- Nyomj rá a funkció nevére hogy elolvasd a hozzátartozó dokumentációt
	wLogin = guiCreateWindow(X, Y, wSzelesseg, wMagassag, "Kérlek jelentkezz be", true)
end

Relatív és Abszolút

Figyeld meg, hogy az utolsó argumentum a guiCreateWindownál a példában true. Ez mutatja, hogy a koordináta és a dimenzió az ablaknál relatív, szóval azt jelenti, hogy százaléka a teljes képernyőméretének. Ez azt jelenti hogy a bal oldala a képernyőnek 0, a jobb oldala 1, akkor egy X pozíció 0.5-nél mutatná a középpontját a képernyőnek. Hasonlóképpen a teteje a képernyőnek 0 és az alja 1, akkor egy Y pozíció 0.2-nél lenne a képernyő 20 százalékánál a képernyőnek fentről lefele. Ezek az elvek igazak mint a wSzelesseg és a wMagassagra is (a wSzelesseg 0.5-nél azt jelenti, hogy az ablak fele olyan széles lesz, mint a képernyőnk).

Az alternatíva a relatív érzékek használatának az abszolút (false adása a true helyett a guiCreateWindownak). Az abszolút értékek úgy vannak kiszámolva, hogy az összes pixel a bal-felső sarokból a szülőnek (ha nem egy gui element a szülő, akkor a szülő a képernyő maga). Feltételezzük, hogy a képernyőnk 1920x1200, a bal oldala a képernyőnknek 0 pixelnél, a jobb oldala 1920 pixelnél kezdődik, akkor egy X pozíció 960-nál mutatnál a középpontját a képernyőnek. Hasonlóképpen a teteje 0 pixelnél, és az alja 1200 pixelnél kezdődik, akkor egy Y pozíció 20-nál 20 pixellel tolná el lefele a képernyő tetejétől. Ezek az elvek igazak mint a wSzelesseg és a wMagassagra is (a wSzelesseg 50-nél azt jelenti, hogy az ablak 50 pixel széles lenne). Használhatod a guiGetScreenSizefunkciót és egy kis matematikai számolást hogy kiszámíts bizonyos abszolút pozíciókat.

Az abszolútot általában egyszerűbb fenntartani amikor egy kódot kézzel hozunk létre, viszont a választásod függ a szituációtól.


Az oktatás céljából relatív értékeket fogunk használni.

Az alkotórészek hozzáadása

Következőnek, szövegeket fogunk hozzáadni ("felhasználónév:" és "jelszó:"), bemeneti mezőket (az adat beviteléhez) és egy gombot a bejelentkezéshez.

Egy gomb létrehozásához a guiCreateButton, egy bemeneti mező létrehozásához a guiCreateEdit funkciót használjuk:

Figyeld meg, hogy már a létező 'bejelentkezesiAblakLetrehozasa' funkcióhoz írunk további kódokat. Ez nem egy új funkció, és azt jelenti, hogy kicseréljük azt, amink már van.

function bejelentkezesiAblakLetrehozasa()
	local X = 0.375
	local Y = 0.375
	local wSzelesseg = 0.25
	local wMagassag = = 0.25
	wLogin = guiCreateWindow(X, Y, wSzelesseg, wMagassag, "Kérlek jelentkezz be", true)
	
	-- Új X és Y koordináta definiálása az első felirathoz
	X = 0.0825
	Y = 0.2
	-- Új wSzelesseg és wMagassag definiálása az első felirathoz
	wSzelesseg = 0.25
	wMagassag = 0.25
	-- Az első felirat létrehozása, jegyezd meg hogy az utolsó 'wLogin' argumentum az ablakot jelenti
	-- amit már feljebb létrehoztunk, és ez lesz a felirat szülője (szóval minden pozíció és méret relatív az ablak pozíciójához képest)
	guiCreateLabel(X, Y, wSzelesseg , wMagassag , "Felhasználónév", true, wdwLogin)
	-- Változtassuk meg az Y értéket, szóval a második címke némileg lejjebb van mint az 
	Y = 0.5
	guiCreateLabel(X, Y, wSzelesseg, wMagassag, "Jelszó", true, wdwLogin)
	

	X = 0.415
	Y = 0.2
	wSzelesseg = 0.5
	wMagassag = 0.15
	edtFelh = guiCreateEdit(X, Y, wSzelesseg, wMagassag, "", true, wdwLogin)
	Y = 0.5
	edtJelszo = guiCreateEdit(X, Y, wSzelesseg, wMagassag, "", true, wdwLogin)
	-- Állíts be a maximum hosszt a felhasználónév és a jelszó mezőnek 50re
	guiEditSetMaxLength(edtFelh, 50)
	guiEditSetMaxLength(edtJelszo, 50)
	
	X = 0.415
	Y = 0.7
	Width = 0.25
	Height = 0.2
	btnLogin = guiCreateButton(X, Y, Width, Height, "Log In", true, wdwLogin)
	
	-- make the window invisible
	guiSetVisible(wdwLogin, false)
end

Ne feledje, hogy minden létrehozott GUI alkotóelem az ablak gyermeke, ezt a alkotóelem létrehozásakor a szülőelem (ebben az esetben wdwLogin) megadásával végezzük.

Ez nagyon hasznos, mert nem csak azt jelenti, hogy az összes alkotóelem az ablakhoz lett hozzákapcsolva, és vele együtt mozog, hanem azt is, hogy any changes done to the parent window will be applied down the tree to these child components. Például elrejthetjük az összes létrehozott GUI-t, egyszerűen az ablak elrejtésével:

guiSetVisible(wdwLogin, false) --hides all the GUI we made so we can show them to the player at the appropriate moment. 

Using the function we wrote

A createLoginWindow function most már kész, de nem fog csinálni semmit, amíg meg nem hívjuk. Ajánlott minden GUI létrehozása, amikor a client resource elindul, elrejtjük őket, majd amikor szükséges megjelenítjük a játékosnak. Ezért létrehozunk egy event handler-t az "onClientResourceStart"-ra az ablak létrehozásához:

-- attach the event handler to the root element of the resource
-- this means it will only trigger when its own resource is started
addEventHandler("onClientResourceStart", getResourceRootElement(), 
	function ()
		createLoginWindow()
	end
)	

Mivel ez egy bejelentkezési ablak, ezért meg kell jelenítenünk az ablakot, amikor a játékos csatlakozik a szerverre. Ezt megtehetjük az "onClientResourceStart" event használatával is, így módosíthatjuk a fenti kódot az ablak megjelenítéséhez:

Mostpedig több kódot adunk hozzá a már meglévő 'onClientResourceStart' handler-ünkre. Ez nem egy új event handler, hanem a már meglévőt helyettesíti.

addEventHandler("onClientResourceStart", getResourceRootElement(), 
	function ()
		-- create the log in window and its components
		createLoginWindow()

		-- output a brief welcome message to the player
                outputChatBox("Welcome to My MTA:SA Server, please log in.")

		-- if the GUI was successfully created, then show the GUI to the player
	        if (wdwLogin ~= nil) then
			guiSetVisible(wdwLogin, true)
		else
			-- if the GUI hasnt been properly created, tell the player
			outputChatBox("An unexpected error has occurred and the log in GUI has not been created.")
	        end 

		-- enable the players cursor (so they can select and click on the components)
	        showCursor(true)
		-- set the input focus onto the GUI, allowing players (for example) to press 'T' without the chatbox opening
	        guiSetInputEnabled(true)
	end
)	

Note that we have a simple security check before making the window visible, so in the unlikely event that the window has not been created, meaning wdwLogin is not a valid element, we don't get an error and just inform the player what has happened. In the next step, we will create the button functionality for the log in button.

Scripting the button

Now that we have created our GUI and shown it to the player, we need to make it work.

Detecting the click

When the player clicks on any part of the GUI, the event "onClientGUIClick" will be triggered for the GUI component you clicked on. This allows us to easily detect any clicks on the GUI elements we want to use. For example, we can attach the event to the btnLogin button to catch any clicks on it:

-- attach the event onClientGUIClick to btnLogin and set it to trigger the 'clientSubmitLogin' function
addEventHandler("onClientGUIClick", btnLogin, clientSubmitLogin, false)

Note the final argument passed is "false". This indicates that the event will only trigger directly on btnLogin, not if the event has propagated up or down the tree. Setting this to "true" while attaching to gui elements will mean that clicking on any element in the same branch will trigger this event.

This line of code can now be added inside the createLoginWindow function. It is a common mistake to try and attach events to non-existant GUI elements, so make sure you always attach your events after the gui element (in this case, the button) has been created:

Note that we are now writing more code for our existing 'createLoginWindow' function.

function createLoginWindow()
	-- create all our GUI elements
	...

	-- now add our onClientGUIClick event to the button we just created
	addEventHandler("onClientGUIClick", btnLogin, clientSubmitLogin, false)

Managing the click

Now that we can detect when the player clicks on the button, we need to write code to manage what happens when they do. In our onClientGUIClick event handle, we told it to call the function clientSubmitLogin whenever btnLogin is clicked. Therefore, we can now use the function clientSubmitLogin to control what happens when the button is clicked:

-- create the function and define the 'button' and 'state' parameters
-- (these are passed automatically by onClientGUIClick)
function clientSubmitLogin(button,state)
	-- if our login button was clicked with the left mouse button, and the state of the mouse button is up
	if button == "left" and state == "up" then
		-- move the input focus back onto the game (allowing players to move around, open the chatbox, etc)
		guiSetInputEnabled(false)
		-- hide the window and all the components
		guiSetVisible(wdwLogin, false)
		-- hide the mouse cursor
		showCursor(false)
	end
end

Now, when the button is clicked, the window will be hidden and all controls will be returned to the player. Next, we will tell the server to allow the player to spawn.

Triggering the server

Triggering the server can be done using triggerServerEvent. This allows you to trigger a specified event on the server from the client. The same can be done in reverse using triggerClientEvent. Here, we use the triggerServerEvent function to call our own custom event on the server, named "submitLogin", which will then control the spawning of the player serverside.

Note that we are now writing more code for our existing 'clientSubmitLogin' function. This is not a new function and is meant to replace what you already have.

function clientSubmitLogin(button,state)
	if button == "left" and state == "up" then
		-- get the text entered in the 'username' field
		local username = guiGetText(edtUser)
		-- get the text entered in the 'password' field
		local password = guiGetText(edtPass)

		-- if the username and password both exist
		if username and password then
			-- trigger the server event 'submitLogin' and pass the username and password to it
			triggerServerEvent("submitLogin", getRootElement(), username, password)

			-- hide the gui, hide the cursor and return control to the player
			guiSetInputEnabled(false)
			guiSetVisible(wdwLogin, false)
			showCursor(false)
		else
			-- otherwise, output a message to the player, do not trigger the server
			-- and do not hide the gui
			outputChatBox("Please enter a username and password.")
		end
	end
end

Creating the serverside event

At this point we now have all the code needed on the client side, so open up your serverside 'script.lua' file (from the Introduction to Scripting) or another suitable serverside file to work with.

On the server side, recall that we are spawning the player as soon as they login. So, first of all, we will need to define the custom event that we used before on the client. This can be done using addEvent and addEventHandler.

-- create our loginHandler function, with username and password parameters (passed from the client gui)
function loginHandler(username,password)

end

-- define our custom event, and allow it to be triggered from the client ('true')
addEvent("submitLogin",true)
-- add an event handler so that when submitLogin is triggered, the function loginHandler is called
addEventHandler("submitLogin",root,loginHandler)

Logging in

Now we have a function that is called through the custom event 'submitLogin', we can start to work on logging in and spawning the player, using our 'loginHandler' function:

function loginHandler(username,password)
	-- check that the username and password are correct
	if username == "user" and password == "apple" then
		-- the player has successfully logged in, so spawn them
		if (client) then
			spawnPlayer(client, 1959.55, -1714.46, 10)
			fadeCamera(client, true)
                        setCameraTarget(client, client)
			outputChatBox("Welcome to My Server.", client)
		end
	else
		-- if the username or password are not correct, output a message to the player
		outputChatBox("Invalid username and password. Please re-connect and try again.",client)
        end			
end

addEvent("submitLogin",true)
addEventHandler("submitLogin",root,loginHandler)

For the purposes of this tutorial, a very basic username and password system is shown. For a more comprehensive alternative, you can use the Account System or a MySQL database.

Also note the use of the variable "client", it's an internal variable used by MTA to identify the player who triggered the event.


Finally, do not forget to include the new gui.lua file in the meta.xml of the main resource, and label it as a client script:

<script src="client/gui.lua" type="client" />


At this point, we now have a basic login window that checks the player's username and password when the login button is clicked. If they are correct, the player is automatically spawned.

For further help with GUI, see the GUI tutorials.

Fordította

  • NexuS
  • Surge