【问题标题】:Pygame buttons functionality and correcting grid select mouse functionPygame 按钮功能和校正网格选择鼠标功能
【发布时间】:2017-06-19 12:53:16
【问题描述】:

我在以下代码的顶部添加了两个矩形,红色和绿色,但由于某种原因,我的代码原本可以正常工作,但现在却不行了。单击时网格单元格应变为红色,但单击是倾斜的。任何人都可以就这个问题提出建议吗?我有两个问题:

  1. 赞成第一个发现并指出错误的人,除非我先得到它!
  2. 我还想将文本(用户 1 和用户 2)添加到矩形并使其可点击。单击时,用户会选择一个随机网格单元(变为红色或绿色)

代码如下:

import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

pygame.init()
size = (350, 350)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()

width=22
height=22
margin=12


grid=[]
#Loop for each row in the list
for row in range(7):
    #for each row, create a list that will represent an entire row
    grid.append([])
    #loop for each column
    for column in range(7):
        #add the number zero to the current row
        grid[row].append(0)
        #set row 1, column 5 to one
#grid[1][3]=1
#print(grid[1][3]) #this is the 2nd row and the 4th element along (0...1 row and 0...1...2....3 Column)


# -------- Main Program Loop -----------
while not done:
#ALL EVENT PROCESSING SHOULD GO BELOW THIS LINE

    # --- Main event loop
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True
            #************CODE ADDED HERE**********************
        elif event.type == pygame.MOUSEBUTTONDOWN:
            #print("user clicked the screen")
            pos=pygame.mouse.get_pos()
            #x = grid[0]
            #y=  grid[1]
            #print(pos)
            #CHANGE THE X and Y screen coordinates as in the comments above to grid coordinates
            column=pos[0]//(width+margin+50)
           row=pos[1]//(height+margin+60)
           #set the location to one (when selected by the mouse)
            grid[row][column]=1
            #print("User click ", pos, "Grid coordinates:", row+1, column+1)



     # --- Game logic should go here


    # --- Screen-clearing code goes here

  # Here, we clear the screen to white. Don't put other drawing commands
   # above this, or they will be erased with this command.

   # If you want a background image, replace this clear with blit'ing the
   # background image.
     screen.fill(BLACK)

    # --- Drawing code should go here
    #Drawing the red and Green rectangles
    pygame.draw.rect(screen,RED, [0,0,120,50])
    pygame.draw.rect(screen,GREEN, [240,0,120,50])

    for row in range(7):
        #the column number - this refers to the number of columns it will produce. 2, for example, will produce only 2 columns
        for column in range(7):
            color = WHITE
            if grid[row][column] ==1:
                color = RED
                #****MOVING THE REST OF THE GRID DOWN*****
                #the 60 is the margin from the top
                #the 50 is the margin from the left
            pygame.draw.rect(screen,color,[(margin + width) * column + margin+50, (margin + height) * row + margin+60,width,height])

#*******PRINTING TEXT TO THE SCREEN**********
    # Select the font to use, size, bold, italics
    #font = pygame.font.SysFont('Calibri', 25, True, False)
    #text = font.render("a", True, BLACK)
    # Put the image of the text on the screen at 250x250
    #screen.blit(text, [25, 25])

    # --- This bit updates the screen with what we've drawn.
pygame.display.flip()

    # --- Limit to 60 frames per second
clock.tick(60)

# Close the window and quit.
pygame.quit()

【问题讨论】:

  • 计算行列时的+50和+60是什么意思?
  • 顺便说一句:你可以做x, y = pygame.mouse.get_pos() 并且代码将更具可读性。
  • 如果你使用x = (margin + width) * column + margin+50绘制矩形,那么column = (x - (margin+50))//(margin + width)
  • 更好地创建类Button,它会更容易使用。见button-hover

标签: python button input grid pygame


【解决方案1】:

这绝不是实现您目标的理想方式,但我尽量使代码与您的代码保持一致。如果您对它的工作原理有任何疑问,请告诉我。我会尽快回复的。

