我正在python中創建生命遊戲。我不確定我是否正確地做了。Pygame的生命遊戲
get_cell函數對我來說不太合適。我也想在count_neighbors函數中使用這個函數。
我在做什麼錯,還有什麼可以做得更好?
import pygame
import time
import sys
HEIGHT = 50
WIDTH = 50
SCALE = 10
SCREEN = pygame.display.set_mode((WIDTH*SCALE, HEIGHT*SCALE))
def create_blank():
"""Creates a HEIGHT x WIDTH list containing all zero's. The inner lists
will all be WIDTH long and the outer list will HEIGHT long."""
board = [[0]*WIDTH]*HEIGHT
return board
def get_cell(board, x, y):
"""Returns the game board at position x,y , this is 1 if the cell at that
position is alive and 0 if the cell is dead. If the x or y parameters are
out of bounds (not valid coordinates), the function returns 0."""
for x in range(WIDTH):
for y in range(HEIGHT):
return board[y][x]
else:
return 0
def count_neighbours(board, x, y):
"""Counts the number of alive neighbours around the position x,y , including
diagonal neighbours. Does not include the cell itself."""
count = 0
for i in range(x-1,x+2):
for j in range(y-1,y+2):
if not(i == x and j == y):
count += int(mat[i][j])
def update(board):
"""Creates a new board copy and applies the game rules to each cell using
the old board. Does not modify the old board. Returns the new board."""
if(count < 2 or count > 3):
return 0
elif count == 3:
return 1
else:
return mat[i][j]
我沒有得到任何錯誤和板出現,但卻仍不能右看看我...
以何種方式它不看你的權利? –
我不確定它是否有效,因爲我無法真正測試。這個功能對您來說似乎是否可行,並且確實需要做些什麼? –
在'get_cell'中,用範圍中的值替換'x'和'y'。這些將從零開始計數。所以,你總是會返回'board [0] [0]'。真的,你應該返回'board [x] [y]'而不通過範圍循環。你可以先檢查'x'和'y'是否有效,否則返回'0'。 –