'Python Pygame Minesweeper game
I'm trying to make the minesweeper game but I have seen this method to store a grid in a list. how do I make a list inside a list that looks like my grid, For example:
list =
[[x,y],[x,y][x,y],[x,y][x,y],[x,y]
[x,y],[x,y][x,y],[x,y][x,y],[x,y]
[x,y],[x,y][x,y],[x,y][x,y],[x,y]]
My code now is that all the grid is in one list([] and not [][]) I'm kinda new to programming in python so I'm not good at it. Hoping to get help and to solve this as fast as possible, Thank You all!
My code:
import pygame
from pygame.math import Vector2
import random
pygame.init()
HEIGHT = 800
WIDTH = 800
tile_size = 100
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
class Grid:
def __init__(self):
self.pGrid = [Vector2(0, 0)]
for num in range(0, int(WIDTH/tile_size)):
for num2 in range(0, int(HEIGHT/tile_size)):
if(not(num == 0 and num2 == 0)):
self.pGrid.append(Vector2(num2*tile_size, num*tile_size))
def make_grid(self):
for line in range(0, int(WIDTH/tile_size)):
pygame.draw.line(screen, (255, 255, 255), (0, line*tile_size), (WIDTH, line*tile_size))
pygame.draw.line(screen, (255, 255, 255), (line * tile_size, 0), (line*tile_size, HEIGHT))
grid = Grid()
#def bomb_found():
#bomb = pygame.image.load('Images/Bomb.png')
#bomb = pygame.transform.scale(bomb, (100, 100))
bomb = pygame.image.load('Images/Bomb.png')
bomb = pygame.transform.scale(bomb, (100, 100))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((175, 215, 70))
grid.make_grid()
#bomb_found()
screen.blit(bomb, grid.pGrid[20])
pygame.display.update()
clock.tick(60)
pygame.quit()
Solution 1:[1]
You could use list comprehensions for easily creating a nested array of successive integer values.
w, h = 3, 4
[[(i, j) for j in range(h)] for i in range(w)]
#result
[[(0, 0), (0, 1), (0, 2), (0, 3)],
[(1, 0), (1, 1), (1, 2), (1, 3)],
[(2, 0), (2, 1), (2, 2), (2, 3)]]
Solution 2:[2]
Create a list for the column before the inner loop and add the Vector2 objects to this list. Add the column list to the grid after the inner loop:
class Grid:
def __init__(self):
self.pGrid = []
for col in range(WIDTH//tile_size):
column = []
for row in range(HEIGHT//tile_size):
column.append(Vector2(col * tile_size, row * tile_size))
self.pGrid.append(column)
The same using List Comprehensions:
class Grid:
def __init__(self):
self.pGrid = [[Vector2(c*tile_size, r*tile_size) for r in range(HEIGHT//tile_size)] for c in range(WIDTH//tile_size)]
The first subscription returns a column and the second subscription returns an item in the column (a row in the column). e.g.:
col = 3 # 4th column
row = 2 # 3rd row
screen.blit(bomb, grid.pGrid[col][row])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rodrigo Rodrigues |
| Solution 2 |
