我正在创建一个棋盘游戏,我正处于显示棋盘和让计数器在方格中移动的初始阶段。让计数器移动的代码工作正常,但我不得不改变它的位置,因为方格的颜色不断更新,而不是像在"while running"循环中那样保持一种纯色。
现在颜色是固定的,但计数器不会移动。
下面是代码:
import pygame, sys
import random
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("board")
exit = False
grey = (224,224, 224)
green = (204, 255, 204)
blue = (204, 255, 255)
purple = (204, 204, 255)
black = (0, 0, 0)
white = (255, 255, 255)
rows = 10
cols = 14
colors = [grey, green, blue, purple]
def display_board(screen_width, screen_height, square_size, margin):
counter_pos = [-0.35, -0.52]
direction = 'right'
for row in range(rows):
for col in range(cols):
if (row == 0 or row == rows-1 or col == cols or col == cols-1):
color = random.choice(colors)
pygame.draw.rect(screen, color, (col * square_size + margin + 2 * col, row * square_size + margin + 2 * row, square_size, quare_size))
elif (row == 0 and col > 0 and col < cols - 1) or (row == rows - 1 and col > 0 and col < cols - 1) or (col == 0 and row > 0 nd row < rows - 1) or (col == cols - 1 and row > 0 and row < rows - 1):
color = random.choice(colors)
pygame.draw.rect(screen, color, (col * square_size + margin + 2 * col, row * square_size + margin + 2 * row, square_size, quare_size))
# Draw the counter
pygame.draw.rect(screen, (255, 255, 255), (counter_pos[1] * square_size + margin + 2 * col, counter_pos[0] * square_size + margin + 2 * ow, square_size, square_size))
pygame.display.update()
# Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if direction == 'right':
counter_pos[1] += 1
if counter_pos[1] >= cols - 1:
direction = 'down'
elif direction == 'down':
counter_pos[0] += 1
if counter_pos[0] >= rows - 1:
direction = 'left'
elif direction == 'left':
counter_pos[1] -= 1
if counter_pos[1] <= 0:
direction = 'up'
elif direction == 'up':
counter_pos[0] -= 1
if counter_pos[0] <= 0:
direction = 'right'
display_board(800, 600, 50, 20)
1条答案
按热度按时间o3imoua41#
你必须在每一帧中重绘场景。你必须在应用程序循环中进行绘制。典型的PyGame应用程序循环必须:
pygame.time.Clock.tick
限制每秒帧数以限制CPU使用pygame.event.pump()
或pygame.event.get()
处理事件。blit
所有对象)pygame.display.update()
或pygame.display.flip()
更新显示