Free Game codes for Python!

Guess Correct number game in Python!

import random


def guess_the_number():

    print("Welcome to Guess the Number!")

    print("I have selected a random number between 1 and 100. Try to guess it.")


    # Generate a random number between 1 and 100

    secret_number = random.randint(1, 100)


    # Initialize variables

    attempts = 0

    max_attempts = 10


    while attempts < max_attempts:

        # Get the player's guess

        guess = int(input("Enter your guess: "))


        # Increment attempts

        attempts += 1


        # Check if the guess is correct

        if guess == secret_number:

            print(f"Congratulations! You guessed the number in {attempts} attempts.")

            break

        elif guess < secret_number:

            print("Too low. Try again.")

        else:

            print("Too high. Try again.")


    # If the player couldn't guess the number in max_attempts

    if attempts == max_attempts:

        print(f"Sorry, you've reached the maximum number of attempts. The correct number was {secret_number}.")


if __name__ == "__main__":

    guess_the_number()


Rock /Paper / scissors game !

import random


def rock_paper_scissors():

    print("Welcome to Rock, Paper, Scissors!")

    choices = ["rock", "paper", "scissors"]

    

    while True:

        user_choice = input("Enter your choice (rock, paper, scissors) or 'q' to quit: ").lower()

        if user_choice == 'q':

            break

        

        if user_choice not in choices:

            print("Invalid choice. Try again.")

            continue

        

        computer_choice = random.choice(choices)

        print(f"Computer chooses {computer_choice}")


        if user_choice == computer_choice:

            print("It's a tie!")

        elif (

            (user_choice == "rock" and computer_choice == "scissors") or

            (user_choice == "paper" and computer_choice == "rock") or

            (user_choice == "scissors" and computer_choice == "paper")

        ):

            print("You win!")

        else:

            print("You lose!")


if __name__ == "__main__":

    rock_paper_scissors()

Python Snake game !

install library to use code!

pip install pygame

code:

import pygame

import sys

import random


# Initialize Pygame

pygame.init()


# Constants

WIDTH, HEIGHT = 600, 400

GRID_SIZE = 20

FPS = 10


# Colors

WHITE = (255, 255, 255)

RED = (255, 0, 0)

GREEN = (0, 255, 0)


# Snake class

class Snake:

    def __init__(self):

        self.length = 1

        self.positions = [((WIDTH // 2), (HEIGHT // 2))]

        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])

        self.color = GREEN


    def get_head_position(self):

        return self.positions[0]


    def update(self):

        cur = self.get_head_position()

        x, y = self.direction

        new = (((cur[0] + (x * GRID_SIZE)) % WIDTH), (cur[1] + (y * GRID_SIZE)) % HEIGHT)

        if len(self.positions) > 2 and new in self.positions[2:]:

            self.reset()

        else:

            self.positions.insert(0, new)

            if len(self.positions) > self.length:

                self.positions.pop()


    def reset(self):

        self.length = 1

        self.positions = [((WIDTH // 2), (HEIGHT // 2))]

        self.direction = random.choice([UP, DOWN, LEFT, RIGHT])


    def render(self, surface):

        for p in self.positions:

            pygame.draw.rect(surface, self.color, (p[0], p[1], GRID_SIZE, GRID_SIZE))


# Food class

class Food:

    def __init__(self):

        self.position = (0, 0)

        self.color = RED

        self.randomize_position()


    def randomize_position(self):

        self.position = (random.randint(0, (WIDTH // GRID_SIZE) - 1) * GRID_SIZE,

                         random.randint(0, (HEIGHT // GRID_SIZE) - 1) * GRID_SIZE)


    def render(self, surface):

        pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))


# Directions

UP = (0, -1)

DOWN = (0, 1)

LEFT = (-1, 0)

RIGHT = (1, 0)


# Main function

def main():

    clock = pygame.time.Clock()

    screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

    surface = pygame.Surface(screen.get_size())

    surface = surface.convert()


    snake = Snake()

    food = Food()


    while True:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_UP:

                    snake.direction = UP

                elif event.key == pygame.K_DOWN:

                    snake.direction = DOWN

                elif event.key == pygame.K_LEFT:

                    snake.direction = LEFT

                elif event.key == pygame.K_RIGHT:

                    snake.direction = RIGHT


        snake.update()

        if snake.get_head_position() == food.position:

            snake.length += 1

            food.randomize_position()


        surface.fill(WHITE)

        snake.render(surface)

        food.render(surface)

        screen.blit(surface, (0, 0))

        pygame.display.update()

        clock.tick(FPS)


if __name__ == "__main__":

    main()