Using godot c# to make a simple tetris game
- User
Using godot c# to make a simple tetris game
Assistant
Simple Tetris Game in Godot with C#
Here's a complete implementation of a simple Tetris game using Godot and C#. This code doesn't rely on 2D textures and uses basic shapes for rendering.
Project Setup
- Create a new Godot project
- Enable C# support when creating the project
- Create the following files in your project
Main Scene Structure
Create a main scene with a Node2D as the root and add the following script to it:
using Godot; using System; using System.Collections.Generic; public partial class TetrisGame : Node2D { // Game Constants private const int GridWidth = 10; private const int GridHeight = 20; private const int BlockSize = 30; private const float MoveDelay = 0.5f; // Game state private int[,] grid = new int[GridWidth, GridHeight]; private Tetromino currentPiece; private Tetromino nextPiece; private float timeSinceLastMove = 0; private bool gameOver = false; private int score = 0; private Random random = new Random(); // Called when the node enters the scene tree for the first time public override void _Ready() { // Initialize game currentPiece = GenerateRandomPiece(); nextPiece = GenerateRandomPiece(); } // Called every frame public override void _Process(double delta) { if (gameOver) return; // Handle automatic piece movement timeSinceLastMove += (float)delta; if (timeSinceLastMove >= MoveDelay) { timeSinceLastMove = 0; MovePieceDown(); } // Handle input ProcessInput(); // Force redraw QueueRedraw(); } // Override _Draw to render the game public override void _Draw() { // Draw grid background DrawRect(new Rect2(0, 0, GridWidth * BlockSize, GridHeight * BlockSize), new Color(0.1f, 0.1f, 0.1f)); // Draw grid lines for (int x = 0; x <= GridWidth; x++) { DrawLine(new Vector2(x * BlockSize, 0), new Vector2(x * BlockSize, GridHeight * BlockSize), new Color(0.3f, 0.3f, 0.3f)); } for (int y = 0; y <= GridHeight; y++) { DrawLine(new Vector2(0, y * BlockSize), new Vector2(GridWidth * BlockSize, y * BlockSize), new Color(0.3f, 0.3f, 0.3f)); } // Draw placed blocks for (int x = 0; x < GridWidth; x++) { for (int y = 0; y < GridHeight; y++) { if (grid[x, y] != 0) { DrawBlock(x, y, GetColorForValue(grid[x, y])); } } } // Draw current piece if (currentPiece != null) { foreach (Vector2I block in currentPiece.Blocks) { DrawBlock(currentPiece.Position.X + block.X, currentPiece.Position.Y + block.Y, currentPiece.Color); } } // Draw score DrawString(GetThemeFont("font", "Label"), new Vector2(GridWidth * BlockSize + 20, 30), $"Score: {score}", modulate: Colors.White); // Draw game over message if (gameOver) { DrawString(GetThemeFont("font", "Label"), new Vector2(GridWidth * BlockSize / 2 - 50, GridHeight * BlockSize / 2), "GAME OVER", modulate: Colors.Red); } } private void DrawBlock(int x, int y, Color color) { Rect2 rect = new Rect2(x * BlockSize, y * BlockSize, BlockSize, BlockSize); DrawRect(rect, color); DrawRect(rect, new Color(0, 0, 0, 0), false, 2); // Border } private void ProcessInput() { if (Input.IsActionJustPressed("ui_left")) { MovePieceHorizontal(-1); } else if (Input.IsActionJustPressed("ui_right")) { MovePieceHorizontal(1); } else if (Input.IsActionJustPressed("ui_down")) { MovePieceDown(); } else if (Input.IsActionJustPressed("ui_up")) { RotatePiece(); } else if (Input.IsActionJustPressed("ui_accept")) // Space bar for hard drop { HardDrop(); } } private void MovePieceHorizontal(int dx) { currentPiece.Position += new Vector2I(dx, 0); if (!IsValidPosition()) { // Move back if invalid currentPiece.Position -= new Vector2I(dx, 0); } } private void MovePieceDown() { currentPiece.Position += new Vector2I(0, 1); if (!IsValidPosition()) { // Move back if invalid currentPiece.Position -= new Vector2I(0, 1); PlacePiece(); } } private void HardDrop() { while (IsValidPosition()) { currentPiece.Position += new Vector2I(0, 1); } // Move back one step since the last position was invalid currentPiece.Position -= new Vector2I(0, 1); PlacePiece(); } private void RotatePiece() { List<Vector2I> originalBlocks = new List<Vector2I>(currentPiece.Blocks); // Rotate for (int i = 0; i < currentPiece.Blocks.Count; i++) { Vector2I block = currentPiece.Blocks[i]; currentPiece.Blocks[i] = new Vector2I(-block.Y, block.X); } // Check if valid, revert if not if (!IsValidPosition()) { currentPiece.Blocks = originalBlocks; } } private void PlacePiece() { // Add the current piece to the grid foreach (Vector2I block in currentPiece.Blocks) { int x = currentPiece.Position.X + block.X; int y = currentPiece.Position.Y + block.Y; if (y < 0) { // Game over if a piece is placed above the grid gameOver = true; return; } grid[x, y] = currentPiece.ColorValue; } // Check for completed lines CheckLines(); // Get the next piece currentPiece = nextPiece; nextPiece = GenerateRandomPiece(); // Check if the new piece can be placed if (!IsValidPosition()) { gameOver = true; } } private void CheckLines() { int linesCleared = 0; for (int y = GridHeight - 1; y >= 0; y--) { bool lineComplete = true; for (int x = 0; x < GridWidth; x++) { if (grid[x, y] == 0) { lineComplete = false; break; } } if (lineComplete) { linesCleared++; // Move all lines above down for (int y2 = y; y2 > 0; y2--) { for (int x = 0; x < GridWidth; x++) { grid[x, y2] = grid[x, y2 - 1]; } } // Clear the top line for (int x = 0; x < GridWidth; x++) { grid[x, 0] = 0; } // Stay on the same line (since we moved everything down) y++; } } // Update score based on lines cleared if (linesCleared > 0) { score += linesCleared * linesCleared * 100; } } private bool IsValidPosition() { foreach (Vector2I block in currentPiece.Blocks) { int x = currentPiece.Position.X + block.X; int y = currentPiece.Position.Y + block.Y; // Check if out of bounds if (x < 0 || x >= GridWidth || y >= GridHeight) return false; // Check for collision with placed blocks (only if block is in the grid) if (y >= 0 && grid[x, y] != 0) return false; } return true; } private Tetromino GenerateRandomPiece() { int pieceType = random.Next(7); Tetromino piece = new Tetromino(); piece.Position = new Vector2I(GridWidth / 2, -1); piece.Blocks = new List<Vector2I>(); piece.ColorValue = pieceType + 1; switch (pieceType) { case 0: // I piece piece.Blocks.Add(new Vector2I(-1, 0)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Blocks.Add(new Vector2I(2, 0)); piece.Color = new Color(0, 1, 1); // Cyan break; case 1: // J piece piece.Blocks.Add(new Vector2I(-1, -1)); piece.Blocks.Add(new Vector2I(-1, 0)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Color = new Color(0, 0, 1); // Blue break; case 2: // L piece piece.Blocks.Add(new Vector2I(1, -1)); piece.Blocks.Add(new Vector2I(-1, 0)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Color = new Color(1, 0.5f, 0); // Orange break; case 3: // O piece piece.Blocks.Add(new Vector2I(0, -1)); piece.Blocks.Add(new Vector2I(1, -1)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Color = new Color(1, 1, 0); // Yellow break; case 4: // S piece piece.Blocks.Add(new Vector2I(0, -1)); piece.Blocks.Add(new Vector2I(1, -1)); piece.Blocks.Add(new Vector2I(-1, 0)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Color = new Color(0, 1, 0); // Green break; case 5: // T piece piece.Blocks.Add(new Vector2I(0, -1)); piece.Blocks.Add(new Vector2I(-1, 0)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Color = new Color(0.5f, 0, 0.5f); // Purple break; case 6: // Z piece piece.Blocks.Add(new Vector2I(-1, -1)); piece.Blocks.Add(new Vector2I(0, -1)); piece.Blocks.Add(new Vector2I(0, 0)); piece.Blocks.Add(new Vector2I(1, 0)); piece.Color = new Color(1, 0, 0); // Red break; } return piece; } private Color GetColorForValue(int value) { switch (value) { case 1: return new Color(0, 1, 1); // Cyan case 2: return new Color(0, 0, 1); // Blue case 3: return new Color(1, 0.5f, 0); // Orange case 4: return new Color(1, 1, 0); // Yellow case 5: return new Color(0, 1, 0); // Green case 6: return new Color(0.5f, 0, 0.5f); // Purple case 7: return new Color(1, 0, 0); // Red default: return new Color(0.5f, 0.5f, 0.5f); // Gray } } // Reset the game public void ResetGame() { grid = new int[GridWidth, GridHeight]; currentPiece = GenerateRandomPiece(); nextPiece = GenerateRandomPiece(); gameOver = false; score = 0; timeSinceLastMove = 0; } } // Tetromino class to represent a Tetris piece public class Tetromino { public Vector2I Position; public List<Vector2I> Blocks; public Color Color; public int ColorValue; }Tetromino Class
The Tetromino class is defined at the bottom of the main script, but you could also put it in a separate file:
public class Tetromino { public Vector2I Position; public List<Vector2I> Blocks; public Color Color; public int ColorValue; }Project Configuration
-
In the project settings, make sure input mappings are set up:
- ui_left: Left arrow key
- ui_right: Right arrow key
- ui_up: Up arrow key (rotate)
- ui_down: Down arrow key
- ui_accept: Space bar (hard drop)
-
Add a UI button to restart the game after game over:
// Add this to the TetrisGame class private Button restartButton; public override void _Ready() { // Initialize game currentPiece = GenerateRandomPiece(); nextPiece = GenerateRandomPiece(); // Create restart button restartButton = new Button(); restartButton.Text = "Restart Game"; restartButton.Position = new Vector2(GridWidth * BlockSize + 20, 60); restartButton.Pressed += RestartGame; AddChild(restartButton); } private void RestartGame() { ResetGame(); }How to Run
- Save the script as
TetrisGame.cs - Attach it to a Node2D in your scene
- Run the project
Game Controls
- Left/Right Arrow Keys: Move piece horizontally
- Down Arrow Key: Move piece down faster
- Up Arrow Key: Rotate piece
- Space Bar: Hard drop (instantly place the piece at the bottom)
Features
- Basic Tetris gameplay
- Score tracking
- Line clearing
- Game over detection
- Piece rotation and movement
- Visual display of the game grid
This implementation is simple but complete, providing all the essential functionality of Tetris using Godot's built-in drawing methods rather than textures.
Would you like me to explain any specific part of the code in more detail?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.