策划游戏,蟒蛇,选择颜色

时间:2021-01-20 10:01:40

标签: python pygame

我正在创建一个策划游戏,但我不知道如何从文本框中获取用户的输入,以便用于用颜色填充其中一个方块。

这是代码:

import pygame

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 = []
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)]

pygame.init()

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

# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")
sair = True
done = False

clock = pygame.time.Clock()
# -------- Main Program Loop -----------
grid[row][column] = 1

#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 32)
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

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

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

            column = pos[0] // (WIDTH + MARGIN)
            row = pos[1] // (HEIGHT + MARGIN)
            print(row)
            print(column)
            # 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
                print(user_text)

            # check if column and row are valid grid indices
            if 0 <= column < array_height and 0 <= row < array_width:

                blocks[row * array_height + column] = not blocks[row * array_height + column]
                # toggle
                for row in range(array_width):
                    for column in range(array_height):

                        # CHECK IF BLOCK SHOULD BE CHANGED
                        if blocks[column * array_width + row]:
                            if user_text == 'blue':
                                colors[column * array_height + row] = (0, 0, 255)

            print("Click ", pos, "Grid coordinates: ", row, column)

    if active:
        color = color_active
    else:
        color=color_passive
    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))

    for row in range(8):
        for column in range(4):
            color = WHITE
            pygame.draw.rect(screen,
                             color,
                             [(MARGIN + WIDTH) * column + MARGIN,
                              (MARGIN + HEIGHT) * row + MARGIN,
                              WIDTH,
                              HEIGHT])

    clock.tick(60)

    pygame.display.flip()

pygame.quit()

GUI 的样子

GUI

我确实有一种使用类似方法的方法

 for row in range(10):
    for column in range(10):
        color = WHITE
        if grid[row][column] == 1:
            color = GREEN
        if grid[row][column] == 2:
            color = RED
        pygame.draw.rect(screen,
                         color,
                         [(MARGIN + WIDTH) * column + MARGIN,
                          (MARGIN + HEIGHT) * row + MARGIN,
                          WIDTH,
                          HEIGHT])

但是当点击文本框时它会显示 index out of range,所以我想我可能应该使用不同的方法。

1 个答案:

答案 0 :(得分:1)

为颜色创建一个变量并使用当前颜色创建一个网格:

current_color = "white"
grid = [[current_color for column in range(4)] for row in range(8)]

当您单击一个单元格时,将当前颜色分配给该单元格:

while not done:
    for event in pygame.event.get():
        # [...]

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

            column = pos[0] // (WIDTH + MARGIN)
            row = pos[1] // (HEIGHT + MARGIN)
            
            if 0 <= row < array_height and 0 <= column < array_width:
                try:
                    grid[row][column] = current_color
                except:
                    print("invalid color")

按下 RETURN 时更改当前颜色:

while not done:
    for event in pygame.event.get():
        # [...]

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                user_text = user_text
                print(user_text)
                if user_text != "":
                    current_color = user_text
                user_text = ""

使用网格中的颜色进行绘图:

while not done:
    # [...]

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

完整示例:

import pygame

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 = []
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)]

pygame.init()

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

# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")
sair = True
done = False

clock = pygame.time.Clock()
# -------- Main Program Loop -----------
grid[row][column] = 1

#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 32)
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)]

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

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

            column = pos[0] // (WIDTH + MARGIN)
            row = pos[1] // (HEIGHT + MARGIN)
            print(row)
            print(column)
            # TEXT BOX CREATION AND USAGE

            # 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")

        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
                print(user_text)
                if user_text != "":
                    current_color = user_text
                user_text = ""

            print("Click ", pos, "Grid coordinates: ", row, column)

    if active:
        color = color_active
    else:
        color=color_passive

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

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

    clock.tick(60)

    pygame.display.flip()

pygame.quit()
相关问题