Final changes and commit

This commit is contained in:
Kristofers Solo
2022-08-02 20:34:11 +03:00
parent db328c4350
commit 253802ac88
38 changed files with 1917 additions and 1708 deletions

View File

@@ -5,182 +5,189 @@ from random import randrange
class Cube:
def __init__(self, position, color=DARK_PURPLE) -> None:
self.pos = position
self.direction = (1, 0)
self.color = color
def __init__(self, position, color=DARK_PURPLE) -> None:
self.pos = position
self.direction = (1, 0)
self.color = color
def move(self, direction: tuple) -> None:
self.direction = direction
self.pos = (self.pos[0] + self.direction[0], self.pos[1] + self.direction[1])
def move(self, direction: tuple) -> None:
self.direction = direction
self.pos = (self.pos[0] + self.direction[0],
self.pos[1] + self.direction[1])
def draw(self, eyes=False) -> None:
distance = WIDTH // ROWS
i, j = self.pos
def draw(self, eyes=False) -> None:
distance = WIDTH // ROWS
i, j = self.pos
pygame.draw.rect(WINDOW, self.color, (i * distance + 1, j * distance + 1, distance - 2, distance - 2))
if eyes:
center = distance // 2
radius = 3
circle_middle = (i * distance + center - radius, j * distance + 8)
circle_middle_2 = (i * distance + distance - radius * 2, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius)
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
pygame.draw.rect(WINDOW, self.color, (i * distance + 1,
j * distance + 1, distance - 2, distance - 2))
if eyes:
center = distance // 2
radius = 3
circle_middle = (i * distance + center - radius, j * distance + 8)
circle_middle_2 = (i * distance + distance -
radius * 2, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius)
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
class Snake:
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None:
self.color = color
self.head = Cube(position, self.color)
self.body = []
self.body.append(self.head)
self.turns = {}
self.direction = (1, 0)
self.number = player_number
self.name = name
self.multiplayer = multiplayer
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None:
self.color = color
self.head = Cube(position, self.color)
self.body = []
self.body.append(self.head)
self.turns = {}
self.direction = (1, 0)
self.number = player_number
self.name = name
self.multiplayer = multiplayer
def move(self) -> None:
keys = pygame.key.get_pressed()
if self.multiplayer:
num_1, num_2 = 1, 2
else:
num_1, num_2 = 1, 1
def move(self) -> None:
keys = pygame.key.get_pressed()
if self.multiplayer:
num_1, num_2 = 1, 2
else:
num_1, num_2 = 1, 1
if self.number == num_1:
if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if self.number == num_1:
if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_RIGHT] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
# turn right
if keys[pygame.K_RIGHT] and self.direction != (-1, 0):
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_UP] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_UP] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if self.number == num_2:
if keys[pygame.K_a] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if self.number == num_2:
if keys[pygame.K_a] and self.direction != (1, 0): # turn left
self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_d] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_d] and self.direction != (-1, 0): # turn right
self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_w] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_w] and self.direction != (0, 1): # turn up
self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_s] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_s] and self.direction != (0, -1): # turn down
self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction
for index, head in enumerate(self.body):
head_pos = head.pos[:]
if head_pos in self.turns:
turn = self.turns[head_pos]
head.move((turn[0], turn[1]))
if index == len(self.body) - 1:
self.turns.pop(head_pos)
else:
from globals import walls
from snake import end_screen
if walls: # end game if goes into the wall
head.move(head.direction)
if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen()
for index, head in enumerate(self.body):
head_pos = head.pos[:]
if head_pos in self.turns:
turn = self.turns[head_pos]
head.move((turn[0], turn[1]))
if index == len(self.body) - 1:
self.turns.pop(head_pos)
else:
from globals import walls
from snake import end_screen
if walls: # end game if goes into the wall
head.move(head.direction)
if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen()
if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left
end_screen()
if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left
end_screen()
if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top
end_screen()
if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top
end_screen()
if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom
end_screen()
if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom
end_screen()
else: # move player to other screen size
if head.direction[0] == -1 and head.pos[0] <= 0: # left to right
head.pos = (ROWS - 1, head.pos[1])
else: # move player to other screen size
if head.direction[0] == -1 and head.pos[0] <= 0: # left to right
head.pos = (ROWS - 1, head.pos[1])
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
head.pos = (0, head.pos[1])
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
head.pos = (0, head.pos[1])
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1: # bottom to top
head.pos = (head.pos[0], 0)
# bottom to top
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1:
head.pos = (head.pos[0], 0)
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
head.pos = (head.pos[0], COLUMNS - 1)
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
head.pos = (head.pos[0], COLUMNS - 1)
else:
head.move(head.direction)
else:
head.move(head.direction)
def add_cube(self) -> None:
tail = self.body[-1]
if tail.direction == (1, 0):
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color))
elif tail.direction == (-1, 0):
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color))
elif tail.direction == (0, 1):
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color))
elif tail.direction == (0, -1):
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color))
def add_cube(self) -> None:
tail = self.body[-1]
if tail.direction == (1, 0):
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color))
elif tail.direction == (-1, 0):
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color))
elif tail.direction == (0, 1):
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color))
elif tail.direction == (0, -1):
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color))
self.body[-1].direction = tail.direction
self.body[-1].direction = tail.direction
def remove_cube(self) -> None:
self.body.pop(-1)
def remove_cube(self) -> None:
self.body.pop(-1)
def draw(self) -> None:
for index, head in enumerate(self.body):
if index == 0:
head.draw(eyes=True)
else:
head.draw()
def draw(self) -> None:
for index, head in enumerate(self.body):
if index == 0:
head.draw(eyes=True)
else:
head.draw()
class Snack:
def __init__(self, texture) -> None:
self.texture = texture
self.randomize()
def __init__(self, texture) -> None:
self.texture = texture
self.randomize()
def draw_snack(self) -> None:
snack_rect = pygame.Rect(self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
WINDOW.blit(self.texture, snack_rect)
def draw_snack(self) -> None:
snack_rect = pygame.Rect(
self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
WINDOW.blit(self.texture, snack_rect)
def randomize(self) -> None:
self.pos = (randrange(ROWS), randrange(COLUMNS))
def randomize(self) -> None:
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 __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 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 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)
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

@@ -11,178 +11,225 @@ color_index = [0, 1]
def main_menu() -> None:
pygame.display.set_caption("Snake - Menu")
while True:
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)
pygame.display.set_caption("Snake - Menu")
while True:
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)
score_button = Button((MID_WIDTH, MID_HEIGHT + 150), "SCORE", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250), "QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button]
play_button = Button((MID_WIDTH, MID_HEIGHT - 50),
"PLAY", 75, GRAY, WHITE)
options_button = Button(
(MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
score_button = Button((MID_WIDTH, MID_HEIGHT + 150),
"SCORE", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250),
"QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button]
on_hover(buttons)
on_hover(buttons)
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if play_button.check_input(mouse_pos): user_input(0)
if options_button.check_input(mouse_pos): options()
if score_button.check_input(mouse_pos): scoreboard()
if quit_button.check_input(mouse_pos): quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if play_button.check_input(mouse_pos):
user_input(0)
if options_button.check_input(mouse_pos):
options()
if score_button.check_input(mouse_pos):
scoreboard()
if quit_button.check_input(mouse_pos):
quit()
pygame.display.update()
pygame.display.update()
def user_input(player: int) -> None:
from snake import main
global user_name
global color_index
pygame.display.set_caption("Snake")
select_active = True
outline_color = WHITE
name_rect_w = 140
while True:
from globals import multiplayer
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
from snake import main
global user_name
global color_index
pygame.display.set_caption("Snake")
select_active = True
outline_color = WHITE
name_rect_w = 140
while True:
from globals import multiplayer
WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect)
back_button = Button((130, WINDOW_HEIGHT - 50), "BACK", 75, GRAY, WHITE)
if multiplayer and player == 0:
next_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
buttons = [back_button, next_button]
else:
play_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
buttons = [back_button, play_button]
back_button = Button((130, WINDOW_HEIGHT - 50),
"BACK", 75, GRAY, WHITE)
if multiplayer and player == 0:
next_button = Button(
(WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
buttons = [back_button, next_button]
else:
play_button = Button(
(WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
buttons = [back_button, play_button]
on_hover(buttons)
on_hover(buttons)
name_rect = pygame.Rect(MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
user_text = set_font(20).render(user_name[player], 1, WHITE)
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
name_rect_w = max(140, user_text.get_width() + 10)
name_rect = pygame.Rect(
MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
user_text = set_font(20).render(user_name[player], 1, WHITE)
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
name_rect_w = max(140, user_text.get_width() + 10)
color = COLORS[color_index[player]]
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
pygame.draw.rect(WINDOW, color, color_rect)
color = COLORS[color_index[player]]
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
pygame.draw.rect(WINDOW, color, color_rect)
if select_active: outline_color = WHITE
else: outline_color = DARK_GRAY
if select_active:
outline_color = WHITE
else:
outline_color = DARK_GRAY
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if name_rect.collidepoint(event.pos): select_active = True
else: select_active = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if name_rect.collidepoint(event.pos):
select_active = True
else:
select_active = False
if back_button.check_input(mouse_pos): main_menu()
if multiplayer and player == 0:
if next_button.check_input(mouse_pos): user_input(1)
else:
if play_button.check_input(mouse_pos): main()
if color_rect.collidepoint(event.pos):
color_index[player] += 1
if color_index[player] == len(COLORS) - 1:
color_index[player] = 0
if back_button.check_input(mouse_pos):
main_menu()
if multiplayer and player == 0:
if next_button.check_input(mouse_pos):
user_input(1)
else:
if play_button.check_input(mouse_pos):
main()
if color_rect.collidepoint(event.pos):
color_index[player] += 1
if color_index[player] == len(COLORS) - 1:
color_index[player] = 0
if event.button == 3: # clear user name on mouse right click
if name_rect.collidepoint(event.pos): user_name[player] = ""
if event.button == 3: # clear user name on mouse right click
if name_rect.collidepoint(event.pos):
user_name[player] = ""
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if select_active:
if event.key == pygame.K_BACKSPACE: user_name[player] = user_name[player][:-1]
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: continue
else: user_name[player] += event.unicode
if select_active:
if event.key == pygame.K_BACKSPACE:
user_name[player] = user_name[player][:-1]
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
continue
else:
user_name[player] += event.unicode
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
if multiplayer and player == 0: user_input(1)
else: main()
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
if multiplayer and player == 0:
user_input(1)
else:
main()
pygame.display.update()
pygame.display.update()
def options() -> None:
pygame.display.set_caption("Snake - Options")
while True:
from globals import fps, multiplayer, walls
mouse_pos = pygame.mouse.get_pos()
pygame.display.set_caption("Snake - Options")
while True:
from globals import fps, multiplayer, walls
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)
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"
# change state names
# multiplayer
if multiplayer:
multiplayer_state = "on"
else:
multiplayer_state = "off"
# walls
if walls:
walls_state = "on"
else:
walls_state = "off"
speed_state = {5: "Slow", 10: "Normal", 15: "Fast"}
speed_state = {5: "Slow", 10: "Normal", 15: "Fast"}
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100), f"SPEED - {speed_state[fps]}", 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]
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100),
f"SPEED - {speed_state[fps]}", 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]
on_hover(buttons)
on_hover(buttons)
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if speed_button.check_input(mouse_pos): change_speed()
if multiplayer_button.check_input(mouse_pos): switch_multiplayer()
if walls_button.check_input(mouse_pos): switch_walls()
if back_button.check_input(mouse_pos): main_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if speed_button.check_input(mouse_pos):
change_speed()
if multiplayer_button.check_input(mouse_pos):
switch_multiplayer()
if walls_button.check_input(mouse_pos):
switch_walls()
if back_button.check_input(mouse_pos):
main_menu()
pygame.display.update()
pygame.display.update()
def scoreboard() -> None:
while True:
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
top_text = set_font(100).render("TOP 10", 1, WHITE)
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
WINDOW.blit(top_text, top_rect)
back_button = Button((MID_WIDTH, MID_HEIGHT + 250), "BACK", 75, GRAY, WHITE)
on_hover([back_button])
while True:
mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK)
top_text = set_font(100).render("TOP 10", 1, WHITE)
top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
WINDOW.blit(top_text, top_rect)
back_button = Button((MID_WIDTH, MID_HEIGHT + 250),
"BACK", 75, GRAY, WHITE)
on_hover([back_button])
for event in pygame.event.get():
if event.type == pygame.QUIT: quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if back_button.check_input(mouse_pos): main_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if back_button.check_input(mouse_pos):
main_menu()
csv_file = read_score(BASE_PATH)
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
for j, text in enumerate(line):
score_text = set_font(30).render(text, 1, WHITE)
score_rect = score_text.get_rect(center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
WINDOW.blit(score_text, score_rect)
csv_file = read_score(BASE_PATH)
for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
for j, text in enumerate(line):
score_text = set_font(30).render(text, 1, WHITE)
score_rect = score_text.get_rect(
center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
WINDOW.blit(score_text, score_rect)
pygame.display.update()
pygame.display.update()
def on_hover(buttons: list) -> None:
for button in buttons:
button.change_color(pygame.mouse.get_pos())
button.update()
for button in buttons:
button.change_color(pygame.mouse.get_pos())
button.update()

View File

@@ -5,33 +5,34 @@ fields = ["Name", "Score"]
def write_score(name: str, score: int, base_path: str) -> None:
create_header = False
path = join(base_path, "score.csv")
if not exists(path):
create_header = True
with open(path, 'a', encoding='UTF-8', newline='') as file:
write = csv.writer(file)
if create_header:
write.writerow(fields)
write.writerows([[name, score]])
create_header = False
path = join(base_path, "score.csv")
if not exists(path):
create_header = True
with open(path, 'a', encoding='UTF-8', newline='') as file:
write = csv.writer(file)
if create_header:
write.writerow(fields)
write.writerows([[name, score]])
def read_score(path: str):
lines = []
path = join(path, "score.csv")
try:
with open(path, 'r', encoding='UTF-8') as file:
for line in csv.reader(file):
lines.append(line)
return lines
except FileNotFoundError:
return [fields]
lines = []
path = join(path, "score.csv")
try:
with open(path, 'r', encoding='UTF-8') as file:
for line in csv.reader(file):
lines.append(line)
return lines
except FileNotFoundError:
return [fields]
def sort(data, reverse: bool):
if reverse == None: reverse = False
header = data[0]
data.remove(header) # remove header
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
data.insert(0, header) # add header
return data
if reverse == None:
reverse = False
header = data[0]
data.remove(header) # remove header
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
data.insert(0, header) # add header
return data

View File

@@ -1,5 +1,5 @@
import pygame
from os.path import join, abspath, dirname
import pygame
CELL_SIZE = 30
ROWS, COLUMNS = 30, 20
@@ -11,9 +11,12 @@ pygame.font.init()
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))
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))
BLACK = (0, 0, 0)
DARK_BLUE = (0, 0, 170)
@@ -32,9 +35,12 @@ LIGHT_PURPLE = (255, 85, 255)
YELLOW = (255, 255, 85)
WHITE = (242, 242, 242)
COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW]
COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE,
GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW]
def set_font(size): return pygame.font.Font(FONT, size) # sets font size
set_font = lambda size: pygame.font.Font(FONT, size) # sets font size
fps = 10 # speed
multiplayer = False
@@ -42,17 +48,20 @@ walls = False
def change_speed() -> None:
global fps
if fps == 5: fps = 10
elif fps == 10: fps = 15
elif fps == 15: fps = 5
global fps
if fps == 5:
fps = 10
elif fps == 10:
fps = 15
elif fps == 15:
fps = 5
def switch_multiplayer() -> None:
global multiplayer
multiplayer = not multiplayer
global multiplayer
multiplayer = not multiplayer
def switch_walls() -> None:
global walls
walls = not walls
global walls
walls = not walls

