简体   繁体   中英

Drawing squares in diagonal line instead of in grid pattern in pygame

import random
import pygame
# Initializing the main varibales:
width = 600
height = 600
cell_size = 10
cols = int(width / cell_size)
rows = int(height / cell_size)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

pygame.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Conway's Game of Life - Clavio Steltman")


def dead_state(w, h):
    # returns 2d array


def random_state(w, h):
    # returns a 2d array with values between 0 and 1


def draw_cell(x, y, state):
    x_pos = x * cell_size
    y_pos = x * cell_size

    if state[x][y] == 1:
        color = BLACK
    elif state[x][y] == 0:
        color = WHITE

    rect = (x_pos, y_pos, cell_size, cell_size)
    pygame.draw.rect(screen, color, rect, 1)
    pygame.display.update()


def main():
    initial_board = random_state(cols, rows)
    print(initial_board)
    screen.fill((255, 255, 255))
    while True:
        for x in range(cols):
            for y in range(rows):
                draw_cell(x, y, initial_board)
    pygame.display.update()


main()

The code above prints sqaures in a diagonal line from the top left to the bottom right, instead of in a grid pattern. Can someone please tell me what I am doing wrong? Does it have something to do with my fore loops or something like that? I'm pretty lost at this point.

It's a typo (In fact many problems are)

Just change

    x_pos = x * cell_size
    y_pos = x * cell_size

to

    x_pos = x * cell_size
    y_pos = y * cell_size

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM