added main menu

This commit is contained in:
Kristofers Solo 2022-04-17 14:18:14 +03:00
parent 787fa1c785
commit 3bb445cf47
5 changed files with 143 additions and 229 deletions

View File

@ -3,10 +3,6 @@ from globals import *
from random import randrange
def end_screen() -> None:
quit()
class Cube:
def __init__(self, position, color=PURPLE) -> None:
@ -34,9 +30,9 @@ class Cube:
class Snake:
def __init__(self, pos: tuple, color: tuple, name: str, player_number: int = 1) -> None:
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1) -> None:
self.color = color
self.head = Cube(pos, self.color)
self.head = Cube(position, self.color)
self.body = []
self.body.append(self.head)
self.turns = {}
@ -93,8 +89,10 @@ class Snake:
if index == len(self.body) - 1:
self.turns.pop(head_pos)
else:
from assets.scripts.menu import walls
if walls: # end game if goes into the wall
head.move(head.direction)
from snake import end_screen
if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen()
@ -158,4 +156,30 @@ class Snack:
WINDOW.blit(self.texture, snack_rect)
def randomize(self) -> None:
self.pos = (randrange(ROWS), randrange(COLUMNS))
self.pos = (randrange(ROWS), randrange(COLUMNS))
class Button():
def __init__(self, position, text, font_size, base_color, hover_color) -> None:
self.pos = position
self.font = set_font(font_size)
self.base_color = base_color
self.hover_color = hover_color
self.text = text
self.text_rect = self.font.render(self.text, 1, self.base_color).get_rect(center=(self.pos))
def update(self) -> None:
WINDOW.blit(self.text, self.text_rect)
def check_input(self, mouse_pos) -> bool:
if mouse_pos[0] in range(self.text_rect.left, self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom):
return True
return False
def change_color(self, mouse_pos) -> None:
if mouse_pos[0] in range(self.text_rect.left,
self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): # on hover
self.text = self.font.render(self.text, 1, self.hover_color)
else:
self.text = self.font.render(self.text, 1, self.base_color)

View File

@ -1,10 +1,13 @@
import pygame
from globals import *
from assets.scripts.score import read_score, sort
from assets.scripts.classes import Button
MID_WIDTH = WIDTH / 2
MID_HEIGHT = WINDOW_HEIGHT / 2
def main_menu() -> None:
text = set_font(20).render("QUIT", 1, GRAY)
def menu() -> None:
while True:
WINDOW.fill(BLACK)
title_label = set_font(50).render("Press any key to start...", 1, WHITE)
@ -19,3 +22,92 @@ def main_menu() -> None:
from snake import main
main()
pygame.display.update()
def main_menu() -> None:
global run
run = True
pygame.display.set_caption("Snake - Menu")
while True:
print(run)
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render("SNAKE GAME", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
play_button = Button((MID_WIDTH, MID_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
options_button = Button((MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 150), "QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, quit_button]
for button in buttons:
button.change_color(mouse_pos)
button.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if play_button.check_input(mouse_pos):
from snake import main
main()
if options_button.check_input(mouse_pos):
options()
if quit_button.check_input(mouse_pos):
quit()
pygame.display.update()
def options() -> None:
global FPS
global multiplayer
global walls
pygame.display.set_caption("Snake - Options")
while True:
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
options_text = set_font(100).render("OPTIONS", 1, WHITE)
options_rect = options_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(options_text, options_rect)
# change state names
# multiplayer
if multiplayer: multiplayer_state = "on"
else: multiplayer_state = "off"
# walls
if walls: walls_state = "on"
else: walls_state = "off"
# speed
if FPS == 5: speed_state = "Slow"
elif FPS == 10: speed_state = "Normal"
elif FPS == 15: speed_state = "Fast"
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100), f"SPEED - {speed_state}", 75, GRAY, WHITE)
multiplayer_button = Button((MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE)
walls_button = Button((MID_WIDTH, MID_HEIGHT + 100), f"WALLS - {walls_state}", 75, GRAY, WHITE)
back_button = Button((MID_WIDTH, MID_HEIGHT + 200), "BACK", 75, GRAY, WHITE)
buttons = [speed_button, multiplayer_button, walls_button, back_button]
for button in buttons:
button.change_color(mouse_pos)
button.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if speed_button.check_input(mouse_pos):
if FPS == 5: FPS = 10
elif FPS == 10: FPS = 15
elif FPS == 15: FPS = 5
if multiplayer_button.check_input(mouse_pos):
multiplayer = not multiplayer
if walls_button.check_input(mouse_pos):
walls = not walls
if back_button.check_input(mouse_pos):
main_menu()
pygame.display.update()

View File

@ -7,14 +7,13 @@ WIDTH, HEIGHT = ROWS * CELL_SIZE, COLUMNS * CELL_SIZE
WINDOW_HEIGHT = HEIGHT + 100
WINDOW = pygame.display.set_mode((WIDTH, WINDOW_HEIGHT))
pygame.font.init()
pygame.display.set_caption("Snake")
BASE_PATH = abspath(dirname(__file__))
FONT = join(BASE_PATH, "fonts", "roboto.ttf")
SPRITE_PATH = join(BASE_PATH, "assets", "sprites")
apple_texture = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE))
poison_texture = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE))
cobblestone_texture = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "cobblestone.jpeg")), (CELL_SIZE, CELL_SIZE))
FONT = join(BASE_PATH, "fonts", "roboto.ttf")
RED = (255, 0, 0)
WHITE = (242, 242, 242)
@ -27,6 +26,9 @@ BLUE = (85, 85, 255)
set_font = lambda size: pygame.font.Font(FONT, size) # sets font size
run = True
snakes = []
FPS = 10 # speed
multiplayer = False
walls = False

