Advertisement

How to make main menu in pygame ?

Started by July 23, 2019 01:20 PM
5 comments, last by Alberth 5 years, 1 month ago

I was trying to do main menu that shows up on the screen, so when I would press q it gets me into the game ( becuse I'dont know How to make buttons yet ) but it displays in the console.


def main():
    menu()

def menu():

    choice = input("""
                      B: Login
                      Q: Logout

                      Please enter your choice: """)

    if choice == "B" or choice == "b":
        login()
    elif choice == "Q" or choice == "q":
        sys.exit
    else:
        print("You must only select B")
        print("Please try again")
        menu()

def login():
    pass

main()

Also when I press Q/q It opens the game so sys.exit doesn't work.

If you know How can i display this message on the screen or make buttons I will be really gratefull. ?

You can paint text and draw coloured rectangles, and detect if mouse clicks are inside the coloured rectangle :) Key-presses are received from events. So you first receive a key event, extract the key, and then check if it is the 'q' key.

EDIT: Added an example, it is Python2, so if you're using Python3, some minor things have to change.


#!/usr/bin/env python2
import pygame

pygame.init()
pygame.font.init()

BLACK  = (0, 0, 0)
DARK   = (120, 120, 120)
LATE   = (170, 170, 170)
NOTICE = (255,   0, 255)
NORMAL = (150, 150, 150)
WHITE  = (200, 200, 200)
SHINY  = (255, 255, 255)
RED    = (200,  10,  10)

NORMAL_SMALL  = (200, 200, 120)
NORMAL_MEDIUM = (180, 180, 120)
NORMAL_LARGE  = (160, 160, 120)

DISPLAY_WIDTH = 200
DISPLAY_HEIGHT = 200


class Button(object):
    def __init__(self, x, y, w, h, text, colour=None):
        if colour is None:
            colour = NORMAL

        self.normal_colour = colour
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.font = pygame.font.Font(None, 20)
        self.text = text
        self.shiny = False

    def draw(self, screen):
        if self.shiny:
            bg = SHINY
        else:
            bg = self.normal_colour

        surf = self.font.render(self.text, True, BLACK, bg)
        rect = (self.x, self.y, self.w, self.h)
        xo = self.x + (self.w - surf.get_width()) // 2
        yo = self.y + (self.h - surf.get_height()) // 2
        screen.fill(bg, rect)
        screen.blit(surf, (xo, yo))

    def on_button(self, pos):
        return self.x <= pos[0] and self.x + self.w > pos[0] and \
               self.y <= pos[1] and self.y + self.h > pos[1]

    def set_shiny(self, new_shiny):
        self.shiny = new_shiny


def draw(screen):
    screen.fill(BLACK)
    for b in buttons:
        b.draw(screen)

def update_click(pos):
    for b in buttons:
        if b.on_button(pos):
            b.set_shiny(not b.shiny)



buttons = []
buttons.append(Button(10, 10, 150, 20, "myname", colour=RED))
buttons.append(Button(10, 100, 150, 30, "yourname", colour=NORMAL))

screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Click Buttons')

done = False
while not done:
    draw(screen)
    pygame.display.flip()

    # Wait until the next event.
    event = pygame.event.wait()

    # Release of the LMB.
    if event.type == pygame.MOUSEBUTTONUP:
        if event.button == 1 and update_click(event.pos):
            pass # Update screen

    # Window got closed.
    elif event.type == pygame.QUIT:
        done = True
        break

    # Pressed 'q'.
    elif event.type == pygame.KEYDOWN:
        if event.key == ord('q'):
            done = True
            break

 

Advertisement

I fixed the q key ? but I don't understand How do I dispay main menu image before the game.

This is the code that reads map in my .txt file from my folder.


def load_map(path):
    f = open(path + '.txt', 'r')
    data = f.read()
    f.close()
    data = data.split('\n')
    game_map = []
    for row in data:
        game_map.append(list(row))
    return game_map

game_map = load_map('map')

so do I need to replace this   with code that reads my .jpg file ?


choice = input("""
                      B: Login
                      Q: Logout

                      Please enter your choice: """)

Oh, ty for the edit. I see how it works. Finally I have even more code to play around ?

Sorry I completely forgot to reply, but this is the code for mouse position and event for it


if event.type == pygame.MOUSEBUTTONUP:
    mx, my = pygame.mouse.get_pos()
    if mx > 10 and mx < 150 and my > 10 and my < 20:
        done = True
        break
    if mx > 10 and mx < 150 and my > 100 and my < 120:
        pygame.quit()
        sys.exit()
15 hours ago, dMn420 said:

Sorry I completely forgot to reply, but this is the code for mouse position and event for it

That works too, but it's not entirely the same as my code which gets the position from the event, ie "event.pos" in


if event.type == pygame.MOUSEBUTTONUP:
    if event.button == 1 and update_click(event.pos):
        pass # do something

The difference is at which point in time exactly the position is queried. The "event.pos" is the mouse position at the moment you click the button. "pygame.mouse.get_pos()" is the mouse position when you run that line of code. If you move the mouse fast while clicking these positions are not the same.

This topic is closed to new replies.

Advertisement