我有一个方法,每次调用时都会重新绘制屏幕。但它似乎不能正常工作。我的pygame窗口上显示了一些按钮,这些按钮上打印了一些来自列表的文本。每次按下按钮,列表都会发生变化。我需要能够重新绘制窗口,从更改的列表中更新按钮的文本。
这是我的Button类
class Button:
def __init__(self, text, x, y, color, width=50, height=50):
self.text = text
self.x = x
self.y = y
self.color = color
self.width = width
self.height = height
def draw(self, window):
pygame.draw.rect(window, self.color, (self.x, self.y, self.width, self.height))
font = pygame.font.SysFont("comicsans", 40)
text = font.render(self.text, 1, (255, 255, 255))
window.blit(text, (self.x + round(self.width / 2) - round(text.get_width() / 2),
self.y + round(self.height / 2) - round(text.get_height() / 2)))
def click(self, pos):
x1 = pos[0]
y1 = pos[1]
if self.x <= x1 <= self.x + self.width and self.y <= y1 <= self.y + self.height:
return True
else:
return False
以及我的重绘方法:
def redrawWindow(window):
window.fill((128, 128, 128))
font = pygame.font.SysFont("comicsans", 20)
if my_turn:
text = font.render("Your move", 1, (0, 200, 10))
else:
text = font.render("Opponent move", 1, (255, 0, 0))
# else: text = their move
screen.blit(text, (width / 2 - text.get_width() / 2, (height / 2 - text.get_height() / 2) - 150))
for btn in btns:
btn.draw(window)
pygame.display.update()
这是我的主要循环:
def main():
# game loop
running = True
while running:
if my_turn:
pass
redrawWindow(screen)
# for loop through the event queue
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
pygame.quit()
btn_counter = -1
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for btn in btns:
btn_counter += 1
if btn.click(pos):
# TODO:check to make sure its that client's turn
if my_turn:
print(f"This is the button that was pressed: {btn_counter}")
print(f"marbles in button: {game_state[btn_counter]}")
hole_chosen(btn_counter)
else:
pass
#flash: not your turn
redrawWindow(screen)