从零开始写代码 2023-12-06 22:16 采纳率: 69.2%
浏览 5
已结题

python扫雷小游戏,列表索引超范围

img

想实现的效果是可以通过这个函数实现自定义棋盘大小

def easy(rows, cols):
    global ROWS
    global COLS
    ROWS = rows
    COLS = cols
    game_loop(10)

# 在主程序中调用easy函数时,可以传入自定义的行数和列数
# 例如,想要一个15x15的棋盘
easy(15, 15)

报错内容:

发生异常: IndexError
list assignment index out of range
  File "C:\Users\范先生\Desktop\大二\python作业\2240919135范力维课程设计\game\clear_mines.py", line 47, in show_set_up
    board[row][col] = -1
  File "C:\Users\范先生\Desktop\大二\python作业\2240919135范力维课程设计\game\clear_mines.py", line 122, in game_loop
    m.show_set_up()
  File "C:\Users\范先生\Desktop\大二\python作业\2240919135范力维课程设计\game\clear_mines.py", line 171, in easy
    game_loop(10)
  File "C:\Users\范先生\Desktop\大二\python作业\2240919135范力维课程设计\game\clear_mines.py", line 174, in <module>
    easy()
IndexError: list assignment index out of range
问题函数
```python
class mines:
    def __init__(self,num) -> None:
        self.NUM_mines=num
# 随机布置地雷
    def show_set_up(self):
        global ROWS
        global COLS
        global board
        mines = random.sample(range(ROWS * COLS), self.NUM_mines)
    # print(show)
        for mine in mines:
            row = mine // COLS
            col = mine % COLS
            board[row][col] = -1
# # 计算每个方格周围的地雷数量
    def count_mines(self):
        global ROWS
        global COLS
        global board
        global revealed
        for row in range(ROWS):
            for col in range(COLS):
                if board[row][col] == -1:
                    continue
                count = 0
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if row+i >= 0 and row+i < ROWS and col+j >= 0 and col+j < COLS and board[row+i][col+j] == -1:
                                count += 1
                board[row][col] = count



完整代码

```python
import pygame
import random
import time
# from Firework_modle import firework
# 游戏参数,全局变量
ROWS = 10
COLS = 10
CELL_SIZE = 30
WINDOW_WIDTH = COLS * CELL_SIZE
WINDOW_HEIGHT = ROWS * CELL_SIZE
FONT_SIZE = 20
game_over = False
show = 0

BG_COLOR = (255, 255, 255)
LINE_COLOR = (0, 0, 0)
MINE_COLOR = (0, 0, 0)
COVERED_COLOR = (192, 192, 192)
FONT_COLOR = (0, 0, 0)
text_color=(255,0,0)

# 创建游戏地图
board = [[0] * COLS for _ in range(ROWS)]
revealed = [[False] * COLS for _ in range(ROWS)]

window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
window_rect = window.get_rect()
pygame.display.set_caption("扫雷游戏")
# NUM_MINES=10
# 初始化 Pygame
pygame.init()

# 雷
class mines:
    def __init__(self,num) -> None:
        self.NUM_mines=num
# 随机布置地雷
    def show_set_up(self):
        global ROWS
        global COLS
        global board
        mines = random.sample(range(ROWS * COLS), self.NUM_mines)
    # print(show)
        for mine in mines:
            row = mine // COLS
            col = mine % COLS
            board[row][col] = -1
# # 计算每个方格周围的地雷数量
    def count_mines(self):
        global ROWS
        global COLS
        global board
        global revealed
        for row in range(ROWS):
            for col in range(COLS):
                if board[row][col] == -1:
                    continue
                count = 0
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if row+i >= 0 and row+i < ROWS and col+j >= 0 and col+j < COLS and board[row+i][col+j] == -1:
                                count += 1
                board[row][col] = count

# 加载图标
icon = pygame.image.load("图标.png")
pygame.display.set_icon(icon)

