首页 > 解决方案 > Creating a Main Menu for connect 4 on python

问题描述

I am trying to create a main menu (starting page) for a 3 player connect 4 but I am unable to create one I want 5 buttons (3 player game, 2 player game, single player, options, Quit).

Can anyone help? If possible can anyone give me example code which I could adapt to my game.

I haven't created a main menu before.

I don't mid use of tkinter or pygame.

标签: pythontkinterpygame-menu

解决方案


一个黄色按钮的小例子,点击时会打印一些文本(代码注释中有更多解释):

import pygame

pygame.init()
screen = pygame.display.set_mode((500, 400))
clock = pygame.time.Clock()

# create the surface that will be the button
btn = pygame.Surface((300, 200))
btn.fill((255, 255, 0))
rect = btn.get_rect(center=(250, 200))
clicked = False


run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    screen.fill((0, 0, 0))
    
    # get mouse pos
    mouse_pos = pygame.mouse.get_pos()
    # get the state of left mouse button
    left, *_ = pygame.mouse.get_pressed()

    # check if mouse is in the button and if the mouse button has been clicked
    # the flag `clicked` is for registering the click once when button is pressed
    # otherwise it will loop again and the conditions will be true again
    # you can also use the event loop above to detect whether the
    # mouse button has been pressed, then the flag is not needed
    if rect.collidepoint(mouse_pos) and left and not clicked:
        clicked = True
        print('clicked')
    # reset flag
    if not left:
        clicked = False
    
    # show the button
    screen.blit(btn, rect)

    pygame.display.update()

有用:


推荐阅读