用python在pygame中制作一个8*8的棋盘

2024-04-16 09:01:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python在pygame中做一个棋盘。只有带for循环的棋盘。我试了好几种方法来做这件事,但我不知道具体是什么。这是我的代码:

import pygame
pygame.init()

#set color with rgb
white,black,red = (255,255,255),(0,0,0),(255,0,0)

#set display
gameDisplay = pygame.display.set_mode((800,600))

#caption
pygame.display.set_caption("ChessBoard")

#beginning of logic
gameExit = False

lead_x = 20
lead_y = 20

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

#For loop for chessboard 

#draw a rectangle
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,20,20])
pygame.display.update()


#quit from pygame & python
pygame.quit()
quit()

现在,我需要一个专家的建议,它将与python代码。我只想在屏幕上显示一个棋盘。就这样。


Tags: 代码eventfor棋盘displaypygamequitblack
3条回答

可能的解决方案,也许不是最优雅的,但是你可以在一个循环中创建正方形

#Size of squares
size = 20

#board length, must be even
boardLength = 8
gameDisplay.fill(white)

cnt = 0
for i in range(1,boardLength+1):
    for z in range(1,boardLength+1):
        #check if current loop value is even
        if cnt % 2 == 0:
            pygame.draw.rect(gameDisplay, white,[size*z,size*i,size,size])
        else:
            pygame.draw.rect(gameDisplay, black, [size*z,size*i,size,size])
        cnt +=1
    #since theres an even number of squares go back one value
    cnt-=1
#Add a nice boarder
pygame.draw.rect(gameDisplay,black,[size,size,boardLength*size,boardLength*size],1)

pygame.display.update()

您可以使用^{}循环遍历嵌套for循环中的颜色,只需将next(colors)传递给pygame.draw.rect。我会创建一个背景曲面,并在程序启动时将矩形绘制到上面,然后在while循环中快速移动背景冲浪,因为这比单独快速移动矩形更有效。

import itertools
import pygame as pg


pg.init()

BLACK = pg.Color('black')
WHITE = pg.Color('white')

screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()

colors = itertools.cycle((WHITE, BLACK))
tile_size = 20
width, height = 8*tile_size, 8*tile_size
background = pg.Surface((width, height))

for y in range(0, height, tile_size):
    for x in range(0, width, tile_size):
        rect = (x, y, tile_size, tile_size)
        pg.draw.rect(background, next(colors), rect)
    next(colors)

game_exit = False
while not game_exit:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            game_exit = True

    screen.fill((60, 70, 90))
    screen.blit(background, (100, 100))

    pg.display.flip()
    clock.tick(30)

pg.quit()

更有效的方法是在初始化时绘制一次板,只需将其点到表面:

cellSize = 20
board = Surface((cellSize * 8, cellSize * 8))
board.fill((255, 255, 255))
for x in range(0, 8, 2):
    for y in range(0, 8, 2):
        pygame.draw.rect(board, (0,0,0), (x*size, y*size, size, size))

然后在循环中,首先绘制板面:

gameDisplay.blit(board, board.get_rect())
# Draw your game pieces

相关问题 更多 >