2021-01-26 14:10:29 +01:00
|
|
|
//! Level structure, grid containing tile data.
|
2021-01-25 19:07:48 +01:00
|
|
|
const std = @import("std");
|
|
|
|
const expect = std.testing.expect;
|
|
|
|
|
2021-01-26 14:10:29 +01:00
|
|
|
const Self = @This();
|
2021-01-26 13:10:16 +01:00
|
|
|
|
2021-01-26 14:10:29 +01:00
|
|
|
const cell_t = u16;
|
|
|
|
|
|
|
|
width: u16,
|
|
|
|
height: u16,
|
|
|
|
buffer: []cell_t,
|
|
|
|
|
2021-01-26 14:46:32 +01:00
|
|
|
/// Create structure and allocate required memory. The `buffer` array size will
|
|
|
|
/// be equal to `width` times `height`.
|
2021-01-26 14:10:29 +01:00
|
|
|
pub fn init(allocator: *std.mem.Allocator, width: u16, height: u16) !Self {
|
|
|
|
var level = Self{
|
|
|
|
.width = width,
|
|
|
|
.height = height,
|
|
|
|
.buffer = undefined,
|
|
|
|
};
|
|
|
|
level.buffer = try allocator.alloc(cell_t, width * height);
|
|
|
|
return level;
|
|
|
|
}
|
|
|
|
|
2021-01-26 14:46:32 +01:00
|
|
|
/// Free the level buffer.
|
2021-01-26 14:10:29 +01:00
|
|
|
pub fn deinit(self: *Self, allocator: *std.mem.Allocator) void {
|
|
|
|
allocator.free(self.buffer);
|
|
|
|
}
|
2021-01-25 19:07:48 +01:00
|
|
|
|
|
|
|
test "create level buffer" {
|
2021-01-26 13:10:16 +01:00
|
|
|
// Create allocator.
|
|
|
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
|
|
defer {
|
|
|
|
const leaked = gpa.deinit();
|
|
|
|
if (leaked) expect(false); //fail test
|
|
|
|
}
|
|
|
|
const allocator = &gpa.allocator;
|
|
|
|
|
|
|
|
// Initialize level struct (twice 'cause why not?).
|
2021-01-26 14:10:29 +01:00
|
|
|
var level: Self = try Self.init(allocator, 64, 32);
|
2021-01-26 13:10:16 +01:00
|
|
|
level.deinit(allocator);
|
2021-01-26 14:10:29 +01:00
|
|
|
level = try Self.init(allocator, 64, 64);
|
2021-01-26 13:10:16 +01:00
|
|
|
defer level.deinit(allocator);
|
|
|
|
|
|
|
|
level.buffer[128] = 32;
|
|
|
|
|
|
|
|
expect(level.buffer[128] == 32);
|
2021-01-25 19:07:48 +01:00
|
|
|
expect(level.width == 64);
|
2021-01-26 13:10:16 +01:00
|
|
|
expect(level.height == 64);
|
2021-01-25 19:07:48 +01:00
|
|
|
}
|