尝试制作康威的生活游戏,我如何让矩形适合pygame中的网格正方形


import pygame, copy,random
w,h = 500,500
cellsize=5
cells=[]
pygame.init()
width, height = w/cellsize, h/cellsize
width = int(width)
height=int(height)
dis= pygame.display.set_mode((w,h))
dis.fill((0,0,0))
randomBool=[]
cellPc=0.001
count = totalcount = 0
for y in range(h):
randomBool.append([])
for x in range(w):
if random.random() < cellPc:
randomBool[y].append(True)
count += 1
else:
randomBool[y].append(False)
totalcount +=1
#sojipo ajs;koojihhasuiio h;asjioasddfoiaidhoiiosaiof

running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
quit()
for x in range(0, w, cellsize):
pygame.draw.line(dis,(123,123,123),(x,0),(x,h))
for y in range(0, h, cellsize):
pygame.draw.line(dis,(123,123,123),(0,y),(w,y))
pygame.display.update()
for y in range(h):
for x in range(w):
if randomBool[y][x]==True:
pygame.draw.rect(dis,(255,0,0),(x,y,cellsize,cellsize))

我以为它只适合网格,但矩阵不起作用。我对python中矩阵的概念还不太熟悉,所以我在这方面还不是很在行。我怎样才能让它们在网格上匹配。如有任何帮助,我将不胜感激。

使用//(楼层除法)运算符计算行数和列数:

width, height = w/cellsize, h/cellsize

width, height = w // cellsize, h // cellsize

网格的列数和行数是width×height而不是w×h。单元格的左上角位置为(col * cellsize, row * cellsize):

for row in range(height):
for col in range(width):
if randomBool[row][col]==True:
x, y = col * cellsize, row * cellsize
pygame.draw.rect(dis, (255,0,0), (x, y, cellsize, cellsize))

最新更新