Skip to content

Instantly share code, notes, and snippets.

@kianurivzzz
Created December 23, 2023 14:43
Show Gist options
  • Save kianurivzzz/9056531ff6d1d80ff09a7f9ef5f3dde8 to your computer and use it in GitHub Desktop.
Save kianurivzzz/9056531ff6d1d80ff09a7f9ef5f3dde8 to your computer and use it in GitHub Desktop.
# part 1
import pygame
import sys
pygame.init()
window = pygame.display.set_mode((500,400)) #Задаём размер игрового поля.
pygame.display.update()
sys.exit()
# part 2
import sys
import pygame
pygame.init()
window = pygame.display.set_mode((500,400))
pygame.display.update()
pygame.display.set_caption('Змейка от EasyCode') #Добавляем название игры.
while True:
for event in pygame.event.get():
print(event) #Выводить в терминал все события
sys.exit()
# part 3
import sys
import pygame
pygame.init()
window = pygame.display.set_mode((500, 400))
pygame.display.update()
pygame.display.set_caption('Змейка от Easycode')
# Создаём переменную, которая поможет нам контролировать
# статус игры — завершена она или нет.
# Изначально присваиваем значение False, то есть игра продолжается.
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
sys.exit()
# part 4
import sys
import pygame
pygame.init()
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
x1 = 300 #Указываем начальное значение положения змейки по оси х.
y1 = 300 #Указываем начальное значение положения змейки по оси y
window = pygame.display.set_mode((500, 400))
pygame.display.set_caption('Змейка от Easycode')
# Создаём переменную, которая поможет нам контролировать
# статус игры — завершена она или нет.
# Изначально присваиваем значение False, то есть игра продолжается.
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.draw.rect(window, BLUE, [x1, y1, 10, 10])
pygame.display.update() # Переместим для обновления
sys.exit()
# part 5
import sys
import pygame
pygame.init()
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
x1 = 300 #Указываем начальное значение положения змейки по оси х.
y1 = 300 #Указываем начальное значение положения змейки по оси y
x1_change = 0 #Создаём переменную, которой в цикле while будут присваиваться значения изменения положения змейки по оси х.
y1_change = 0 #создаём переменную, которой в цикле while будут присваиваться значения изменения положения змейки по оси y.
window = pygame.display.set_mode((500, 400))
pygame.display.set_caption('Змейка от Easycode')
# Создаём переменную, которая поможет нам контролировать
# статус игры — завершена она или нет.
# Изначально присваиваем значение False, то есть игра продолжается.
game_over = False
clock = pygame.time.Clock()
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN: # Добавляем считывание направления движений с клавиатуры.
if event.key == pygame.K_LEFT:
x1_change = -10 #Указываем шаг изменения положения змейки в 10 пикселей.
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = 10
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -10
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = 10
x1_change = 0
x1 += x1_change #Записываем новое значение положения змейки по оси х.
y1 += y1_change #Записываем новое значение положения змейки по оси y.
pygame.draw.rect(window, BLUE, [x1, y1, 10, 10])
window.fill(WHITE)
pygame.display.update() # Переместим для обновления
clock.tick(30)
sys.exit()
# part 6
import sys
import time
import random
import pygame
pygame.init()
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
display_width = 800 #Зададим размер игрового поля через две переменные.
display_height = 600
x1 = display_width / 2 #Указываем начальное значение положения змейки по оси х.
y1 = display_height / 2 #Указываем начальное значение положения змейки по оси y
x1_change = 0 #Создаём переменную, которой в цикле while будут присваиваться значения изменения положения змейки по оси х.
y1_change = 0 #создаём переменную, которой в цикле while будут присваиваться значения изменения положения змейки по оси y.
font_style = pygame.font.SysFont(None, 50)
window = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Змейка от Easycode')
# Создаём переменную, которая поможет нам контролировать
# статус игры — завершена она или нет.
# Изначально присваиваем значение False, то есть игра продолжается.
game_over = False
clock = pygame.time.Clock()
snake_speed = 15 #Ограничим скорость движения змейки.
snake_block = 10
def get_message(msg, color):
message = font_style.render(msg, True, color)
window.blit(message, [display_width / 6, display_height / 3])
def game_loop():
game_over = False
game_close = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(WHITE)
get_message('Вы проиграли! Нажмите Q для выхода или C для повторной игры', RED)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
window.fill(WHITE)
pygame.draw.rect(window, GREEN, [foodx, foody, snake_block, snake_block])
pygame.display.update()
pygame.draw.rect(window, BLUE, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(window, BLACK, [x1, y1, snake_block, snake_block])
clock.tick(snake_speed)
time.sleep(2)
sys.exit()
game_loop()
# part 7
import time
import random
import sys
import pygame
pygame.init()
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
display_width = 800
display_height = 600
snake_block = 10
snake_speed = 15
window = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Змейка от EasyCode')
clock = pygame.time.Clock()
font_style = pygame.font.SysFont('bahnschrift', 25) # Укажем название шрифта и его размер для системных сообщений, например, при завершении игры.
score_font = pygame.font.SysFont('comicsansms', 35) # Укажем шрифт и его размер для отображения счёта.
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(window, BLACK, [x[0], x[1], snake_block, snake_block])
def get_message(msg, color):
message = font_style.render(msg, True, color)
window.blit(message, [display_width / 6, display_height / 3])
def game_loop():
game_over = False
game_close = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = [] #Создаём список, в котором будем хранить показатель текущей длины змейки.
length_of_snake = 1
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(BLUE)
get_message('Вы проиграли! Нажмите Q для выхода или C для повторной игры', RED)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
window.fill(BLUE)
pygame.draw.rect(window, GREEN, [foodx, foody, snake_block, snake_block])
snake_head = [] # Создаём список, в котором будет храниться показатель длины змейки при движениях.
snake_head.append(x1) # Добавляем значения в список при изменении по оси х.
snake_head.append(y1) # Добавляем значения в список при изменении по оси y.
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
# Удаляем первый элемент в списке
# длины змейки, чтобы она не увеличивалась сама по себе при движениях.
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
our_snake(snake_block, snake_list)
pygame.display.update()
# Указываем, что в случаях,
# если координаты головы змейки совпадают с координатами еды, еда появляется
# в новом месте, а длина змейки увеличивается на одну клетку.
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
clock.tick(snake_speed)
sys.exit()
game_loop()
# part 8
import time
import random
import sys
import pygame
pygame.init()
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
display_width = 800
display_height = 600
snake_block = 10
snake_speed = 15
window = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Змейка от EasyCode')
clock = pygame.time.Clock()
font_style = pygame.font.SysFont('bahnschrift', 25)
score_font = pygame.font.SysFont('comicsansms', 35)
def get_score(score):
value = score_font.render('Ваш счёт: ' + str(score), True, YELLOW)
window.blit(value, [0, 0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(window, BLACK, [x[0], x[1], snake_block, snake_block])
def get_message(msg, color):
message = font_style.render(msg, True, color)
window.blit(message, [display_width / 6, display_height / 3])
def game_loop():
game_over = False
game_close = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(BLUE)
get_message('Вы проиграли! Нажмите Q для выхода или C для повторной игры', RED)
get_score(length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
window.fill(BLUE)
pygame.draw.rect(window, GREEN, [foodx, foody, snake_block, snake_block])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
our_snake(snake_block, snake_list)
get_score(length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
clock.tick(snake_speed)
sys.exit()
game_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment