我设法找到了解决我自己问题的方法,并包含了我的代码,希望它可以在未来帮助其他人。我创建了一个 Button 类并循环了 9 次以创建网格。该类有一个方法'controls',它是一个按钮索引列表,可以通过按下按钮来更改。我可以使用按钮[i].controls 访问这些按钮。
如原帖中所述,我是 python 和 pygame 新手,所以如果我的代码中有任何错误或效率低下,请随时发布改进。在我的学习过程中,我一直在使用 Michael Dawson 的 Python Programming for the Absolute Beginner (Third Edition) 和 pythonprogramming.net 以及其他资源。
##import and initiate pygame
import pygame as pg
pg.init()
##Set display dimensions and the button size as a function of these dimensions.
display_width = 400
display_height = 600
buttonSize = (display_width/4)
##Create game display surface.
gameDisplay = pg.display.set_mode((display_width,display_height))
white = (255,255,255)
##posList holds nine pairs of X,Y multipliers. These are multiplied by buttonSize to draw the grid.
posList = ((0.25,0.25), (0.25,1.5), (0.25,2.75), (1.5,0.25), (1.5,1.5), (1.5,2.75), (2.75,0.25), (2.75,1.5), (2.75,2.75))
##board is a list of nine lists. Each nested list holds the butttons that switched by each button press.
board = ((0,1,3),(1,0,2,4),(2,1,5),(3,4),(4,1,7),(5,4),(6,3,7),(7,4,6,8),(8,5,7))
##I import the button image
redSquare = pg.image.load('Button Image.png').convert()
redSquare = pg.transform.scale(redSquare, (int(buttonSize), int(buttonSize)))
##The Button class holds coordinate, image and controls attributes
class Button:
def __init__(self, x, y, image, controls, green = False):
self.x = x
self.y = y
self.image = image
self.isgreen = green
self.controls = controls
##It has a blit method.
def buttonBlit(self):
gameDisplay.blit(self.image, (self.x, self.y))
##I create an empty list called buttons.
buttons = []
##I populate buttons by looping through the Button class 9 times.
for i in range(9):
buttons.append(Button(posList[i][0] * buttonSize, posList[i][1] * buttonSize, redSquare, board[i]))
##The blit method draws the buttons.
gameDisplay.fill(white)
for button in buttons:
Button.buttonBlit(button)
pg.display.update()
##I can reference each button by using the index in the buttons list. Furthermore, I can use buttons[i].controls to perform the actions of a button press.