159
pygame/snake/source/snake.py Executable file → Normal file
View File

@@ -17,104 +17,109 @@ snakes = []
def draw_grid() -> None:
x, y = 0, 0
for _ in range(ROWS):
x += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT))
for _ in range(COLUMNS):
y += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y))
x, y = 0, 0
for _ in range(ROWS):
x += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT))
for _ in range(COLUMNS):
y += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y))
def draw_score(snakes) -> None:
for index, snake in enumerate(snakes):
score_label = set_font(40).render(f"Score {len(snake.body) - 1}", 1, snake.color)
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)), (WINDOW_HEIGHT - score_label.get_height())))
for index, snake in enumerate(snakes):
score_label = set_font(40).render(
f"Score {len(snake.body) - 1}", 1, snake.color)
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)),
(WINDOW_HEIGHT - score_label.get_height())))
def collision_check(snakes, snack) -> None:
for snake in snakes:
for block in snake.body:
if block.pos == snack.pos:
snack.randomize()
for snake in snakes:
for block in snake.body:
if block.pos == snack.pos:
snack.randomize()
def end_screen() -> None:
for snake in snakes:
if len(snake.body) > 1:
write_score(snake.name, len(snake.body) - 1, BASE_PATH)
main_menu()
for snake in snakes:
if len(snake.body) > 1:
write_score(snake.name, len(snake.body) - 1, BASE_PATH)
main_menu()
def main() -> None:
snakes.clear()
from globals import fps, multiplayer, walls
pygame.display.set_caption("Snake")
snakes.clear()
from globals import fps, multiplayer, walls
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
from assets.scripts.menu import user_name, color_index
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[0]], user_name[0], 1, multiplayer)
snakes.append(snake_one)
clock = pygame.time.Clock()
from assets.scripts.menu import user_name, color_index
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
COLORS[color_index[0]], user_name[0], 1, multiplayer)
snakes.append(snake_one)
if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[1]], user_name[1], 2, multiplayer)
snakes.append(snake_two)
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
COLORS[color_index[1]], user_name[1], 2, multiplayer)
snakes.append(snake_two)
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
def redraw_window() -> None:
WINDOW.fill(BLACK)
draw_grid()
draw_score(snakes)
for snake in snakes:
snake.draw()
apple.draw_snack()
poison.draw_snack()
if walls:
for i in range(ROWS):
COBBLE_RECT = pygame.Rect(i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
pygame.display.update()
def redraw_window() -> None:
WINDOW.fill(BLACK)
draw_grid()
draw_score(snakes)
for snake in snakes:
snake.draw()
apple.draw_snack()
poison.draw_snack()
if walls:
for i in range(ROWS):
COBBLE_RECT = pygame.Rect(
i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
pygame.display.update()
while True:
clock.tick(fps)
pygame.time.delay(0)
while True:
clock.tick(fps)
pygame.time.delay(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
end_screen()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
end_screen()
for snake in snakes:
snake.move()
if snake.body[0].pos == apple.pos:
snake.add_cube()
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
for snake in snakes:
snake.move()
if snake.body[0].pos == apple.pos:
snake.add_cube()
apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple)
if snake.body[0].pos == poison.pos:
if len(snake.body) > 1:
snake.remove_cube()
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
if snake.body[0].pos == poison.pos:
if len(snake.body) > 1:
snake.remove_cube()
poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
end_screen()
if multiplayer:
for i in snakes[0].body:
if i.pos == snakes[1].head.pos:
end_screen()
for i in snakes[1].body:
if i.pos == snakes[0].head.pos:
end_screen()
for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
end_screen()
if multiplayer:
for i in snakes[0].body:
if i.pos == snakes[1].head.pos:
end_screen()
for i in snakes[1].body:
if i.pos == snakes[0].head.pos:
end_screen()
redraw_window()
redraw_window()
if __name__ == '__main__':
main_menu()
main_menu()

View File

@@ -20,17 +20,23 @@ FONT = join(BASE_PATH, "fonts", "space_invaders.ttf")
# load sprites
SPACESHIP = pygame.image.load(join(SPRITE_PATH, "playership.png")) # player
PLAYER_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile
PLAYER_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile
# enemies
ENEMY_1 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
ENEMY_2 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
ENEMY_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
ENEMY_1 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
ENEMY_2 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
ENEMY_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
pygame.display.set_icon(ENEMY_3)
# background
BACKGROUND = pygame.transform.scale(pygame.image.load(join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT))
BACKGROUND = pygame.transform.scale(pygame.image.load(
join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT))
# colors (R, G, B)
BLUE = (16, 16, 69)
@@ -40,259 +46,267 @@ RED = (188, 2, 5)
class Missile:
def __init__(self, x: int, y: int, img) -> None:
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def __init__(self, x: int, y: int, img) -> None:
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def draw(self, window) -> None:
window.blit(self.img, (self.x, self.y))
def draw(self, window) -> None:
window.blit(self.img, (self.x, self.y))
def move(self, vel: int) -> None:
self.y += vel
def move(self, vel: int) -> None:
self.y += vel
def off_screen(self, height: int) -> bool:
return not (self.y <= height and self.y >= 0)
def off_screen(self, height: int) -> bool:
return not (self.y <= height and self.y >= 0)
def collision(self, obj) -> bool:
return collide(self, obj)
def collision(self, obj) -> bool:
return collide(self, obj)
class Ship:
COOLDOWN = 30 # cooldown before shooting next missile
COOLDOWN = 30 # cooldown before shooting next missile
def __init__(self, x: int, y: int, lives: int = 3) -> None:
self.x = x
self.y = y
self.lives = lives
self.ship_img = None
self.missile_img = None
self.missiles = []
self.cooldown_counter = 0
def __init__(self, x: int, y: int, lives: int = 3) -> None:
self.x = x
self.y = y
self.lives = lives
self.ship_img = None
self.missile_img = None
self.missiles = []
self.cooldown_counter = 0
def draw(self, window) -> None:
window.blit(self.ship_img, (self.x, self.y))
for missile in self.missiles:
missile.draw(WINDOW)
def draw(self, window) -> None:
window.blit(self.ship_img, (self.x, self.y))
for missile in self.missiles:
missile.draw(WINDOW)
def move_missiles(self, vel: int, obj) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
elif missile.collision(obj):
obj.lives -= 1
self.missiles.remove(missile)
def move_missiles(self, vel: int, obj) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
elif missile.collision(obj):
obj.lives -= 1
self.missiles.remove(missile)
def cooldown(self) -> None:
if self.cooldown_counter >= self.COOLDOWN:
self.cooldown_counter = 0
elif self.cooldown_counter > 0:
self.cooldown_counter += 1
def cooldown(self) -> None:
if self.cooldown_counter >= self.COOLDOWN:
self.cooldown_counter = 0
elif self.cooldown_counter > 0:
self.cooldown_counter += 1
def shoot(self) -> None:
if self.cooldown_counter == 0:
missile = Missile(self.x + self.get_width() / 2 - 5 / 2, self.y, self.missile_img) # missile spawn with offset
self.missiles.append(missile)
self.cooldown_counter = 1
def shoot(self) -> None:
if self.cooldown_counter == 0:
missile = Missile(self.x + self.get_width() / 2 - 5 / 2,
self.y, self.missile_img) # missile spawn with offset
self.missiles.append(missile)
self.cooldown_counter = 1
def get_width(self) -> int:
return self.ship_img.get_width()
def get_width(self) -> int:
return self.ship_img.get_width()
def get_height(self) -> int:
return self.ship_img.get_height()
def get_height(self) -> int:
return self.ship_img.get_height()
class Player(Ship):
def __init__(self, x: int, y: int, lives: int = 3) -> None:
super().__init__(x, y, lives)
self.ship_img = SPACESHIP
self.missile_img = PLAYER_MISSILE
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_lives = lives
self.score = 0
def __init__(self, x: int, y: int, lives: int = 3) -> None:
super().__init__(x, y, lives)
self.ship_img = SPACESHIP
self.missile_img = PLAYER_MISSILE
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_lives = lives
self.score = 0
def move_missiles(self, vel: int, objs: list) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
self.score -= 10
else:
for obj in objs:
if missile.collision(obj):
objs.remove(obj)
def move_missiles(self, vel: int, objs: list) -> None:
self.cooldown()
for missile in self.missiles:
missile.move(vel)
if missile.off_screen(HEIGHT):
self.missiles.remove(missile)
self.score -= 10
else:
for obj in objs:
if missile.collision(obj):
objs.remove(obj)
# different scores for different colored enemies
if obj.color == "lime":
self.score += 10
elif obj.color == "cyan":
self.score += 20
elif obj.color == "magenta":
self.score += 30
if missile in self.missiles:
self.missiles.remove(missile)
# different scores for different colored enemies
if obj.color == "lime":
self.score += 10
elif obj.color == "cyan":
self.score += 20
elif obj.color == "magenta":
self.score += 30
if missile in self.missiles:
self.missiles.remove(missile)
class Enemy(Ship):
COLOR_MAP = {
"magenta": ENEMY_1,
"cyan": ENEMY_2,
"lime": ENEMY_3,
}
COLOR_MAP = {
"magenta": ENEMY_1,
"cyan": ENEMY_2,
"lime": ENEMY_3,
}
def __init__(self, x: int, y: int, color: str) -> None:
super().__init__(x, y)
self.missile_img = ENEMY_MISSILE
self.ship_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
self.color = color
def __init__(self, x: int, y: int, color: str) -> None:
super().__init__(x, y)
self.missile_img = ENEMY_MISSILE
self.ship_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
self.color = color
def move(self, vel_x: int, vel_y: int = 0) -> None:
self.x += vel_x
self.y += vel_y
def move(self, vel_x: int, vel_y: int = 0) -> None:
self.x += vel_x
self.y += vel_y
def main() -> None:
FPS = 60
run = True
lost = False
lost_count = 0
level = 0
FPS = 60
run = True
lost = False
lost_count = 0
level = 0
enemies = []
player_vel = 7
player_missile_vel = 15
enemy_x_vel = 2
enemy_y_vel = 2
vel_x = enemy_x_vel
enemy_missile_vel = 6
last_enemy_shot = 0
enemies = []
player_vel = 7
player_missile_vel = 15
enemy_x_vel = 2
enemy_y_vel = 2
vel_x = enemy_x_vel
enemy_missile_vel = 6
last_enemy_shot = 0
player = Player(WIDTH / 2, 650)
player = Player(WIDTH / 2, 650)
clock = pygame.time.Clock()
clock = pygame.time.Clock()
def redraw_window() -> None:
WINDOW.blit(BACKGROUND, (0, 0))
# draw text
lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE)
score_label = set_font(40).render(f"Score {player.score}", 1, WHITE)
level_label = set_font(40).render(f"Level: {level}", 1, WHITE)
WINDOW.blit(lives_label, (10, 10))
WINDOW.blit(score_label, (10, lives_label.get_height() + 10))
WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
def redraw_window() -> None:
WINDOW.blit(BACKGROUND, (0, 0))
# draw text
lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE)
score_label = set_font(40).render(f"Score {player.score}", 1, WHITE)
level_label = set_font(40).render(f"Level: {level}", 1, WHITE)
WINDOW.blit(lives_label, (10, 10))
WINDOW.blit(score_label, (10, lives_label.get_height() + 10))
WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
for enemy in enemies:
enemy.draw(WINDOW)
for enemy in enemies:
enemy.draw(WINDOW)
player.draw(WINDOW)
player.draw(WINDOW)
if lost:
lost_label = set_font(60).render("You lost!", 1, RED)
WINDOW.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 350))
if lost:
lost_label = set_font(60).render("You lost!", 1, RED)
WINDOW.blit(lost_label, (WIDTH / 2 -
lost_label.get_width() / 2, 350))
pygame.display.update()
pygame.display.update()
while run:
clock.tick(FPS)
redraw_window()
while run:
clock.tick(FPS)
redraw_window()
if player.lives <= 0:
lost = True
lost_count += 1
if player.lives <= 0:
lost = True
lost_count += 1
# stop game
if lost:
if lost_count > FPS * 3: # wait for 3 sec
run = False
else:
continue
# stop game
if lost:
if lost_count > FPS * 3: # wait for 3 sec
run = False
else:
continue
# spawn enemies
if len(enemies) == 0:
level += 1
margin = 75
for x in range(margin, WIDTH - margin, margin):
for y in range(margin, int(HEIGHT / 2), margin):
if y == margin: # top row
color = "magenta"
elif y == 2 * margin: # rows 2-3
color = "cyan"
elif y == 4 * margin: # rows 4-5
color = "lime"
enemy = Enemy(x, y, color)
enemies.append(enemy)
# spawn enemies
if len(enemies) == 0:
level += 1
margin = 75
for x in range(margin, WIDTH - margin, margin):
for y in range(margin, int(HEIGHT / 2), margin):
if y == margin: # top row
color = "magenta"
elif y == 2 * margin: # rows 2-3
color = "cyan"
elif y == 4 * margin: # rows 4-5
color = "lime"
enemy = Enemy(x, y, color)
enemies.append(enemy)
for event in pygame.event.get():
# quit game
if event.type == pygame.QUIT:
quit()
for event in pygame.event.get():
# quit game
if event.type == pygame.QUIT:
quit()
keys = pygame.key.get_pressed()
keys = pygame.key.get_pressed()
# move left
if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0):
player.x -= player_vel
# move right
if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH):
player.x += player_vel
# shoot
if keys[pygame.K_SPACE]:
player.shoot()
# move left
if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0):
player.x -= player_vel
# move right
if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH):
player.x += player_vel
# shoot
if keys[pygame.K_SPACE]:
player.shoot()
# enemies action
for enemy in enemies[:]:
if enemy.x >= WIDTH - enemy.get_width():
move(0, enemy_y_vel, enemies)
vel_x = -enemy_x_vel
# enemies action
for enemy in enemies[:]:
if enemy.x >= WIDTH - enemy.get_width():
move(0, enemy_y_vel, enemies)
vel_x = -enemy_x_vel
elif enemy.x <= 0:
move(0, enemy_y_vel, enemies)
vel_x = enemy_x_vel
elif enemy.x <= 0:
move(0, enemy_y_vel, enemies)
vel_x = enemy_x_vel
enemy.move_missiles(enemy_missile_vel, player)
enemy.move_missiles(enemy_missile_vel, player)
if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT):
player.score -= 10
player.lives -= 1
enemies.remove(enemy)
if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT):
player.score -= 10
player.lives -= 1
enemies.remove(enemy)
move(vel_x, 0, enemies)
move(vel_x, 0, enemies)
if pygame.time.get_ticks() - last_enemy_shot > 2000:
choice(enemies).shoot()
last_enemy_shot = pygame.time.get_ticks()
if pygame.time.get_ticks() - last_enemy_shot > 2000:
choice(enemies).shoot()
last_enemy_shot = pygame.time.get_ticks()
player.move_missiles(-player_missile_vel, enemies)
player.move_missiles(-player_missile_vel, enemies)
# lambda functions
set_font = lambda size, font=FONT: pygame.font.Font(font, size) # sets font size
collide = lambda obj1, obj2: obj1.mask.overlap(obj2.mask, (obj2.x - obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
def set_font(size, font=FONT): return pygame.font.Font(
font, size) # sets font size
def collide(obj1, obj2): return obj1.mask.overlap(obj2.mask, (obj2.x -
obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
def move(vel_x: int, vel_y: int, enemies: list) -> None:
for enemy in enemies:
enemy.move(vel_x, vel_y)
for enemy in enemies:
enemy.move(vel_x, vel_y)
def main_menu() -> None:
while True:
WINDOW.blit(BACKGROUND, (0, 0))
title_label = set_font(50).render("Press any key to start...", 1, WHITE)
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, HEIGHT / 2 - title_label.get_height() / 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
main()
while True:
WINDOW.blit(BACKGROUND, (0, 0))
title_label = set_font(50).render(
"Press any key to start...", 1, WHITE)
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() /
2, HEIGHT / 2 - title_label.get_height() / 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
main()
if __name__ == "__main__":
main_menu()
main_menu()