import pygame
from pygame.locals import *

pygame.init()

# first we define some constants
# doing this will reduce the amount of 'magic' numbers throughout the code
WINWIDTH = 350
WINHEIGHT = 350
WINSIZE = (WINWIDTH, WINHEIGHT)

CELLWIDTH = 22
CELLHEIGHT = 22
CELLSIZE = (CELLWIDTH, CELLHEIGHT)

CELLMARGINX = 12 # number of pixels to the left and right of each cell
CELLMARGINY = 12 # number of pixels to the top and bottom of each cell

SCREENPADX = 60 # number of pixels between the GRID and the left and right of the window
SCREENPADY = 70 # number of pixels between the GRID and the top and bottom of the window

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

DONE = False # is our program finished running?

# information about the two buttons (red and green)
REDBUTTON = (0, 0, 120, 50)
GREENBUTTON = (240, 0, 120, 50)

# create the WINDOW and CLOCK
WINDOW = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('My Game')
CLOCK = pygame.time.Clock()

CURRENTCOLOR = RED # which color is active

# setting up the GRID
# cells can be accessed by GRID[row][col] ie. GRID[3][4] is the 3rd row and 4th column
# each cell contains [x, y, color]
# where x is the x position on the screen
#       y is the y position on the screen
#       color is the current color of the cell
GRID = []
for y in range(7):
     row = []
     for x in range(7):
         row.append([x * (CELLWIDTH + CELLMARGINX) + SCREENPADX, y * (CELLHEIGHT + CELLMARGINY) + SCREENPADY, WHITE])
     GRID.append(row)

# main loop
while not DONE:

    # process all events
    for event in pygame.event.get():
        if event.type == QUIT: # did the user click the 'x' to close the window
            DONE = True

        if event.type == MOUSEBUTTONDOWN:
            # get the position of the mouse
            mpos_x, mpos_y = event.pos

            # check if REDBUTTON was clicked
            button_x_min, button_y_min, button_width, button_height = REDBUTTON
            button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
            if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
                CURRENTCOLOR = RED

            # check if GREENBUTTON WAS CLICKED
            button_x_min, button_y_min, button_width, button_height = GREENBUTTON
            button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
            if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
                CURRENTCOLOR = GREEN

            # calculations for clicking cells

            mpos_x -= SCREENPADX # mouse position relative to the upper left cell
            mpos_y -= SCREENPADY # ^ same

            col = mpos_x // (CELLWIDTH + CELLMARGINX) # which cell is the mouse clicking
            row = mpos_y // (CELLHEIGHT + CELLMARGINY) # ^ same

            # make sure the user clicked on the GRID area
            if row >= 0 and col >= 0:
                try:
                    # calculate the boundaries of the cell
                    cell_x_min, cell_y_min =  col * (CELLHEIGHT + CELLMARGINY), row * (CELLWIDTH + CELLMARGINX)
                    cell_x_max = cell_x_min + CELLWIDTH
                    cell_y_max = cell_y_min + CELLHEIGHT
                    # now we will see if the user clicked the cell or the margin
                    if cell_x_min <= mpos_x <= cell_x_max and cell_y_min <= mpos_y <= cell_y_max:
                        GRID[row][col][2] = CURRENTCOLOR if event.button == 1 else WHITE
                    else:
                        # the user has clicked the margin, so we do nothing
                        pass
                except IndexError: # clicked outside of the GRID
                    pass           # we will do nothing

    # logic goes here


    # drawing
    WINDOW.fill(BLACK)

    pygame.draw.rect(WINDOW, RED, REDBUTTON)
    pygame.draw.rect(WINDOW, GREEN, GREENBUTTON)

    for row in GRID:
        for x, y, color in row:
            pygame.draw.rect(WINDOW, color, (x, y, CELLWIDTH, CELLHEIGHT))

    pygame.display.flip()

    CLOCK.tick(60)

pygame.quit()

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多