View File

@ -2,6 +2,7 @@
# Date - 16.04.2022
# Title - Snake
from glob import glob
import pygame
from random import randint
from os.path import abspath, dirname
@ -10,6 +11,7 @@ from globals import *
from assets.scripts.score import *
from assets.scripts.menu import main_menu
from assets.scripts.classes import *
from assets.scripts.menu import FPS, multiplayer, walls
BASE_PATH = abspath(dirname(__file__))
@ -37,12 +39,20 @@ def collision_check(snakes, snack) -> None:
snack.randomize()
def main() -> None:
def end_screen() -> None:
global run
for snake in snakes:
write_score(snake.name, len(snake.body), BASE_PATH)
run = False
def main() -> None:
global snakes
pygame.display.set_caption("Snake")
run = True
clock = pygame.time.Clock()
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), PURPLE, "test1")
snakes = [snake_one]
snakes.append(snake_one)
if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), BLUE, "test2", 2)
@ -90,9 +100,7 @@ def main() -> None:
for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
for snake in snakes:
write_score(snake.name, len(snake.body), BASE_PATH)
run = False
end_screen()
redraw_window()

View File

@ -1,212 +0,0 @@
import pygame,sys,random
from pygame.math import Vector2
class SNAKE:
def __init__(self):
self.body = [Vector2(5,10),Vector2(4,10),Vector2(3,10)]
self.direction = Vector2(0,0)
self.new_block = False
self.head_up = pygame.image.load('Graphics/head_up.png').convert_alpha()
self.head_down = pygame.image.load('Graphics/head_down.png').convert_alpha()
self.head_right = pygame.image.load('Graphics/head_right.png').convert_alpha()
self.head_left = pygame.image.load('Graphics/head_left.png').convert_alpha()
self.tail_up = pygame.image.load('Graphics/tail_up.png').convert_alpha()
self.tail_down = pygame.image.load('Graphics/tail_down.png').convert_alpha()
self.tail_right = pygame.image.load('Graphics/tail_right.png').convert_alpha()
self.tail_left = pygame.image.load('Graphics/tail_left.png').convert_alpha()
self.body_vertical = pygame.image.load('Graphics/body_vertical.png').convert_alpha()
self.body_horizontal = pygame.image.load('Graphics/body_horizontal.png').convert_alpha()
self.body_tr = pygame.image.load('Graphics/body_tr.png').convert_alpha()
self.body_tl = pygame.image.load('Graphics/body_tl.png').convert_alpha()
self.body_br = pygame.image.load('Graphics/body_br.png').convert_alpha()
self.body_bl = pygame.image.load('Graphics/body_bl.png').convert_alpha()
self.crunch_sound = pygame.mixer.Sound('Sound/crunch.wav')
def draw_snake(self):
self.update_head_graphics()
self.update_tail_graphics()
for index,block in enumerate(self.body):
x_pos = int(block.x * cell_size)
y_pos = int(block.y * cell_size)
block_rect = pygame.Rect(x_pos,y_pos,cell_size,cell_size)
if index == 0:
screen.blit(self.head,block_rect)
elif index == len(self.body) - 1:
screen.blit(self.tail,block_rect)
else:
previous_block = self.body[index + 1] - block
next_block = self.body[index - 1] - block
if previous_block.x == next_block.x:
screen.blit(self.body_vertical,block_rect)
elif previous_block.y == next_block.y:
screen.blit(self.body_horizontal,block_rect)
else:
if previous_block.x == -1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == -1:
screen.blit(self.body_tl,block_rect)
elif previous_block.x == -1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == -1:
screen.blit(self.body_bl,block_rect)
elif previous_block.x == 1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == 1:
screen.blit(self.body_tr,block_rect)
elif previous_block.x == 1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == 1:
screen.blit(self.body_br,block_rect)
def update_head_graphics(self):
head_relation = self.body[1] - self.body[0]
if head_relation == Vector2(1,0): self.head = self.head_left
elif head_relation == Vector2(-1,0): self.head = self.head_right
elif head_relation == Vector2(0,1): self.head = self.head_up
elif head_relation == Vector2(0,-1): self.head = self.head_down
def update_tail_graphics(self):
tail_relation = self.body[-2] - self.body[-1]
if tail_relation == Vector2(1,0): self.tail = self.tail_left
elif tail_relation == Vector2(-1,0): self.tail = self.tail_right
elif tail_relation == Vector2(0,1): self.tail = self.tail_up
elif tail_relation == Vector2(0,-1): self.tail = self.tail_down
def move_snake(self):
if self.new_block == True:
body_copy = self.body[:]
body_copy.insert(0,body_copy[0] + self.direction)
self.body = body_copy[:]
self.new_block = False
else:
body_copy = self.body[:-1]
body_copy.insert(0,body_copy[0] + self.direction)
self.body = body_copy[:]
def add_block(self):
self.new_block = True
def play_crunch_sound(self):
self.crunch_sound.play()
def reset(self):
self.body = [Vector2(5,10),Vector2(4,10),Vector2(3,10)]
self.direction = Vector2(0,0)
class FRUIT:
def __init__(self):
self.randomize()
def draw_fruit(self):
fruit_rect = pygame.Rect(int(self.pos.x * cell_size),int(self.pos.y * cell_size),cell_size,cell_size)
screen.blit(apple,fruit_rect)
#pygame.draw.rect(screen,(126,166,114),fruit_rect)
def randomize(self):
self.x = random.randint(0,cell_number - 1)
self.y = random.randint(0,cell_number - 1)
self.pos = Vector2(self.x,self.y)
class MAIN:
def __init__(self):
self.snake = SNAKE()
self.fruit = FRUIT()
def update(self):
self.snake.move_snake()
self.check_collision()
self.check_fail()
def draw_elements(self):
self.draw_grass()
self.fruit.draw_fruit()
self.snake.draw_snake()
self.draw_score()
def check_collision(self):
if self.fruit.pos == self.snake.body[0]:
self.fruit.randomize()
self.snake.add_block()
self.snake.play_crunch_sound()
for block in self.snake.body[1:]:
if block == self.fruit.pos:
self.fruit.randomize()
def check_fail(self):
if not 0 <= self.snake.body[0].x < cell_number or not 0 <= self.snake.body[0].y < cell_number:
self.game_over()
for block in self.snake.body[1:]:
if block == self.snake.body[0]:
self.game_over()
def game_over(self):
self.snake.reset()
def draw_grass(self):
grass_color = (167,209,61)
for row in range(cell_number):
if row % 2 == 0:
for col in range(cell_number):
if col % 2 == 0:
grass_rect = pygame.Rect(col * cell_size,row * cell_size,cell_size,cell_size)
pygame.draw.rect(screen,grass_color,grass_rect)
else:
for col in range(cell_number):
if col % 2 != 0:
grass_rect = pygame.Rect(col * cell_size,row * cell_size,cell_size,cell_size)
pygame.draw.rect(screen,grass_color,grass_rect)
def draw_score(self):
score_text = str(len(self.snake.body) - 3)
score_surface = game_font.render(score_text,True,(56,74,12))
score_x = int(cell_size * cell_number - 60)
score_y = int(cell_size * cell_number - 40)
score_rect = score_surface.get_rect(center = (score_x,score_y))
apple_rect = apple.get_rect(midright = (score_rect.left,score_rect.centery))
bg_rect = pygame.Rect(apple_rect.left,apple_rect.top,apple_rect.width + score_rect.width + 6,apple_rect.height)
pygame.draw.rect(screen,(167,209,61),bg_rect)
screen.blit(score_surface,score_rect)
screen.blit(apple,apple_rect)
pygame.draw.rect(screen,(56,74,12),bg_rect,2)
pygame.mixer.pre_init(44100,-16,2,512)
pygame.init()
cell_size = 40
cell_number = 20
screen = pygame.display.set_mode((cell_number * cell_size,cell_number * cell_size))
clock = pygame.time.Clock()
apple = pygame.image.load('Graphics/apple.png').convert_alpha()
game_font = pygame.font.Font('Font/PoetsenOne-Regular.ttf', 25)
SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE,150)
main_game = MAIN()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == SCREEN_UPDATE:
main_game.update()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if main_game.snake.direction.y != 1:
main_game.snake.direction = Vector2(0,-1)
if event.key == pygame.K_RIGHT:
if main_game.snake.direction.x != -1:
main_game.snake.direction = Vector2(1,0)
if event.key == pygame.K_DOWN:
if main_game.snake.direction.y != -1:
main_game.snake.direction = Vector2(0,1)
if event.key == pygame.K_LEFT:
if main_game.snake.direction.x != 1:
main_game.snake.direction = Vector2(-1,0)
screen.fill((175,215,70))
main_game.draw_elements()
pygame.display.update()
clock.tick(60)