2D Arrays Basics
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 12 of 78.
A 2D array stores values in rows and columns, like a table or the tiles of a game map. In GDScript, a 2D array is an array whose elements are arrays: each inner array is one row.
var level := [
[1, 1, 1, 1],
[1, 0, 2, 1],
[1, 1, 1, 1]
]In this map, 0 is floor, 1 is a wall and 2 is a coin. Writing one row per line keeps the grid readable, and GDScript also accepts the whole literal on one line.
print() shows a 2D array on one line, with each row inside its own brackets:
print(level)[[1, 1, 1, 1], [1, 0, 2, 1], [1, 1, 1, 1]]size() on the outer array counts the rows. level[0] is the first row, an ordinary array, so level[0].size() counts the columns:
print(level.size()) # 3 rows
print(level[0].size()) # 4 columnsA for loop over the outer array gives you one row per pass:
for row in level:
print(row)[1, 1, 1, 1]
[1, 0, 2, 1]
[1, 1, 1, 1]The cells can be of any type: [["X", "O"], ["O", "X"]] is a grid of strings. You can also start from an empty array and append() whole rows:
var board := []
board.append(["X", "O", "X"])
board.append(["O", "X", "O"])
print(board.size()) # 2Challenge
EasyBuild the map of a small dungeon. Create a 2D array called level with these 4 rows, in this order:
1 1 1 1 1
1 0 2 0 1
1 0 1 3 1
1 1 1 1 1Each row is an array of 5 numbers. Then print the number of rows and the number of columns, using size(), before the given loop prints the rows. The output must be:
Rows: 4
Columns: 5
[1, 1, 1, 1, 1]
[1, 0, 2, 0, 1]
[1, 0, 1, 3, 1]
[1, 1, 1, 1, 1]Try it yourself
extends Node
func _ready():
# Replace [] with the dungeon map
var level := []
# Print the number of rows and of columns here
for row in level:
print(row)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler