2017-02-02 10 views
0

赤と緑の2つの矩形を次のコードの先頭に追加しました。何らかの理由で私のコードが機能しませんでした。グリッドセルはクリックされると赤くなりますが、クリックは歪んでいます。誰も問題についてアドバイスできますか?私は2つの問題があります:Pygameボタンの機能と修正グリッド選択マウス機能

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

行と列を計算するときの+50と+60は何ですか? –

+0

BTW: 'x、y = pygame.mouse.get_pos()'を実行するとコードが読みやすくなります。 – furas

+0

'x =(margin + width)* column + margin + 50 'を使用して矩形を描くなら、' column =(x - (margin + 50))//(margin + width) ' – furas

答えて

0

これは決してあなたの目標を達成するための理想的な方法ですが、私可能な限りあなたのコードと一貫性を保つようにコードを保ちました。これがどのように機能するかご質問がありましたら教えてください。すぐに答えるために全力を尽くします。

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