0% encontró este documento útil (0 votos)
5 vistas15 páginas

Introducción a GDScript y sus conceptos básicos

Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como RTF, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
5 vistas15 páginas

Introducción a GDScript y sus conceptos básicos

Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como RTF, PDF, TXT o lee en línea desde Scribd

GDScript

PALABRA SIGNIFICADO
var Variable

const Constante

func Función

if Si

for Para, por, en

return Volver, regresar, devolver

print Imprimir, imprimirse, publicar

func _ready():

Multilínea

'''

Comentario

de multiples

lineas

'''

"""

Comentario

de multiples

lineas

"""

Print
func _ready():

print("hola Mundo")
Variables 1
func _ready() -> void:

var cazuela = "Cebolla"

print(cazuela)

cazuela = "papas"

print(cazuela)

Array
func _ready() -> void:

var array = []

array = [1,2,3]

print(array)

print(array[0])

print([Link]())

array[0] = "papas"

print(array)

Variable 2
func _ready() -> void:

var cazuela = "Cebolla\n\ty papas"

print(cazuela)

var numero_entero = 5

var numero_real = 78.8

var booleano = false

var muerto = true

var mi_variable = null


mi_variable = -0.15

Vector
func _ready():

var coordenadas = Vector2(1.1,7.18)

var coordenadas_entero = Vector2i(1,7)

var coordenadas3D = Vector3i(1,7,9)

var color_fondo = Color(1,1,1,0)

#print(coordenadas_entero.x)

Costantes
func _ready():

var vida_actual = 10

vida_actual = 7

const VIDA_INICIAL = 100

vida_actual = VIDA_INICIAL

print(VIDA_INICIAL)

Operadores
func _ready():

const VIDA_INICIAL = 10

var vida_actual = VIDA_INICIAL

var daño = 1 + 2

print(daño)

vida_actual = vida_actual - daño / 3

print(vida_actual)
var puntuacion = (vida_actual + 5) * 300 - daño * 50

daño = -daño

var x = 2 ** 3

var modulo = 5 % 2

Abreviados

func _ready():

const VIDA_INICIAL = 10

var vida_actual = VIDA_INICIAL

var daño = 1 + 2

daño += 2

print(daño)

daño -= 2

daño *= 3

daño /= 2

daño **= 3

Comparacion
func _ready():

const VIDA_INICIAL = 10

var vida_actual = VIDA_INICIAL

var daño = 1 + 2

var muerto = vida_actual == 0

var herido = vida_actual != VIDA_INICIAL

herido = vida_actual < VIDA_INICIAL

var muy_vivo = vida_actual > 8

var vivo = vida_actual >= 1


print(muerto)

var textoA = "Hola"

var textoB = "Adios"

print (textoA == textoB)

Boolean
func _ready():

const VIDA_INICIAL = 10

var vida_actual = VIDA_INICIAL

var daño = 1 + 2

var muerto = vida_actual == 0

var herido = vida_actual != VIDA_INICIAL

herido = vida_actual < VIDA_INICIAL and vida_actual > 0

herido = vida_actual < VIDA_INICIAL and not muerto

var operador_or = false or true

var operador_and = true or true

var operador_not = not true

var puede_coger_cosas =(pulsa_coger or recogida_automatica) and hay_algo_cerca and not


inventario_lleno

Condiciones
func _ready():

const VIDA_INICIAL = 10

var vida = VIDA_INICIAL

if condicion:

if vida <= 0:

print("el jugador esta muerto")


pasa esto

tambien esto otro

else:

print("el jugador continua vivo")

esto ocurre en otro caso

esto tambien

mover enemigos

print("continua el programa")

Secuencias de condiciones
func _ready():

const VIDA_INICIAL = 10

var vida = VIDA_INICIAL

if vida == 100:

print("el jugador tiene toda la vida")

elif vida > 50:

print("el jugador tiene algunas heridas")

elif vida > 0:

print("el jugador esta hecho polvo")

else:

print("ha muerto")

print("continua el programa")

Anidar instrucciones
func _ready():

const VIDA_INICIAL = 10

var vida = VIDA_INICIAL


var pociones = 1

if vida == 100:

print("el jugador tiene toda la vida")

elif vida > 50:

print("el jugador tiene algunas heridas")

elif vida > 0:

print("el jugador esta hecho polvo")

else:

if pociones > 0:

pociones = pociones - 1

vida = VIDA_INICIAL

print("Vida restaurada")

else:

print("ha muerto")

print("continua el programa")

bucle while
func _ready():

var turnos = 3

while turnos > 0:

print(turnos)

turnos = turnos - 1

print("ha terminado la ronda")

bucle for
func _ready():

var turnos = 3
for i in [0,1,2]:

for i in range(3):

for i in turnos:

for letra in "turnos":

print(i)

print(letra)

print("ha terminado la ronda")

Recorrer un array
func _ready():

var turnos = 3

var array = ["hola", 3, "final"]

for elemento in array:

print(elemento)

for i in [Link]():

if i == 0:

array[i] = "primer elemento"

array[i] = i

print(array)

print("ha terminado la ronda")

Interrumpir un Bucle
func _ready():

var turnos = 3

var array = ["hola", 3, "final"]

for i in 5:

if (i == 0):
continue

elif (i == 2):

break

print(i)

print("ha terminado la ronda")

Array y sus Metodos


func _ready():

var inventario = []

inventario = ["pocion"]

inventario = ["hierbas"]

[Link]("hierbas")

for objeto in inventario:

print(objeto)

for posicion in [Link]():

print(inventario[posicion])

if inventario[posicion] == "pocion":

inventario[posicion] = "pocion vacia"

elif inventario[posicion] == "hierbas":

inventario.remove_at(posicion)

var loot = ["pocion","arma","escudo"]

inventario.append_array(loot)

[Link](2,"lanza")

print([Link]("arma"))

print([Link]("arma"))

[Link]()
[Link]()

[Link]()

[Link]()

print(loot)

print(inventario)

Ejemplo de uso
func _ready():

var inventario = []

var loot = ["pocion","arma","escudo"]

[Link]()

[Link](loot[0])

[Link]()

print(inventario)

print(loot)

Diccionarios
func _ready():

