2025年3月31日 星期一 乙巳(蛇)年 正月初一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

使用Python编写数独游戏自动出题程序

时间:12-25来源:作者:点击数:17

数独是一个很好玩的游戏,可以锻炼推理能力。下面的代码可以自动生成数独游戏题目。

  • from random import shuffle, randrange
  • def generate():
  • # 初始网格
  • result = []
  • line = list(range(1,10))
  • for i in range(9):
  • result.append(line)
  • line.append(line.pop(0))
  • # 注意,这里的切片很重要
  • line = line[:]
  • # Python允许函数的嵌套定义
  • def switchRows(first, second):
  • # 这里的括号和换行不是必须的
  • # 只是为了方便手机阅读
  • (result[first],
  • result[second]) =\
  • (result[second],
  • result[first])
  • def switchColumns(first, second):
  • for index in range(9):
  • (result[index][first],
  • result[index][second]) =\
  • (result[index][second],
  • result[index][first])
  • # 随机交换行
  • randomRows = list(range(9))
  • shuffle(randomRows)
  • for i in range(0,7,2):
  • switchRows(randomRows[i],\
  • randomRows[i+1])
  • # 随机交换列
  • randomColumns = list(range(9))
  • shuffle(randomColumns)
  • for i in range(0,7,2):
  • switchColumns(randomColumns[i],\
  • randomColumns[i+1])
  • # 随机清空一些格子
  • num = randrange(25, 50)
  • positions = {(randrange(9),randrange(9))\
  • for i in range(num)}
  • for row, col in positions:
  • result[row][col] = ' '
  • return result
  • def output(grids):
  • print('+'+'-+'*9)
  • for row in range(9):
  • line = '|'.join(map(str,grids[row]))
  • line = line.join(['|']*2)
  • print(line)
  • print('+'+'-+'*9)
  • grids = generate()
  • output(grids)

运行结果一:

运行结果二:

运行结果三:

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门