使用python在pygame中制作8 * 8棋盘 [英] Make a 8*8 chessboard in pygame with python
本文介绍了使用python在pygame中制作8 * 8棋盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用python在pygame中制作一个棋盘.仅带有for循环的棋盘.我尝试了几种方法来做到这一点,但是我没有弄清楚到底是什么.这是我的代码:
I want to make a chessboard in pygame with python. Just only the chessboard with for loops. I tried in several ways to do this but i didn't figured out what exactly it will be. Here is my code:
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代码将是什么.我只是想在屏幕上显示一个棋盘.就是这样.
Now i need an expert suggestion what it will be with python code. I just wanna show a chessboard in my screen. Thats it.
推荐答案
可能的解决方案,也许不是最优雅的,但是您可以循环创建正方形
Possible solution, maybe not the most elegant, but you can create the squares in a loop
#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()
这篇关于使用python在pygame中制作8 * 8棋盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文