Skip to content

Commit

Permalink
Count levels dynamically
Browse files Browse the repository at this point in the history
Previously, the number of levels was hardcoded in the Global script, and would
have to match the number of scene files in the TileMap directory.

Instead, when Global is initialized, enumerate the numbered scene files in that
directory; sort them numerically; and load them for good measure. The number of
levels is then determined from the number of scenes found.

Fixes #5
  • Loading branch information
wjt committed Jan 13, 2025
1 parent 000209e commit e972fbc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
5 changes: 1 addition & 4 deletions Script/Game.gd
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
extends Node2D

var tmpath := "res://TileMap/"
enum {TILE_WALL = 0, TILE_PLAYER = 1, TILE_GOOBER = 2}
var Map: TileMapLayer

Expand Down Expand Up @@ -43,9 +42,7 @@ func _process(delta):
MapChange(delta)

func MapLoad():
var nxtlvl = min(global.level, global.lastLevel)
var tm = load(tmpath + str(nxtlvl) + ".tscn").instantiate()
tm.name = "TileMapLayer"
var tm = global.instantiate_level()
add_child(tm)
Map = tm

Expand Down
38 changes: 36 additions & 2 deletions Script/Global.gd
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
extends Node2D

const DEFAULT_WORLD := "res://TileMap/"

var _levels: Array[PackedScene]
var level := 0
const firstLevel := 0
const lastLevel := 21
var lastLevel: int
var Game

var OST = load("res://Audio/OST.mp3")
var audio

func _ready():
load_levels(DEFAULT_WORLD)

await get_tree().create_timer(0.1).timeout

audio = AudioStreamPlayer.new()
add_child(audio)
audio.stream = OST
Expand All @@ -23,5 +28,34 @@ func _input(event):
DisplayServer.mouse_set_mode(DisplayServer.MOUSE_MODE_VISIBLE if win_full else DisplayServer.MOUSE_MODE_HIDDEN)
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED if win_full else DisplayServer.WINDOW_MODE_FULLSCREEN)

## Load a series of numbered scenes from the given directory.
## Each must be a TileMapLayer node.
func load_levels(tilemap_dir: String):
_levels.clear()

var levelrx := RegEx.new()
levelrx.compile("^(\\d+).tscn$")

var level_paths: Array[String]
var dir := DirAccess.open(tilemap_dir)
dir.list_dir_begin()
var file := dir.get_next()
while file:
var rxmatch := levelrx.search(file)
if rxmatch:
level_paths.append(file)

file = dir.get_next()

level_paths.sort_custom(func (a: String, b: String): return a.naturalnocasecmp_to(b) < 0)
for path in level_paths:
var l := load(tilemap_dir.path_join(path)) as PackedScene
_levels.append(l)

lastLevel = _levels.size() - 1

func instantiate_level() -> Node:
return _levels[level].instantiate()

func wrapp(pos := Vector2.ZERO):
return Vector2(wrapf(pos.x, 0.0, 144.0), wrapf(pos.y, 0.0, 144.0))

0 comments on commit e972fbc

Please sign in to comment.