GDScript Examples

GDScript is the native scripting language for the Godot Game Engine. If you are at all interested in developing games, or experimenting with interactive 2D or 3D graphics or sound it is definitely worth a look.

Array Shuffler

This script outputs a shuffled array to Godot's terminal. It can be easily adapted for any number of purposes, including card or word games. You can see this script run live in a web page here.

Download

extends Node

var origList = ["A","B","C","D","E","F","G","H","I","J"]

func sample(list,amt):
    randomize()
    var shuffled = list.duplicate()
    shuffled.shuffle()
    var sampled = []
    for i in range(amt):
        sampled.append( shuffled.pop_front() )
    return sampled

func _ready():
    print("Original: " + str(origList))
    print("Shuffled: " + str(sample(origList, origList.size())))

Fibonacci Series

This script outputs a Fibonacci series to Godot's terminal. You can see it run live in a web page here.

Download

extends Node

var n1:int = 0          # first term
var n2:int = 1          # second term
var count:int = 0       # counter
var nth:int = 0         # accumulator
var numArray = []        # printing array
var numTerms:int = 20   # length of Fibonacci sequence

func getFibonacci():
    # check for valid terms
    if numTerms <= 0:
       print("Sequence length must be greater than zero.") 
    elif numTerms == 1:
       print("First Fibonacci number is ", n1)
    else:
        print("First ", numTerms, " Fibonacci numbers: ")
        numArray.append(0) # first Fibonacci number is 0
        while count < numTerms - 1:
            nth = n1 + n2
            n1 = n2
            n2 = nth
            numArray.append(n1)
            count += 1

func numOutput():
    var i = 0
    var numStr = ''
    while i < numArray.size():
        # correct comma formatting
        if i > 0:
            numStr = numStr + ', ' + str(numArray[i])
        else:
            numStr = numStr + str(numArray[i])
        i += 1
    print (numStr)

func _ready():
    getFibonacci()
    numOutput()

Thanks to https://tohtml.com/python/ for providing an online code to HTML utility.