0% found this document useful (0 votes)
18 views52 pages

Gd Script

gd script

Uploaded by

marcopomoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views52 pages

Gd Script

gd script

Uploaded by

marcopomoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

GDScript Playground

https://gd.tumeo.space/
Introduction to GDScript
1. Introduction to GDScript
• GDScript is a high-level, dynamically typed programming language
used to create games and applications within the Godot Engine.

• It is designed specifically for Godot, making it tightly integrated with


the engine's features.
Learning Objectives:
• Understand what GDScript is and its purpose.
• Familiarize with GDScript's syntax and structure.
• Get comfortable writing basic GDScript scripts.
2. Basics and Fundamentals of
GDScript
2.1 Variables and Data Types
• Variables are used to store information that can be referenced and
manipulated within a program. GDScript supports several data types,
including integers, floats, strings, and booleans.
Example: extends Node
var var_sample = "Cortez"

var age = 25 # Integer func _ready():


var type_of_my_name = typeof(var_sample)
var name = "Godot" # String match type_of_my_name:
TYPE_NIL: print("Data type: Nil")
var height = 5.9 # Float TYPE_BOOL: print("Data type: Bool")
TYPE_INT: print("Data type: Int")
var is_active = true # Boolean TYPE_FLOAT: print("Data type: Float")
TYPE_STRING: print("Data type: String")
TYPE_VECTOR2: print("Data type: Vector2")
TYPE_VECTOR3: print("Data type: Vector3")
TYPE_OBJECT: print("Data type: Object")
Challenge: Write a script that:
• Defines three variables: x, y, and z.
• Assigns values to x and y.
• Sets z to the sum of x and y.
• Prints the value of z.
2.2 Constants
• Constants are similar to variables but cannot be changed once
defined. They are often used for values that remain constant
throughout the program.
Example:
const PI = 3.14159
const MAX_PLAYERS = 4
2.3 Operators and Operands
• Operators are symbols that tell the program to perform specific
mathematical, logical, or relational operations. Operands are the
values or variables on which the operators act.
Example:
var a = 10
var b = 5
var sum = a + b # Addition
var difference = a - b # Subtraction
var product = a * b # Multiplication
var quotient = a / b # Division
var remainder = a % b # Modulus
Challenge: Write a script that:
• Defines two variables width and height.
• Calculates and prints the area of a rectangle using these variables.
2.4 Conditional Statements
(if/elif/else)
• Conditional statements allow you to execute certain code blocks
based on specific conditions.
Example:
var score = 85

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or lower")
Challenge:
Create a variable temperature, then write a conditional statement that
prints:
"It's hot" if temperature is greater than 30.
"It's warm" if it's between 20 and 30,
and "It's cold" if it's below 20.
I strongly discourage using ChatGPT or any AI
tools to answer direct coding problems.
Challenge:
Takes an integer number and checks if it's positive, negative, or zero.
Prints an appropriate message for each case.
2.5 Loops (while loop)
• Loops allow you to execute a block of code multiple times. The while
loop runs as long as a specified condition is true.
Example:
var count = 0

while count < 5:


print("Count is", count)
count += 1
DON’T JUST WRITE CODE YOU
DON’T UNDERSTAND!
2.6 Loops (for loop)
• A for loop is a control flow statement that allows code to be executed
repeatedly by iterating over a sequence of elements (such as a range
of numbers, an array, or other iterable structures). The loop continues
for each item in the sequence, executing the code block inside the
loop.

• In GDScript, the for loop typically uses the range() function or iterates
over elements in a list, dictionary, or other iterable collections.
Example: Iterating Over a Range of
Numbers
for i in range(5):
print(i)
Example: Iterating Over an Array
var fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)
Challenge:
1. Using for loop, print all odd numbers from 1 to 30.
Challenge:
2. Given a list of numbers, find the product of all even numbers.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Expected result:
The product is: 46080
2.7 Match Statement
• The match statement in GDScript is similar to the switch statement in
other languages. It allows you to compare a variable against multiple
values and execute different code depending on the match.
Example:
var day = "Monday"

