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(array.size())
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 array.size():
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"]
inventario.append("hierbas")
for objeto in inventario:
print(objeto)
for posicion in inventario.size():
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)
inventario.insert(2,"lanza")
print(inventario.find("arma"))
print(inventario.has("arma"))
loot.reverse()
loot.sort()
loot.shuffle()
loot.clear()
print(loot)
print(inventario)
Ejemplo de uso
func _ready():
var inventario = []
var loot = ["pocion","arma","escudo"]
loot.shuffle()
inventario.append(loot[0])
loot.clear()
print(inventario)
print(loot)
Diccionarios
func _ready():
var inventario = {
hierbas = 15,
madera = 1300,
"pocion vacia" = 10,
print(inventario["hierbas"])
print(inventario.hierbas)
inventario.hechizos = ["lumos", "windardium leviosa", "avada kedavra"]
inventario.hierbas += 1
inventario.erase("madera")
print(inventario)
for clave in inventario.keys():
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 = texto.split(" ")
print(array_trozos)
print(texto.to_upper())
print(texto.to_lower())
texto = texto.replace("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 inventario.has(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):
arr.append(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 = Vector3.ZERO
var mi_puntaje = GLOBAL.score
Camera2D
extends Camera2D
@export var object_to_follow:Node2D
func _process(delta):
position = object_to_follow.position
func _physics_process(delta):
pass