https://www.youtube.com/watch?v=x41O-TP-9BU&list=PLQAt0m1f9OHun6Q9uZPNryl5gXm1ng_kd&index=1
import pygame
import sys
import random
import time
FPS = 5
SIZE_BLOCK = 20
FRAME_COLOR = (0, 0, 100)
WHITE = (255,255,255)
BLUE = (100,100,255)
blue = (0,0,100)
red = (255,0,255)
COUNT_BLOCK = 20
MARGIN = 1
x=10
y=10
napr_x = 1
napr_y = 0
size = [450,450]
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Snake Game')
clock = pygame.time.Clock()
x_food = random.randint(0,19)
y_food = random.randint(0,19)
class SnakeBlock:
def __init__(self,x,y):
self.x=x
self.y=y
snake_blocks = [SnakeBlock(9,8),SnakeBlock(9,9),SnakeBlock(9,10)]
while True:
for i in pygame.event.get():
if i.type == pygame.QUIT:
pygame.quit()
exit()
elif i.type == pygame.KEYDOWN:
if i.key == pygame.K_LEFT:
napr_x = -1
napr_y = 0
elif i.key == pygame.K_RIGHT:
napr_x = 1
napr_y = 0
elif i.key == pygame.K_UP:
napr_y = -1
napr_x = 0
elif i.key == pygame.K_DOWN:
napr_y = 1
napr_x = 0
screen.fill(FRAME_COLOR)
# Создание поля игры
for row in range(COUNT_BLOCK):
for column in range(COUNT_BLOCK):
if (row+column)%2==0:
color = BLUE
else:
color = WHITE
pygame.draw.rect(screen,color,
(10+column*SIZE_BLOCK + MARGIN*(column+1),
20+row*SIZE_BLOCK + MARGIN*(row+1),
SIZE_BLOCK,SIZE_BLOCK))
# Создание змейки
for block in snake_blocks:
# Проверка столкновения со стенками
if block.x==COUNT_BLOCK or block.x==-1 or block.y==COUNT_BLOCK or block.y==-1:
exit()
snake = pygame.draw.rect(screen,blue,
(10+block.x*SIZE_BLOCK + MARGIN*(block.x+1),
20+block.y*SIZE_BLOCK + MARGIN*(block.y+1),
SIZE_BLOCK,SIZE_BLOCK))
head=snake_blocks[-1]
new_head = SnakeBlock(head.x+napr_x,head.y+napr_y)
snake_blocks.append(new_head)
snake_blocks.pop(0)
# Создание еды
food = pygame.draw.rect(screen,red,
(10+x_food*SIZE_BLOCK + MARGIN*(x_food+1),
20+y_food*SIZE_BLOCK + MARGIN*(y_food+1),
SIZE_BLOCK,SIZE_BLOCK))
# Проверка поглощения еды змейкой
if snake==food:
snake_blocks.append(new_head)
food=0
x_food = random.randint(0,19)
y_food = random.randint(0,19)
pygame.display.flip()
clock.tick(FPS)
Немає коментарів:
Дописати коментар