首先有一个错字:color = red
而不是colour = red
.
无论如何,你必须改变你的游戏逻辑。对于未单击的单元格使用值 0 和 2,对于已单击的单元格使用值 1 和 3。将网格的所有字段初始化为 0。通过将 2 分配给随机单元格,在网格上放置随机炸弹。
当单击值为 0 的单元格时,将其值更改为 1。当单击带有炸弹(值 2)的单元格时,将其值更改为 3:
while not done:
# [...]
for event in pygame.event.get():
# [...]
elif event.type == pygame.MOUSEBUTTONDOWN:
# Change the x/y screen coordinates to grid coordinates
column = event.pos[0] // (width + margin)
row = event.pos[1] // (height + margin)
if grid[row][column] == 2:
print('Boom')
grid[row][column] = 3
if grid[row][column] == 0:
grid[row][column] = 1
print("Click ", event.pos, "Grid coordinates: ", row, column)
当您绘制网格时,所有单元格都必须绘制为白色。除了单元格的值为 1 之外。在本例中,它的颜色为绿色。如果单元格的值为 3,则其颜色为红色:
while not done:
# [...]
#Draw the grid
for row in range(10):
for column in range(10):
color = white
if grid[row][column] == 1:
color = green
elif grid[row][column] == 3:
color = red
cell_rect = ((margin + width) * column + margin, (margin + height) * row + margin, width, height)
pygame.draw.rect(gameD, color, cell_rect)
完整示例:
#initilising
import pygame
import random
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
width = 20
height = 20
margin = 5#gap between
current = 0
bank = 0
turnnumber = 0
grid = []
for row in range(10):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(10):
grid[row].append(0)
pygame.init()
GameR = [600,600]
gameD = pygame.display.set_mode(GameR)
pygame.display.set_caption("Pirate Game")
done = False
clock = pygame.time.Clock()
#-------------------------------------------------------------------------------------------------------
#FUNCTIONS
def bombs():
for i in range(5):
row = random.randrange(10)
column = random.randrange(10)
grid[row][column] = 2
print(row,column)
bombs()
#---------------------------------------------------------------------------
#MAIN LOOP:
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bombs()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print("Dont Press that")
elif event.type == pygame.MOUSEBUTTONDOWN:
# Change the x/y screen coordinates to grid coordinates
column = event.pos[0] // (width + margin)
row = event.pos[1] // (height + margin)
if grid[row][column] == 2:
print('Boom')
grid[row][column] = 3
if grid[row][column] == 0:
grid[row][column] = 1
print("Click ", event.pos, "Grid coordinates: ", row, column)
gameD.fill(black)
#Draw the grid
for row in range(10):
for column in range(10):
color = white
if grid[row][column] == 1:
color = green
elif grid[row][column] == 3:
color = red
cell_rect = ((margin + width) * column + margin, (margin + height) * row + margin, width, height)
pygame.draw.rect(gameD, color, cell_rect)
clock.tick(60)
pygame.display.flip()
pygame.quit()