繁体   English   中英

Python/Pygame 添加带有按钮的标题屏幕

[英]Python/Pygame adding a title screen with a button

我有这个代码


import pygame, random, sys
from pygame.locals import *

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0 , 0, 255)

WIDTH = 20
HEIGHT = 20
WIDTH1 = 30
HEIGHT1 = 30

MARGIN = 5
MARGIN1 = 10

array_width = 4
array_height = 8

grid = []
guess1 = 'white'
guess2 = 'yellow'
guess3 = 'blue'
guess4 = 'green'
guess5 = 'red'
guess6 = 'pink'
guess7 = 'purple'
guess8 = 'orange'
loop = ()

computerguess = []
# CREATING RANDOM COLOUR SEQUENCE TO GUESS
for i in range(4):
    loop = random.randint(1,8)
    if loop == 1:
        computerguess.append(guess1)
    if loop == 2:
        computerguess.append(guess2)
    if loop == 3:
        computerguess.append(guess3)
    if loop == 4:
        computerguess.append(guess4)
    if loop == 5:
        computerguess.append(guess5)
    if loop == 6:
        computerguess.append(guess6)
    if loop == 7:
        computerguess.append(guess7)
    if loop == 8:
        computerguess.append(guess8)

print(computerguess)


for row in range(10):
    grid.append([])
    for column in range(10):
        grid[row].append(0)


colors = [(0, 0, 0) for i in range(array_width * array_height)]
blocks = [False for i in range(array_width * array_height)]
indicator_grid = [[None for column in range(4)] for row in range(8)]
pygame.init()

# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [300, 300]
WINDOW_SIZE2 = [300, 300]
screen = pygame.display.set_mode(WINDOW_SIZE)
screen2 = pygame.display.set_mode(WINDOW_SIZE2)


# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")

done = False

clock = pygame.time.Clock()
# -------- Main Program Loop -----------


#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 20)
user_text = ""
input_rect = pygame.Rect (10,250,100,50)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('gray15')
color=color_passive
active = False

current_color = "white"
grid = [[current_color for column in range(4)] for row in range(8)]
#----MAIN PROGRAM LOOP----#
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()

            column = pos[0] // (WIDTH + MARGIN)
            row = pos[1] // (HEIGHT + MARGIN)


            # check if column and row are valid grid indices
            if 0 <= row < array_height and 0 <= column < array_width:
                try:
                    grid[row][column] = current_color
                except:
                    print("invalid color")

        # TEXT BOX CREATION AND USAGE

        if event.type == pygame.MOUSEBUTTONDOWN:
            if input_rect.collidepoint(event.pos):
                active = True
            else:
                active = False

        if event.type == pygame.KEYDOWN:
            if active == True:
                if event.key == pygame.K_BACKSPACE:
                    user_text = user_text[0:-1]
                else:
                    user_text += event.unicode
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                user_text = user_text
                if user_text != "":
                    current_color = user_text
                user_text = ""

    if active:
        color = color_active
    else:
        color=color_passive

    #TEXT FOR THE GUI TO MAKE IT EASIER FOR THE USER
    screen.fill(0)
    pygame.draw.rect(screen,color,input_rect,2)
    text_surface= base_font.render(user_text,True,(255,255,255))
    screen.blit(text_surface, (input_rect.x +5, input_rect.y + 5))
    text1 = base_font.render("WORK BOTTOM TO TOP ", True, (0, 50, 255))
    text2 = base_font.render('POSSIBLE CHOICES:', True, (250, 0, 0))
    text3 = base_font.render('WHITE BLUE RED', True, (0, 128, 0))
    text4 = base_font.render('GREEN ORANGE PINK', True, (0,128,0))
    text5= base_font.render('PURPLE YELLOW', True, (0, 128, 0))
    screen.blit(text1,(140, 200))
    screen.blit(text2,(140, 220))
    screen.blit(text3,(140, 240))
    screen.blit(text4,(140, 260))
    screen.blit(text5,(140, 280))
    screen.blit(text5,(140, 280))



    for row, gridrow in enumerate(grid):
        for column, color in enumerate(gridrow):
            pygame.draw.rect(screen,
                             color,
                             [(MARGIN + WIDTH) * column + MARGIN,
                              (MARGIN + HEIGHT) * row + MARGIN,
                              WIDTH,
                              HEIGHT])
            if gridrow == computerguess:
                text = base_font.render("Correct, you win!!!!!", True, (255, 128, 0))
                screen.blit(text,
                            (10, 220 ))
            x = 100 + (MARGIN + WIDTH) * column + MARGIN
            y = (MARGIN + HEIGHT) * row + MARGIN
            color = "grey"
            pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)

    for row, gridrow in enumerate(grid):


        if computerguess[0] == gridrow[0]:
            color = "red"
            pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)

        if computerguess[1] == gridrow[1]:
            color = "purple"
            pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)

        if computerguess[2] == gridrow[2]:
            color = "red"
            pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)

        if computerguess[3] == gridrow[3]:
            color = "red"
            pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)




    clock.tick(60)

    pygame.display.flip()

pygame.quit()

我想添加一个标题屏幕,上面写着以按钮的形式开始,然后将它们传输到代码开始播放,但我不太确定怎么做,我添加了一个新的 window (WINDOW_SIZE2 ),但我不确定从那里到 go

任何帮助深表感谢

谢谢

一个按钮的实现被回答了好几次。 例如Pygame 鼠标点击检测如何检测鼠标是否悬停在按钮上? PyGame 按钮 class 未在 hover 上显示文本或更改颜色还有更多。


使用 2 个应用程序循环创建 2 个场景。 第一个循环显示标题屏幕并等待按钮 2 被按下。 第二个循环是游戏循环:

button_rect = pygame.Rect(x, y, width, height) # start button rectangle

abort = False
start = False
while not abort and not start:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            abort = True   

        if event.type == MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):
                start = True
 
    # draw title screen
    # [...]

done = abort
while not done:
 
    while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # game
    # [...]

或者,您可以将两个场景组合在一个循环中。添加变量game_state ,实现事件处理并根据game_state的值绘制场景。 按下开始按钮时更改game_state状态:

game_state = 'title'

done = False
while not done:
    
    # event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        if game_state == 'title':
            if event.type == MOUSEBUTTONDOWN:
                if button_rect.collidepoint(event.pos):
                    game_state = 'game'

        elif game_state == 'game':
            # handle game events:
            # [...]

    # drawing
    if game_state == 'title':
        # draw title screen
        # [...]
            
    elif game_state == 'game':
        # game
        # [...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM