usg/src/movement.zig

82 lines
2.6 KiB
Zig
Raw Normal View History

2022-06-28 12:42:28 +00:00
const Grid = @import("grid.zig");
const Piece = @import("piece.zig");
pub fn moveRight(grid: Grid, piece: Piece) Piece {
var new_piece = piece;
new_piece.col += 1;
for (new_piece.structure) |_, y| {
for (new_piece.structure[y]) |_, x| {
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
@intCast(i32, x) + new_piece.col > Grid.ncolumns - 1)
{
2022-06-28 12:42:28 +00:00
return piece;
}
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
!grid.cells[@intCast(usize, new_piece.row + @intCast(i32, y))][@intCast(usize, new_piece.col + @intCast(i32, x))].free)
{
2022-06-28 12:42:28 +00:00
return piece;
}
}
}
return new_piece;
}
pub fn moveLeft(grid: Grid, piece: Piece) Piece {
var new_piece = piece;
new_piece.col -= 1;
for (new_piece.structure) |_, y| {
for (new_piece.structure[y]) |_, x| {
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
@intCast(i32, x) + new_piece.col < 0)
{
2022-06-28 12:42:28 +00:00
return piece;
}
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
!grid.cells[@intCast(usize, new_piece.row + @intCast(i32, y))][@intCast(usize, new_piece.col + @intCast(i32, x))].free)
{
2022-06-28 12:42:28 +00:00
return piece;
}
}
}
return new_piece;
}
pub fn moveDown(grid: Grid, piece: Piece) Piece {
var new_piece = piece;
new_piece.row += 1;
for (new_piece.structure) |_, y| {
for (new_piece.structure[y]) |_, x| {
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
@intCast(i32, y) + new_piece.row > Grid.nrows - 1)
{
new_piece.row -= 1;
new_piece.dropped = true;
return new_piece;
2022-06-28 12:42:28 +00:00
}
if (new_piece.structure[y][x] and
2022-06-28 16:42:40 +00:00
!grid.cells[@intCast(usize, new_piece.row + @intCast(i32, y))][@intCast(usize, new_piece.col + @intCast(i32, x))].free)
{
new_piece.row -= 1;
new_piece.dropped = true;
return new_piece;
2022-06-28 12:42:28 +00:00
}
}
}
return new_piece;
}
2022-06-28 16:42:40 +00:00
pub fn drop(grid: Grid, piece: Piece) Grid {
var new_grid = grid;
for (piece.structure) |_, y| {
for (piece.structure[y]) |_, x| {
if (piece.structure[y][x]) {
new_grid.cells[@intCast(usize, piece.row + @intCast(i32, y))][@intCast(usize, piece.col + @intCast(i32, x))].free = false;
new_grid.cells[@intCast(usize, piece.row + @intCast(i32, y))][@intCast(usize, piece.col + @intCast(i32, x))].color = piece.color;
}
}
}
return new_grid;
}