我是初学者,并为玩数独游戏写了一个小脚本
我能够检查行和列条件,但我无需帮助检查方形条件,即3x3方格中只应有一个唯一数字
如果有人能帮助我缩小条件的大小,我将不胜感激,请解释我如何创建随机数据板生成随机数,因为我已经采用静态板
TF()
我想为它制作GUI版所以请推荐我一种方法。
提前致谢 以下是此处提供的代码链接https://drive.google.com/file/d/0B0mzB3WBm-8-VzJua1BLakExajQ/view?usp=sharing
board=[[5,7,3,6,9,4,2,1,8],[9,2,4,7,8,1,3,5,'X'],['X',1,6,3,5,'X',7,9,4],[3,8,5,4,2,7,9,6,1],[1,9,2,5,3,6,8,4,7],[4,6,7,9,1,8,5,2,3],[7,3,1,'X',4,5,6,8,'X'],
['X',5,8,1,7,9,4,3,2],[2,4,9,8,6,3,'X',7,5]]#simple sudoku board for testing
def initiator():#print the board and start redirect to the funtion
for i in range(0,9):
print str(board[i])+"\n"
rc_checker()
def find_xs():#find whether there are any remaining spaces to fill
count = 0
for i in range(0,9):
for j in range(0,9):
if board[i][j] == 'X':
count+=1
if count>0:
return 1
else:
for i in range(0,9):
print str(board[i])+"\n"
print "Thanks for playing"
def rc_checker():#checks whether inputted row and column are valid
if find_xs()==1:
for i in range(0,9):
print str(board[i])+"\n"
print "Give the row and column"
r = int(input())
c = int(input())
if r<10 and c<10:
r=r-1
c-=1
validator(r,c)
def validator(r,c):#validate whether the field is empty and redirects accordingly
if board[r][c]=='X':
print "Enter the value"
val = int(input())
if val>0 and val <10:
tf(r,c,val)
rc_checker()
else:
print "The feild is not empty please try again"
rc_checker()
def tf(r,c,val):#checking if the inputted value is repeated in corresponding row or column
i = 0
r1 = 0
c1 = 0
if val!=board[r][i] and val!=board[r][i+1] and val!=board[r][i+2] and val!=board[r][i+3] and val!=board[r][i+4] and val!=board[r][i+5] and val!=board[r][i+6] and val!=board[r][i+7] and val!=board[r][i+8] and val!=board[r1][c] and val!=board[r1+1][c] and val!=board[r1+2][c] and val!=board[r1+3][c] and val!=board[r1+4][c] and val!=board[r1+5][c] and val!=board[r1+6][c] and val!=board[r1+7][c] and val!=board[r1+8][c]:
print "Value entered is correct"
board[r][c]=val#value is set
else:
print "Invalid value Retry"
board[r][c]='X'
def main():#welcome message
print "Welcome to sudoku game"
print "Fill all 'X' with valid input"
initiator()
main()
答案 0 :(得分:0)
你问的问题:
<强> 1。如何检查方块?
<强> 2。如何减小条件的大小?
第3。如何生成随机数?
<强> 4。如何制作GUI版本?
答案。
<强> 1。和2.
首先,检查这些条件的一种简单方法是:
val = 6
my_list = [2, 4, 3, 1, 'X', 7, 8, 9, 5] # this might be your row for example
if val in my_list:
print 'Invalid value Retry'
else:
print 'Value entered is correct'
根据具体情况,您必须采用不同的方式构建my_list:
获取行的列表
r = 3
my_list = board[r]
获取列
的列表c = 4
my_list = [row[4] for row in board]
获取正方形的列表
# where the squares are numbered as follows:
# 0 1 2
# 3 4 5
# 6 7 8
s = 3 # second row, first column
r = int(s/3) # r = 1
c = s%3 # c = 0
my_list = [element for row in board[r*3:r*3+3]
for element in row[c*3:c*3+3]]
这里我使用了两个重要的功能:
确保理解它们,因为它们非常有用。
第3 强>
您可以使用randint
import random
random.randint(0,8) # random integer in range [0, 8], including both end points.
<强> 4 强>
有很多方法可以做到,我没有足够的经验告诉你。我个人非常喜欢这个tutorial。如果你想用GUI编写一个简单的游戏,它可能会很有用。在使用GUI开始项目之前,我的建议是学习课程。