Using godot c# to make a simple tetris game
- User
Using godot c# to make a simple tetris game
Assistant
Below is a simple implementation of Tetris using Godot 4 with C#. This version uses basic
ColorRectnodes to represent blocks instead of textures, making it lightweight and easy to understand.
Step 1: Set Up the Project
- Create a new Godot 4 project.
- Attach a C# script to the main scene (e.g.,
Main.cs).
Step 2: Game Structure
- Game Board: A grid of
ColorRectnodes. - Tetrominoes: Represented as arrays of block positions.
- Controls: Arrow keys for movement, spacebar for rotation.
Step 3: Full Code
Main.cs
using Godot; using System; using System.Collections.Generic; public partial class Main : Node { // Constants private const int GridWidth = 10; private const int GridHeight = 20; private const int BlockSize = 30; private const int FallSpeed = 500; // Milliseconds per step // Variables private Grid grid; private Tetromino currentPiece; private Tetromino nextPiece; private Timer fallTimer; private bool gameOver; public override void _Ready() { grid = new Grid(GridWidth, GridHeight, BlockSize); AddChild(grid); grid.Position = new Vector2(100, 100); fallTimer = new Timer(); AddChild(fallTimer); fallTimer.WaitTime = FallSpeed / 1000f; // Convert milliseconds to seconds fallTimer.Timeout += OnFallTimerTimeout; fallTimer.Start(); NewGame(); } private void NewGame() { grid.Clear(); gameOver = false; SpawnPiece(); } private void SpawnPiece() { if (nextPiece == null) { nextPiece = Tetromino.CreateRandom(); } currentPiece = nextPiece; nextPiece = Tetromino.CreateRandom(); currentPiece.Position = new Vector2(GridWidth / 2 - 1, 0); if (!grid.CanPlace(currentPiece)) { GameOver(); return; } grid.Place(currentPiece, false); } private void GameOver() { gameOver = true; fallTimer.Stop(); GD.Print("Game Over!"); } private void OnFallTimerTimeout() { if (gameOver) return; if (CanMove(currentPiece, Vector2.Down)) { MovePiece(Vector2.Down); } else { grid.Place(currentPiece, true); ClearLines(); SpawnPiece(); } } private void MovePiece(Vector2 direction) { grid.Place(currentPiece, false); // Remove current position currentPiece.Position += direction; grid.Place(currentPiece, false); // Place new position } private bool CanMove(Tetromino piece, Vector2 direction) { var newPosition = piece.Position + direction; return grid.CanPlace(piece, newPosition); } private void ClearLines() { for (int y = GridHeight - 1; y >= 0; y--) { if (grid.IsLineFull(y)) { grid.ClearLine(y); grid.ShiftDown(y); y++; // Recheck the same line after shifting } } } public override void _Process(double delta) { if (gameOver) return; if (Input.IsActionJustPressed("ui_down")) { while (CanMove(currentPiece, Vector2.Down)) { MovePiece(Vector2.Down); } fallTimer.Start(0); // Reset fall timer } if (Input.IsActionJustPressed("ui_left")) MovePiece(Vector2.Left); if (Input.IsActionJustPressed("ui_right")) MovePiece(Vector2.Right); if (Input.IsActionJustPressed("ui_rotate")) RotatePiece(); } private void RotatePiece() { var rotatedBlocks = Tetromino.RotateBlocks(currentPiece.Blocks); var offsetPosition = currentPiece.Position; // Wall kicks (basic) for (int i = 0; i < 2; i++) { if (grid.CanPlace(new Tetromino(offsetPosition, rotatedBlocks))) { currentPiece.Blocks = rotatedBlocks; return; } offsetPosition.X -= (i % 2 == 0) ? 1 : -1; // Try left, then right } } }Grid.cs
using Godot; using System.Collections.Generic; public partial class Grid : Node2D { private int width; private int height; private int blockSize; private ColorRect[,] gridArray; public Grid(int width, int height, int blockSize) { this.width = width; this.height = height; this.blockSize = blockSize; gridArray = new ColorRect[width, height]; } public override void _Ready() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { gridArray[x, y] = new ColorRect { Color = Colors.Transparent, Size = new Vector2(blockSize, blockSize) }; AddChild(gridArray[x, y]); gridArray[x, y].Position = new Vector2(x, y) * blockSize; } } } public void Clear() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { gridArray[x, y].Color = Colors.Transparent; } } } public bool CanPlace(Tetromino piece, Vector2? position = null) { var pos = (position != null) ? (Vector2)position : piece.Position; foreach (var block in piece.Blocks) { int x = (int)(pos.X + block.X); int y = (int)(pos.Y + block.Y); if (x < 0 || x >= width || y >= height || (y >= 0 && gridArray[x, y].Color != Colors.Transparent)) { return false; } } return true; } public void Place(Tetromino piece, bool lockPiece) { foreach (var block in piece.Blocks) { int x = (int)(piece.Position.X + block.X); int y = (int)(piece.Position.Y + block.Y); if (y >= 0 && y < height) { gridArray[x, y].Color = lockPiece ? piece.Color : Colors.White; } } } public bool IsLineFull(int y) { for (int x = 0; x < width; x++) { if (gridArray[x, y].Color == Colors.Transparent) return false; } return true; } public void ClearLine(int y) { for (int x = 0; x < width; x++) { gridArray[x, y].Color = Colors.Transparent; } } public void ShiftDown(int startRow) { for (int y = startRow; y > 0; y--) { for (int x = 0; x < width; x++) { gridArray[x, y].Color = gridArray[x, y - 1].Color; } } for (int x = 0; x < width; x++) { gridArray[x, 0].Color = Colors.Transparent; } } }Tetromino.cs
using Godot; using System.Collections.Generic; public class Tetromino { public Vector2 Position { get; set; } public List<Vector2> Blocks { get; set; } public Color Color { get; set; } public Tetromino(Vector2 position, List<Vector2> blocks, Color color) { Position = position; Blocks = blocks; Color = color; } public static Tetromino CreateRandom() { var rng = new RandomNumberGenerator(); rng.Randomize(); int type = rng.RandiRange(0, 6); return new Tetromino(Vector2.Zero, GetBlocksForType(type), GetColorForType(type)); } private static List<Vector2> GetBlocksForType(int type) { switch (type) { case 0: return new List<Vector2> { new(0, 0), new(-1, 0), new(1, 0), new(2, 0) }; // I case 1: return new List<Vector2> { new(0, 0), new(0, 1), new(1, 0), new(1, -1) }; // S case 2: return new List<Vector2> { new(0, 0), new(0, 1), new(-1, 0), new(-1, -1) }; // Z case 3: return new List<Vector2> { new(0, 0), new(0, 1), new(1, 0), new(-1, 0) }; // O case 4: return new List<Vector2> { new(0, 0), new(0, 1), new(1, 1), new(-1, 0) }; // L case 5: return new List<Vector2> { new(0, 0), new(0, 1), new(1, 0), new(0, -1) }; // T case 6: return new List<Vector2> { new(0, 0), new(0, 1), new(-1, 1), new(1, 0) }; // J default: return new List<Vector2>(); } } private static Color GetColorForType(int type) { switch (type) { case 0: return Colors.Cyan; case 1: return Colors.Green; case 2: return Colors.Red; case 3: return Colors.Yellow; case 4: return Colors.Orange; case 5: return Colors.Purple; case 6: return Colors.Blue; default: return Colors.White; } } public static List<Vector2> RotateBlocks(List<Vector2> blocks) { var rotated = new List<Vector2>(); foreach (var block in blocks) { rotated.Add(new Vector2(-block.Y, block.X)); // 90-degree rotation } return rotated; } }
Step 4: Input Mapping
- Go to Project Settings > Input Map.
- Add the following actions:
ui_down: Down arrow key.ui_left: Left arrow key.ui_right: Right arrow key.ui_rotate: Up arrow key or spacebar.
How It Works
- Grid: Manages the game board using
ColorRectnodes. - Tetromino: Represents each piece with its position, blocks, and color.
- Main Script: Handles game logic (movement, rotation, line clearing).
- Fall Timer: Automatically moves the piece downward.
To Run
- Attach the
Main.csscript to aNodein your scene. - Run the project and use the arrow keys to play!
Let me know if you need help expanding this (e.g., adding scoring, levels, or animations)! 🕹️
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.