# 加载字体
font = pygame.font.Font(None, FONT_SIZE)
# txt_image=font.render('100',True,None,text_color)
# txt_rect=txt_image.get_rect()

def game_map_drawing():
    global ROWS
    global COLS
    global WINDOW_WIDTH
    global WINDOW_HEIGHT
    global window
    global window_rect
    map_width = COLS * CELL_SIZE
    map_height = ROWS * CELL_SIZE
    start_x = (WINDOW_WIDTH - map_width) // 2
    start_y = (WINDOW_HEIGHT - map_height) // 2

    for row in range(ROWS):
        for col in range(COLS):
            if revealed[row][col]:
                if board[row][col] == -1:
                    pygame.draw.rect(
                        window, MINE_COLOR, (start_x + col*CELL_SIZE, start_y + row*CELL_SIZE, CELL_SIZE, CELL_SIZE))
                else:
                    pygame.draw.rect(
                        window, COVERED_COLOR, (start_x + col*CELL_SIZE, start_y + row*CELL_SIZE, CELL_SIZE, CELL_SIZE))
                    text = font.render(str(board[row][col]), True, FONT_COLOR)
                    text_rect = text.get_rect(
                        center=(start_x + col*CELL_SIZE+CELL_SIZE//2, start_y + row*CELL_SIZE+CELL_SIZE//2))
                    window.blit(text, text_rect)
            else:
                pygame.draw.rect(
                    window, COVERED_COLOR, (start_x + col*CELL_SIZE, start_y + row*CELL_SIZE, CELL_SIZE, CELL_SIZE))

            pygame.draw.rect(window, LINE_COLOR, (start_x + col*CELL_SIZE,
                             start_y + row*CELL_SIZE, CELL_SIZE, CELL_SIZE), 1)

# 游戏胜利条件检查
def is_win(show,n):
    # print(show)
    global ROWS
    global COLS
    if show == (ROWS*COLS-n):
       return True
    else:
       return False 

# 游戏循环

def game_loop(n):
    global game_over
    show=0
    m = mines(n)
    m.show_set_up()
    m.count_mines()
    print(f'雷的总量为{m.NUM_mines}')
    while not game_over:
        window.fill(BG_COLOR)
    # 绘制游戏地图
        game_map_drawing()
        pygame.display.flip()

        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    x, y = event.pos
                    col = x // CELL_SIZE
                    row = y // CELL_SIZE
                    # print(revealed[row][col])
                    if  revealed[row][col] == False:
                      revealed[row][col] = True
                      #  print(show)
                      show = show + 1
                elif event.button == 3:  # 右键点击
                    x, y = event.pos
                    col = x // CELL_SIZE
                    row = y // CELL_SIZE
                    revealed[row][col] = False
                    board[row][col] = 9
                # 游戏失败
                if board[row][col] == -1:
                    pygame.display.set_caption("游戏结束!你踩到了地雷!")
                    print('游戏结束!你踩到了地雷!')
                    game_over = True
                    time.sleep(5)
                    pygame.quit()
                elif is_win(show,n):
                    # 游戏胜利
                    pygame.display.set_caption("恭喜!你成功扫雷!")
                    print('恭喜!你成功扫雷!')
                    game_over = True
                    time.sleep(5)
                    pygame.quit()
                    # firework.gofirework()
def easy():
  global ROWS
  global COLS
  ROWS=15
  COLS=15
  game_loop(10)

if __name__=='__main__':
    easy()


  • 写回答

2条回答 默认 最新

  • 浪客 2023-12-06 23:39
    关注
    
    def easy():
        global ROWS
        global COLS
        ROWS=15
        COLS=15
        global board
        global revealed
        board = [[0] * COLS for _ in range(ROWS)] # 调整数组大小,不然15越界,下同
        revealed = [[False] * COLS for _ in range(ROWS)]
        game_loop(10)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月15日
  • 已采纳回答 12月7日
  • 创建了问题 12月6日