BLOCKS GAME python(pygame,random)

 

import pygame

import random


# Initialize Pygame

pygame.init()


# Constants

WIDTH, HEIGHT = 800, 600

PLAYER_WIDTH, PLAYER_HEIGHT = 50, 50

PLAYER_SPEED = 5

OBJECT_WIDTH, OBJECT_HEIGHT = 30, 30

OBJECT_SPEED = 3

OBJECT_COLOR = (255, 0, 0)


# Colors

WHITE = (255, 255, 255)


# Create the screen

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

pygame.display.set_caption("Simple Game")


# Player

player = pygame.Rect(WIDTH // 2 - PLAYER_WIDTH // 2, HEIGHT - PLAYER_HEIGHT - 10, PLAYER_WIDTH, PLAYER_HEIGHT)


# Falling objects

objects = []


# Score

score = 0


def draw_player():

    pygame.draw.rect(screen, WHITE, player)


def draw_objects():

    for obj in objects:

        pygame.draw.rect(screen, OBJECT_COLOR, obj)


def move_objects():

    for obj in objects:

        obj.y += OBJECT_SPEED


def add_object():

    x = random.randint(0, WIDTH - OBJECT_WIDTH)

    y = 0

    obj = pygame.Rect(x, y, OBJECT_WIDTH, OBJECT_HEIGHT)

    objects.append(obj)


# Game loop

running = True

clock = pygame.time.Clock()


while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False


    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and player.x > 0:

        player.x -= PLAYER_SPEED

    if keys[pygame.K_RIGHT] and player.x < WIDTH - PLAYER_WIDTH:

        player.x += PLAYER_SPEED


    # Add falling objects

    if random.randint(1, 100) < 5:

        add_object()


    # Move and remove objects

    move_objects()

    objects = [obj for obj in objects if obj.y < HEIGHT]


    # Collision detection

    for obj in objects:

        if player.colliderect(obj):

            running = False

        elif obj.y >= HEIGHT - OBJECT_HEIGHT:

            # Player successfully avoided the object

            score += 1


    # Clear the screen

    screen.fill((0, 0, 0))


    # Draw the player and objects

    draw_player()

    draw_objects()


    # Display the score

    font = pygame.font.Font(None, 36)

    score_text = font.render(f"Score: {score}", True, WHITE)

    screen.blit(score_text, (10, 10))


    pygame.display.flip()

    clock.tick(60)


# Quit Pygame

pygame.quit()


# Display final score

print(f"Your final score: {score}")


Comments

Popular Posts