Menu
CoddyTech

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 columns

A 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()) # 2
challenge icon

Challenge

Easy

Build 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 1

Each 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler