rust
use macroquad::prelude::*;
const GRID_SIZE: Vec2 = Vec2::new(10.0, 20.0);
const CELL_SIZE: f32 = 30.0;
const WINDOW_SIZE: Vec2 = Vec2::new(GRID_SIZE.x * CELL_SIZE, GRID_SIZE.y * CELL_SIZE);
#[derive(Clone, Copy, PartialEq)]
enum Block {
Empty,
Filled(usize),
}
struct Piece {
shape: [[bool; 4]; 4],
color: usize,
pos: Vec2,
}
impl Piece {
fn rotate(&mut self) {
let mut new_shape = [[false; 4]; 4];
for y in 0..4 {
for x in 0..4 {
new_shape[x][3 - y] = self.shape[y][x];
}
}
if !check_collision(&new_shape, self.pos) {
self.shape = new_shape;
}
}
}
struct Game {
grid: [[Block; GRID_SIZE.x as usize]; GRID_SIZE.y as usize],
current_piece: Piece,
score: u32,
}
impl Game {
fn new() -> Self {
let mut grid = [[Block::Empty; GRID_SIZE.x as usize]; GRID_SIZE.y as usize];
let current_piece = create_random_piece();
Game { grid, current_piece, score: 0 }
}
fn update(&mut self, dt: f32) {
// Movement and input handling
if is_key_pressed(KeyCode::Left) {
self.current_piece.pos.x -= 1.0;
if check_collision(&self.current_piece.shape, self.current_piece.pos) {
self.current_piece.pos.x += 1.0;
}
}
if is_key_pressed(KeyCode::Right) {
self.current_piece.pos.x += 1.0;
if check_collision(&self.current_piece.shape, self.current_piece.pos) {
self.current_piece.pos.x -= 1.0;
}
}
if is_key_pressed(KeyCode::Up) {
self.current_piece.rotate();
}
// Gravity
self.current_piece.pos.y += 1.0 * dt as f32;
if check_collision(&self.current_piece.shape, self.current_piece.pos) {
self.current_piece.pos.y -= 1.0;
self.lock_piece();
}
}
fn lock_piece(&mut self) {
// Add current piece to grid
// Check lines
// Spawn new piece
}
}
fn check_collision(shape: &[[bool; 4]; 4], pos: Vec2) -> bool {
// Collision detection logic
false
}
fn create_random_piece() -> Piece {
// Generate random tetromino
Piece {
shape: [[false; 4]; 4],
color: 0,
pos: Vec2::new(GRID_SIZE.x / 2.0, 0.0),
}
}
#[macroquad::main("Tetris")]
async fn main() {
let mut game = Game::new();
loop {
clear_background(Color::new(0.1, 0.1, 0.1, 1.0));
game.update(get_frame_time());
// Rendering
for y in 0..GRID_SIZE.y as usize {
for x in 0..GRID_SIZE.x as usize {
let cell = game.grid[y][x];
if let Block::Filled(color) = cell {
draw_rectangle(
x as f32 * CELL_SIZE,
y as f32 * CELL_SIZE,
CELL_SIZE,
CELL_SIZE,
Color::new(1.0, 1.0, 1.0, 1.0)
);
}
}
}
next_frame().await
}
}
Это базовая структура. Для полной реализации нужно:
Если есть конкретные ошибки - укажите, исправлю.