Python/Pygame 添加带有按钮的标题屏幕 [英] Python/Pygame adding a title screen with a button

查看:45
本文介绍了Python/Pygame 添加带有按钮的标题屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

<预><代码>导入 pygame、随机、系统从 pygame.locals 导入 *黑色 = (0, 0, 0)白色 = (255, 255, 255)绿色 = (0, 255, 0)红色 = (255, 0, 0)蓝色 = (0, 0, 255)宽度 = 20高度 = 20宽度 1 = 30高度 1 = 30保证金 = 5保证金 1 = 10数组宽度 = 4数组高度 = 8网格 = []猜测 1 = '白色'猜测 2 = '黄色'猜测 3 = '蓝色'猜测 4 = '绿色'猜测 5 = '红色'猜测 6 = '粉红色'猜测 7 = '紫色'猜测8 = '橙色'循环 = ()计算机猜测 = []# 创建随机颜色序列来猜测对于范围内的 i (4):循环 = random.randint(1,8)如果循环 == 1:computerguess.append(guess1)如果循环 == 2:computerguess.append(guess2)如果循环 == 3:computerguess.append(guess3)如果循环 == 4:computerguess.append(guess4)如果循环 == 5:computerguess.append(guess5)如果循环 == 6:computerguess.append(guess6)如果循环 == 7:computerguess.append(guess7)如果循环 == 8:computerguess.append(guess8)打印(电脑猜测)对于范围(10)中的行:grid.append([])对于范围(10)中的列:网格[行].追加(0)颜色 = [(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()# 设置屏幕的高度和宽度WINDOW_SIZE = [300, 300]WINDOW_SIZE2 = [300, 300]屏幕 = pygame.display.set_mode(WINDOW_SIZE)screen2 = pygame.display.set_mode(WINDOW_SIZE2)# 设置屏幕标题pygame.display.set_caption(大师游戏")完成 = 错误时钟 = pygame.time.Clock()# -------- 主程序循环 -----------#TEXT 框变量和数据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')颜色=颜色_被动活动 = 假current_color =白色";grid = [[[current_color for column in range(4)] for row in range(8)]#----主程序循环----#虽然没有完成:对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:完成 = 真elif event.type == pygame.MOUSEBUTTONDOWN:pos = pygame.mouse.get_pos()column = pos[0]//(宽度 + 边距)row = pos[1]//(高度 + 边距)# 检查列和行是否是有效的网格索引如果 0 <= 行

我想添加一个标题屏幕,上面写着以按钮的形式开始,然后将它们转移到代码中开始播放,但我不太确定该怎么做,我添加了一个新的窗口(WINDOW_SIZE2),但我不知道从那里去

非常感谢任何帮助

谢谢

解决方案

一个按钮的实现被多次回答.例如Pygame鼠标点击检测如何检测鼠标是否悬停在按钮?PyGame 按钮类未在悬停时显示文本或更改颜色如何将图像或图标添加到 Pygame 中的按钮矩形? 等等.


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

button_rect = pygame.Rect(x, y, width, height) # 开始按钮矩形中止 = 错误开始=假虽然不中止且不启动:对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:中止 = 真如果 event.type == MOUSEBUTTONDOWN:如果 button_rect.collidepoint(event.pos):开始 = 真# 绘制标题画面# [...]完成 = 中止虽然没有完成:虽然没有完成:对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:完成 = 真# 游戏# [...]


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

game_state = 'title'完成 = 错误虽然没有完成:# 事件处理对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:完成 = 真如果游戏状态=='标题':如果 event.type == MOUSEBUTTONDOWN:如果 button_rect.collidepoint(event.pos):游戏状态 = '游戏'elif game_state == '游戏':# 处理游戏事件:# [...]# 画画如果游戏状态=='标题':# 绘制标题画面# [...]elif game_state == '游戏':# 游戏# [...]

I have this code


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()

i would like to add a title screen, that says start in the form of a button and then would transfer them to the code to begin playing, but i'm not very sure how to do it, i have added a new window (WINDOW_SIZE2), but i am not sure where to go from there

Any help is much appreciated

Thanks

解决方案

The implementation of a button is answered several times. For example Pygame mouse clicking detection, How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover or How can I add an image or icon to a button rectangle in Pygame? and myn more.


Create 2 scenes with 2 application loops. The first loop shows the title screen and waits for button 2 to be pressed. The 2nd loop is the game loop:

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
    # [...]


Alternatively, you can combine both scenes in one loop.Add a variable game_state, implement event handling and draw the scenes depending on the value of game_state. Change the game_state when the start button is pressed:

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
        # [...]

这篇关于Python/Pygame 添加带有按钮的标题屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