Найти тему
Broud

Змейка на python.

Код игры "Змейка" на питоне:

import pygame

import random

pygame.init()

Создаем окно для игры

screen_width = 800

screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption('Змейка')

Создаем цвета, используемые в игре

black = (0, 0, 0)

white = (255, 255, 255)

red = (255, 0, 0)

green = (0, 255, 0)

dark_green = (0, 215, 0)

Создаем змейку

snake_pos = [100, 50]

snake_body = [[100, 50], [90, 50], [80, 50]]

direction = 'RIGHT'

Создаем еду для змейки

food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10]

food_spawn = True

Создаем основной цикл игры

clock = pygame.time.Clock()

game_over = False

while not game_over:

    # Обрабатываем события

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            game_over = True

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_RIGHT and direction != "LEFT":

                direction = 'RIGHT'

            elif event.key == pygame.K_LEFT and direction != "RIGHT":

                direction = 'LEFT'

            elif event.key == pygame.K_UP and direction != "DOWN":

                direction = 'UP'

            elif event.key == pygame.K_DOWN and direction != "UP":

                direction = 'DOWN'

    Создаем перемещение змейки

    if direction == 'RIGHT':

        snake_pos[0] += 10

    elif direction == 'LEFT':

        snake_pos[0] -= 10

    elif direction == 'UP':

        snake_pos[1] -= 10

    elif direction == 'DOWN':

        snake_pos[1] += 10

    snake_body.insert(0, list(snake_pos))

    Если змея съела еду, создаем новую

    if snake_pos == food_pos:

        food_spawn = False

    else:

        snake_body.pop()

    Создаем новую еду

    if not food_spawn:

        food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10]

    food_spawn = True

    Заливаем экран(любой цвет, но белый лучший. )

    screen.fill(white)

    Рисуем змейку и еду

    for pos in snake_body:

        if snake_body.index(pos) == 0:

            pygame.draw.rect(screen, dark_green, pygame.Rect(pos[0], pos[1], 10, 10))

        else:

            pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))

    pygame.draw.rect(screen, red, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    Проверяем столкновения с границами

    if snake_pos[0] < 0 or snake_pos[0] > screen_width - 10:

        game_over = True

    elif snake_pos[1] < 0 or snake_pos[1] > screen_height - 10:

        game_over = True

    Проверяем столкновения с телом змеи

    for block in snake_body[1:]:

        if snake_pos == block:

            game_over = True

    Обновляем экран

    pygame.display.update()

    Ограничиваем количество кадров в секунду

    clock.tick(15)

Завершаем работу Pygame

pygame.quit()

Готово надеюсь эта статья вас помогла :)

ЕЩЁ БОЛЬШЕ В ТГ - python kuds

python kuds

Наука
7 млн интересуются