match day:
"Monday", "Wednesday", "Friday":
print("You have classes today.")
"Saturday", "Sunday":
print("It's the weekend!")
_:
print("It's a regular day.")
Challenge:
Defines a variable command with values like "start", "stop", or "pause".
Uses a match statement to print appropriate actions based on the value
of command.
Intermediate GDScript
Concepts
1. Introduction
• This lesson will introduce functions, arrays, dictionaries, and object-
oriented programming (OOP) principles in GDScript.
Learning Objectives:
• Understand and create functions in GDScript.
• Work with arrays and dictionaries to manage collections of data.
• Explore basic object-oriented programming concepts like classes and
inheritance.
2. Intermediate Concepts in
GDScript
2.1 Functions
• Functions are reusable blocks of code that perform a specific task.
They help organize your code and make it more modular and
readable.
Example:
func greet(name):
print("Hello, " + name + "!")

greet("Godot")
Challenge:
1. Write a function called add_numbers that takes two arguments and
returns their sum.
2. Write a function is_even that takes an integer and returns true if it's
even, and false if it's odd.
2.2 Arrays
• Arrays are collections of elements that can be accessed by their index.
They are useful for storing lists of items.
Examples:
var fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # Outputs: apple


fruits.append("date")
print(fruits) # Outputs: ["apple", "banana", "cherry", "date"]
Challenge:
Create an array called numbers with the values [1, 2, 3, 4, 5].

1. Add the number 6 to the array.


2. Print the length of the array.
Challenge:
Given the item array ['HunterXHunter', 'Doraemon', 'Harry Potter',
'Fantastic Beasts'], write a function that determines if a given value
exists within it. The function should take two parameters: the array and
the search item.
If the search item exists in the array, print “Search item exists in the
array”; otherwise, print “Search item does not exist in the array”.
2.3 Dictionaries
• Dictionaries store key-value pairs, similar to objects or maps in other
languages. They allow for quick lookups by key.
Example:
var player = {
"name": "PlayerOne",
"score": 100,
"lives": 3
}

print(player["name"]) # Outputs: PlayerOne


player["score"] += 50
print(player["score"]) # Outputs: 150
Challenge:
1. Create a dictionary car with keys "make", "model", and "year".
Add a new key "color" with a value to the dictionary.
2. Given the dictionaries below, create a function that calculates and
returns the average grade.
var grades = {
"Math": 90,
"Science": 85,
"English": 92,
"History": 88
}
Expected result:
The average grade is: 88
2.4 Object-Oriented Programming
(OOP) in GDScript
2.4.1 Classes and Objects
• In GDScript, you can define classes to create custom objects. A class is
like a blueprint for objects, defining properties and methods
(functions) that the objects will have.
Example:
class_name Player

var name: String


var health: int

func _init(_name, _health):


name = _name
health = _health

func take_damage(amount):
health -= amount
if health <= 0:
print(name + " is dead.")

var player = Player.new("Hero", 100)


player.take_damage(20)
Challenge:
Create a class Animal with properties name and sound.
Add a method make_sound that prints the sound the animal makes.
Create an instance of Animal and call make_sound.
Challenge:
Defines a class Enemy with properties like type, health, and damage.
Adds a method attack that prints an attack message.
Creates multiple Enemy objects with different types and attacks.
2.4.2 Inheritance
• Inheritance allows a class to inherit properties and methods from
another class. This helps in reusing code and creating a hierarchy of
classes.
Example:
class_name Enemy

var health: int

func take_damage(amount):
health -= amount
if health <= 0:
print("Enemy defeated.")

class Boss extends Enemy

var special_attack: String

func use_special():
print("Boss uses " + special_attack + "!")
Challenge:
Create a base class Vehicle with properties speed and color.
Create a subclass Car that inherits from Vehicle and adds a new
property make.
Create an instance of Car and print its properties.
Challenge:
Defines a class Character with properties like name and level.
Defines a subclass Wizard that adds a property mana and a method
cast_spell.
Creates a Wizard object and demonstrates casting a spell.
Remember:

I strongly discourage using ChatGPT or any AI


tools to answer direct coding problems.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy