前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Python编写数独游戏自动出题程序

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

作者头像
Python小屋屋主
发布2018-04-16 15:21:48
2.1K0
发布2018-04-16 15:21:48
举报
文章被收录于专栏:Python小屋Python小屋

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

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)

运行结果一:

运行结果二:

运行结果三:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-08-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档