var inventario = {

hierbas = 15,

madera = 1300,

"pocion vacia" = 10,

print(inventario["hierbas"])

print([Link])

[Link] = ["lumos", "windardium leviosa", "avada kedavra"]

[Link] += 1
[Link]("madera")

print(inventario)

for clave in [Link]():

print(clave)

print(inventario[clave])

Strings
func _ready():

var texto = "thank you mario"

print(texto[1])

texto = texto + "\r\tbut our \\princess in in \"another\" castle!"

print(texto)

Textos
func _ready():

var texto = "thank you mario"

var nombre = texto.get_slice(" ", 2)

print(nombre)

var array_trozos = [Link](" ")

print(array_trozos)

print(texto.to_upper())

print(texto.to_lower())

texto = [Link]("Mario", "Luigi")

print(texto)

Valor de retorno
func _ready():

var texto = "thank you mario"


var nombre = "Alex"

#var mensaje = game_over(nombre, "155")

var mensaje = crear_mensaje_game_over(nombre, "155")

#print(mensaje)

mostrar_mensaje(mensaje)

func game_over(nombre, puntos = "0"):

func crear_mensaje_game_over(nombre, puntos = "0"):

var mensaje = "lo siento, " + nombre + ","

return

var puntuacion = "\nhas conseguido: " + puntos

return mensaje + puntuacion

print("mersaje despues")

func mostrar_mensaje(texto):

print(texto)

Funciones
func _ready():

var texto = "thank you mario"

print(texto)

var nombre = "Alex"

game_over(nombre, "140")

game_over(nombre, "0")

func game_over(nombre, puntos):

func game_over(nombre, puntos = "0"):

var mensaje = "lo siento, " + nombre + ","

var puntuacion = "\nhas conseguido: " + puntos


var puntuacion = "\nhas conseguido: " + str(puntos)

print(mensaje + puntuacion)

print("lo siento, has perdido")

func mostrar_mensaje(texto):

print(texto)

play_sonido_derrota()

func play_sonido_derrota():

pass

Ambito de las variables


var inventario = {madera = 1, hierba = 3, piedra = 10}

func _ready():

var inventario = {madera = 1, hierba = 3, piedra = 10}

recoger(inventario, "hierba")

print(inventario)

print(otra)

func recoger(materia, cantidad=1):

func recoger(inventario, materia, cantidad=1):

var otra = 3

var inventario = {}

if [Link](material):

inventario[material] += cantidad

else:

inventario[material] = cantidad

print(inventario)

Variable globales
func _ready():

var array = [1]

modificar(array)

print(array)

var mi_numero = 1

mi_numero = modificar(mi_numero)

print(mi_numero)

func modificar(arr):

[Link](3)

func modificar(valor):

valor += 3

return valor

Projectil
class_name Proyectil

extends Sprite2D

var velocidad = 10

var daño = 5

var tipo = "hielo"

var color = Color(1,2,234)

func _ready():

pass

func _process(delta):

mover(delta)

explotar()

func mover(delta):
position.x += velocidad * delta

func explotar():

if position.x > 300:

print("exploto causando " + str(daño) + "de daño")

queue_free()

acceder-a-propiedades

func _ready() -> void:

get_node("Personaje").position = [Link]

var mi_puntaje = [Link]

Camera2D

extends Camera2D

@export var object_to_follow:Node2D

func _process(delta):

position = object_to_follow.position

func _physics_process(delta):

pass

Common questions

Con tecnología de IA

The use of specific variable types like Vector and Color is crucial in GDScript for graphical applications as they provide precision in defining positions, movements, and appearances. Vectors encapsulate coordinates and allow complex transformations in 2D/3D space, which is essential for movements and animations. Meanwhile, Color defines visual elements, crucial for rendering and aesthetic consistency. Together, they empower developers to create rich, interactive visual experiences that respond fluidly to inputs and internal logic .

GDScript implements error handling primarily through conditional checks ensuring that critical operations only execute when specific conditions are met. For instance, using conditional sequences and boolean evaluations to control flow allows developers to anticipate potential errors by simulating alternative pathways (using 'if', 'elif', 'else') that guide robust decision-making in real-time. This planning reduces program crashes and ensures graceful recovery or continuation, enhancing the fault tolerance of applications .

Arrays in GDScript are vital for managing collections of data dynamically, providing methods like 'append', 'remove_at', and 'find' which offer flexibility in how data is stored and manipulated. They support operations such as iterating over elements, modifying array size, and sorting elements, essential for tasks like inventory management in games. This allows developers to write concise, efficient code while efficiently organizing complex datasets, significantly enhancing program capability .

Default parameter values in functions enhance flexibility by allowing callers to omit arguments, using defaults when specific values aren't provided, thus simplifying function calls. This reduces errors from omitted arguments and eases the function's adaptability to various contexts, as seen in examples like 'crear_mensaje_game_over(nombre, puntos="0")', where defaulting 'puntos' allows for both simplified and detailed calls .

Using abbreviations such as '+=', '-=', '*=', etc., in arithmetic operations can enhance code readability and brevity, which helps in maintaining and understanding code more efficiently. However, if overused, they can obscure logic flow, particularly for complex expressions, making debugging challenging. This trade-off between readability and potential confusion requires balanced use, favoring simple expressions to maintain code clarity .

Global variables in GDScript extend variable scope across multiple functions or nodes, which can simplify data sharing. However, they can complicate maintainability by leading to increased interdependencies between program components and making debugging difficult, as changes to global data might have widespread unintentional effects. Careful management and minimal use are advised to prevent compromising code encapsulation and modularity .

Boolean operators such as 'and', 'or', and 'not' are crucial for controlling program flow, as they allow the combination of multiple conditions to determine the execution path. For example, 'and' and 'or' enable complex condition checks, while 'not' can invert conditions, aiding in scenarios like simulations or game logic where behavior is contingent on multiple factors. This makes code both more versatile and concise by avoiding excessive nesting of simple conditional statements .

Loops, such as 'for' and 'while', in GDScript streamline repetitive tasks, eliminating redundancy by reducing the need for manual repetition of similar code blocks. This not only conserves code length but also minimizes human error and enhances efficiency, as loop constructs efficiently manage iterations. By using 'continue' and 'break', loops become highly flexible, adjusting dynamically to conditions, which can significantly decrease computational load by avoiding unnecessary operations .

Constants in GDScript are defined with the keyword 'const' and are intended to hold values that should not change during the program's execution, while variables defined with 'var' can have their values altered. This distinction promotes program stability and error prevention by ensuring certain important values remain constant, thus preventing accidental modifications that could lead to unexpected behavior or bugs .

Dictionaries in GDScript provide a structured way to manage key-value pairs, offering advantages in handling associative data types by allowing fast lookup, insertion, and deletion operations. This is ideal for contexts where data needs to be accessed by custom identifiers rather than numerical indices, facilitating operations such as inventory or data configuration where the relationship between keys and values is more significant than their order .

También podría gustarte