Итак, идея для моей игры - открыть ее в меню с четырьмя вариантами: Easy, Medium, Hard и Exit. Опция «Easy» откроет первый уровень, Medium откроет второй уровень, Hard откроет третий уровень, и выход выйдет из игры.Pygame игра не работает
Если пользователь выбирает вариант «Легкий», «Средний» или «Жесткий», то он доставит их в лабиринт (макет лабиринта будет сделан позже), где игрок поселяется посередине. В каждом углу лабиринта есть зеленый квадрат, и один из зеленых квадратов станет красным, и у игрока будет 60 секунд, чтобы добраться до него. Если игрок достигнет его вовремя, позиция игрока, случайное число и таймер будут сброшены, но с 10 секундами меньше, чем в предыдущее время (50, 40, 30, ...). Если игрок не достигнет его вовремя, тогда текст появляется, говоря «Вы теряете» вместе со своим лучшим временем (например, «Лучшее время: 24 секунды») на пару секунд, прежде чем вернуться в главное меню.
Я знаю, что это немного растягивается, но если кто-то может объединить то, что у меня есть сейчас, со своими знаниями, чтобы создать игру с описанием выше, я был бы всегда благодарен. Пожалуйста помоги.
import pygame, random, os, sys
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
YELLOW = (255, 200, 0)
pygame.init()
screen = pygame.display.set_mode((480, 320))
font = pygame.font.SysFont("Calibri", 20)
menu_font = pygame.font.Font(None, 40)
currentLevel = 0
pygame.display.set_caption("Mazer")
screen = pygame.display.set_mode((1040, 768))
clock = pygame.time.Clock()
rand = random.randint(1, 4)
class Player(object):
def __init__(self, pos):
self.rect = pygame.Rect(pos[0], pos[1], 15, 15)
def move(self, dx, dy):
if dx != 0:
self.move_single_axis(dx, 0)
if dy != 0:
self.move_single_axis(0, dy)
def move_single_axis(self, dx, dy):
self.rect.x += dx
self.rect.y += dy
for wall in walls:
if self.rect.colliderect(wall.rect):
if dx > 0:
self.rect.right = wall.rect.left
if dx < 0:
self.rect.left = wall.rect.right
if dy > 0:
self.rect.bottom = wall.rect.top
if dy < 0:
self.rect.top = wall.rect.bottom
# Nice class to hold a wall rect
class Wall(object):
def __init__(self, pos):
self.rect = pygame.Rect(pos[0], pos[1], 16, 16)
class Finish1(object):
def __init__(self, pos):
Finish1.rect = pygame.Rect(pos[0], pos[1], 16, 16)
class Finish2(object):
def __init__(self, pos):
Finish2.rect = pygame.Rect(pos[0], pos[1], 16, 16)
class Finish3(object):
def __init__(self, pos):
Finish3.rect = pygame.Rect(pos[0], pos[1], 16, 16)
class Finish4(object):
def __init__(self, pos):
Finish4.rect = pygame.Rect(pos[0], pos[1], 16, 16)
class Option:
hovered = False
def __init__(self, text, pos):
self.text = text
self.pos = pos
self.set_rect()
self.draw()
def draw(self):
self.set_rend()
screen.blit(self.rend, self.rect)
def set_rend(self):
self.rend = menu_font.render(self.text, True, self.get_color())
def get_color(self):
if self.hovered:
return (255, 255, 255)
else:
return (100, 100, 100)
def set_rect(self):
self.set_rend()
self.rect = self.rend.get_rect()
self.rect.topleft = self.pos
options = [Option("Easy", (140, 105)), Option("Medium", (135, 155)),
Option("Hard", (145, 205)), Option("Exit", (145, 255))]
def Menu():
runnin = True
while runnin:
clock.tick(60)
screen.fill(BLACK)
mouseclick = pygame.mouse.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit(0)
for option in options:
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
if mouseclick[0] == 1:
if option.text == "Easy":
global currentlevel
currentlevel = 0
main()
elif option.text == "Medium":
currentlevel = 1
main()
elif option.text == "Hard":
currentlevel = 2
main()
else:
runnin = False
else:
option.hovered = False
option.draw()
#screen.blit(, (350, 50))
pygame.display.update()
pygame.quit()
sys.exit(0)
levels = [[
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"WF GW",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W P W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WH IW",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
],
[
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"WF GW",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W P W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WH IW",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
],
[
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"WF GW",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W P W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WH IW",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
]]
def load_level(level):
walls = []
players = []
finishes = []
x = y = 0
for row in levels[level]:
for col in row:
if col == "W":
walls.append(Wall((x, y)))
if col == "P":
players.append(Player((x, y)))
if col == "F":
finishes.append(Finish1((x, y)))
if col == "G":
finishes.append(Finish2((x, y)))
if col == "H":
finishes.append(Finish3((x, y)))
if col == "I":
finishes.append(Finish4((x, y)))
x += 16
y += 16
x = 0
return walls, players, finishes
walls, players, finishes = load_level(currentLevel)
def main():
frame_count = 0
frame_rate = 60
start_time = 60
running = True
while running:
clock.tick(60)
pygame.event.pump()
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
running = False
for option in options:
if option.rect.collidepoint(pygame.mouse.get_pos()):
option.hovered = True
else:
option.hovered = False
option.draw()
total_seconds = start_time - (frame_count // frame_rate)
if total_seconds < 1:
#Draw "you lose" text on screen along with your best time for a couple of
#seconds then return to main menu
Menu()
minutes = total_seconds // 60
seconds = total_seconds % 60
output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)
text = font.render(output_string, True, WHITE)
screen.blit(text, [250, 280])
frame_count += 1
clock.tick(frame_rate)
# Move the player if an arrow key is pressed
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
player.move(-2, 0)
if key[pygame.K_RIGHT]:
player.move(2, 0)
if key[pygame.K_UP]:
player.move(0, -2)
if key[pygame.K_DOWN]:
player.move(0, 2)
for player in players:
if player.rect.colliderect(Finish1.rect) and rand == 1:
total_seconds = best_time
start_time -= 10
#reset the timer to start_time - 10, reset the random integer, and reset player somehow
if player.rect.colliderect(Finish2.rect) and rand == 2:
total_seconds = best_time
start_time -= 10
#reset the timer to start_time - 10, reset the random integer, and reset player somehow
if player.rect.colliderect(Finish3.rect) and rand == 3:
total_seconds = best_time
start_time -= 10
#reset the timer to start_time - 10, reset the random integer, and reset player somehow
if player.rect.colliderect(Finish4.rect) and rand == 4:
total_seconds = best_time
start_time -= 10
#reset the timer to start_time - 10, reset the random integer, and reset player somehow
screen.fill((BLACK))
for wall in walls:
pygame.draw.rect(screen, (WHITE), wall.rect)
for player in players:
pygame.draw.rect(screen, (YELLOW), player.rect)
pygame.draw.rect(screen, (GREEN), finish.rect)
if rand == 1:
pygame.draw.rect(screen, (RED), Finish1.rect)
elif rand == 2:
pygame.draw.rect(screen, (RED), Finish2.rect)
elif rand == 3:
pygame.draw.rect(screen, (RED), Finish3.rect)
else:
pygame.draw.rect(screen, (RED), Finish4.rect)
pygame.display.flip()
if __name__ == '__main__':
main()