added snake game#3203
Open
vivek2004-sec wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR adds a classic Snake game implementation using tkinter. The player controls a snake using the arrow keys, guiding it around a canvas to eat randomly-placed food. Each time the snake eats food, it grows longer and the score increases; the game ends if the snake collides with the canvas walls or its own body.
Core components:
Snake class — initializes the snake's starting body segments (as coordinates and canvas rectangles)
Food class — spawns food at a random grid-aligned position on the canvas
next_turn() — the main game loop: moves the snake each tick based on current direction, checks for food collision (grow + increment score) or normal movement (remove tail segment), checks for game-ending collisions, and re-schedules itself via window.after()
change_direction() — handles arrow key input, with a safeguard preventing the snake from reversing directly into itself (e.g., can't go left while moving right)
check_collisions() — detects wall collisions and self-collisions
game_over() — clears the canvas and displays a "GAME OVER" message
The game window is also centered on the screen at launch using screen/window dimension calculations.
Problem it solves: Adds a complete, playable, classic arcade game to the repository as an example of tkinter canvas manipulation, game loops using window.after(), and simple 2D collision detection — useful as a learning reference for GUI-based game development in Python.
Type of Change
Related Issues
Closes #(issue number)
Testing
Please describe the tests you've run to verify your changes:
Checklist
Screenshots (if applicable)
Add screenshots or demos of your changes if relevant.