ES/Introducción a la Programación de GUI

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

Una importante caracteristica de MTA:SA es la posibilidad de programar GUIs propias (Graphics User Interface que traducido seria, Interfaz Grafica del Usuario). Una GUI consiste en ventanas, botones, cajas de edición, entre otras cosas.... Estos pueden ser mostrados mientras el jugador esta en el juego, y es usado para tener interacción con el usuario en lugar de los típicos comandos.

Consola de Administración

Un tutorial para hacer una ventana de ingreso

En este tutorial nosotros haremos una simple ventana de ingreso, con dos cajas de edición y un botón. La ventana aparecerá cuando el jugador ingrese al juego, y cuando el botón sea apretado, el jugador aparecerá. El tutorial continuara el modo que hicimos en Introducción a LUA (Si tu continuaste de la pagina anterior, tendrás que remover o comentar la linea donde se encuentra la función spawnPlayer, porque estaremos reemplazando eso con una GUI alternativa en este tutorial). También daremos una mirada a lo que es la programación en el cliente.

Dibujando la ventana

Toda GUI se debe hacer en el cliente. Esto tambien es una buena practica para tener todos los archivos de cliente en carpetas separadas.

Busca el directorio /Tu servidor MTA/mods/deathmatch/resources/myserver/, y crea una carpeta llamada "cliente". En la carpeta cliente, crea un archivo de texto y llamalo "gui.lua".

En este archivo escribiremos una función que dibuje la ventana. Para crear la ventana usaremos guiCreateWindow:

function createLoginWindow()
	-- definimos las coordenadas X,Y donde se creara la ventana
	local X = 0.375
	local Y = 0.375
	-- definimos el tamaño de la ventana (El ancho y el alto)
	local Width = 0.25
	local Height = 0.25
	-- Creamos la ventana y la grabamos su valor de elemento en la variable 'wdwLogin'
	-- Apreta en el nombre de la función para leer su definición
	wdwLogin = guiCreateWindow(X, Y, Width, Height, "Porfavor ingrese", true)
end

Relativo y absoluto

Notese que el argumento final pasado a la función guiCreateWindow en el ejemplo de arriba es true. Esto indica que las coordenadas y las dimensiones de la ventana son relativas, queriendo decir que son un porcentaje del tamaño total de la pantalla. Queriendo decir que el lado izquierdo de la pantalla es 0 y el lado derecho es 1. Una posición X de 0.5, representaría el centro de la pantalla. Similarmente, si la parte de arriba de la pantalla es 0 y la de abajo es 1, entonces una posición en Y de 0.2 seria un 20% abajo de la pantalla. Este mismo principio se aplica al ancho y alto también. (Con un ancho de 0.5, quiere decir que la ventana tendrá un ancho de la mitad de la pantalla)

La alternativa a usar valores relativos es usar absolutos (Pasando false en vez de true a guiCreateWindow)). Los valores absolutos son calculados como el numero total de pixeles de la esquina superior-izquierda de su padre (Si no se especifica un elemento padre, entonces el padre seria la pantalla en si). Si asumimos una resolución de 1920x1200, El lado izquierdo empezaría con 0 pixeles y el lado derecho tendría 1920 pixeles, una posición X de 960 representaría el centro de la pantalla. Similarmente, si el lado superior de la pantalla empieza 0 pixeles y el lado inferior termina con 1920 pixeles, una posición Y de 20 seria 20 pixeles bajo el lado superior de la pantalla. El mismo principio se aplica al ancho y al alto. Tu puedes usar guiGetScreenSize y un poco de matemáticas para calcular algunas posiciones absolutas.

Las diferencias entre usar valores relativos y absolutos es un poco simple; Una GUI creada con valores absolutos siempre tendrá el mismo tamaño y posición, mientras que una GUI creada usando valores relativos siempre sera un porcentaje del tamaño de su padre.

El valor absoluto es generalmente mas fácil de mantener cuando se edita un código a mano, aunque tu opción del tipo depende de la situación para que lo estas usando.

Para propósitos de esta introducción usaremos valores relativos. (Aunque recomiendo usar absolutos)

Añadiendo los componentes

Ahora agregaremos las etiquetas de texto (Diciendo "Usuario:" y "Contraseña:", Cajas de edición (Para ingresar los datos) y un botón para ingresar.

Para crear el botón usaremos guiCreateButton, y para crear las cajas de edición usaremos guiCreateEdit:

Nota que estamos escribiendo mas codigo de nuestra existente función 'createLoginWindow'. Esto no es una nueva función y esta pensada a reemplazar la que tu ya tenias.

function createLoginWindow()
	local X = 0.375
	local Y = 0.375
	local Width = 0.25
	local Height = 0.25
	wdwLogin = guiCreateWindow(X, Y, Width, Height, "Porfavor Ingrese", true)
	
	-- definimos las coordenadas X,Y de nuestra primera etiqueta
	X = 0.0825
	Y = 0.2
	-- definimos el ancho y el alto de nuestra primera etiqueta
	Width = 0.25
	Height = 0.25
	-- Creamos la primera etiqueta, nota que el argumento final es 'wdwLogin' significando la ventana que creamos arriba es el padre de
	-- esta etiqueta (asique todos los valores de posición y tamaño son relativos a la posición de esa ventana)
	guiCreateLabel(X, Y, Width, Height, "Usuario", true, wdwLogin)
	-- alteramos el valor Y, para que la segunda etiqueta este un poco mas abajo de la primera
	Y = 0.5
	guiCreateLabel(X, Y, Width, Height, "Contraseña", true, wdwLogin)
	

	X = 0.415
	Y = 0.2
	Width = 0.5
	Height = 0.15
	edtUser = guiCreateEdit(X, Y, Width, Height, "", true, wdwLogin)
	Y = 0.5
	edtPass = guiCreateEdit(X, Y, Width, Height, "", true, wdwLogin)
	-- Ponemos el maximo de caracteres que se pueden escribir en las cajas a 50
	guiEditSetMaxLength(edtUser, 50)
	guiEditSetMaxLength(edtPass, 50)
	
	X = 0.415
	Y = 0.7
	Width = 0.25
	Height = 0.2
	btnLogin = guiCreateButton(X, Y, Width, Height, "Ingresar", true, wdwLogin)
	
	-- Hacer la ventana invisible
	guiSetVisible(wdwLogin, false)
end

Nota que todo componente GUI creado es un hijo de la ventana, esto se hace espeficicando el elemento padre (wdwLogin, en este caso) cuando se crea el componente.

Esto es muy util porque no solo hace pensar que todos sus componentes estan unidos a la ventana y que se van a mover con ella, sino que ademas todo cambio hecho a la ventana padre seran aplicados arbol abajo a todos sus elementos hijos. Por ejemplo, ahora podemos esconder todos los elementos GUI que creamos con solo esconder la ventana:

guiSetVisible(wdwLogin, false) --esconde todos los elementos GUI que hicimos para poderlos mostrar al jugador en el momento apropiado

Uso de la función anterior

La función createLoginWindow ha sido completada, pero no hará nada hasta procesarlo. Es recomendable hacer todo el GUI cuando el resource del cliente se inicie, ocultarlo, y mostrarle al jugador cuando sea necesario. Por lo tanto, vamos a escribir un "event handler" para "onClientResourceStart" para crear la siguiente ventana:

-- 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(getThisResource()), 
	function ()
		createLoginWindow()
	end
)	

As this is a log in window, we now need to show the window when the player joins the game. This can be done using the same event, "onClientResourceStart", so we can modify the above code to include showing the window:

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

addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), 
	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.