Python 9x9 数独游戏:规则生成,随机空位,挑战你的逻辑!
以下是一个简单的 Python 数独游戏实现:
import random
def generate_random_sequence():
# 生成一个随机数列
sequence = []
empty_spaces = random.randint(15, 26)
for i in range(9):
row = []
for j in range(9):
if empty_spaces > 0:
row.append(' ')
empty_spaces -= 1
else:
# 生成符合规则的数字
valid_numbers = [x for x in range(1, 10) if x not in row and x not in [sequence[k][j] for k in range(i)]]
if valid_numbers:
row.append(random.choice(valid_numbers))
else:
# 如果没有符合规则的数字,则重新生成数列
return generate_random_sequence()
sequence.append(row)
return sequence
def print_sequence(sequence):
# 打印数列
for row in sequence:
print(' '.join([str(x) for x in row]))
def play_game():
print('按S开始游戏,按C结束游戏,按R重新生成数列')
while True:
choice = input().lower()
if choice == 's':
sequence = generate_random_sequence()
print_sequence(sequence)
while True:
# 填空位为可输入空格
row_index = int(input('请输入行号: ')) - 1
col_index = int(input('请输入列号: ')) - 1
if sequence[row_index][col_index] == ' ':
number = int(input('请输入数字: '))
if number not in sequence[row_index] and number not in [sequence[i][col_index] for i in range(9)]:
sequence[row_index][col_index] = number
print_sequence(sequence)
else:
print('请输入符合规则的数字!')
else:
print('该位置已经有数字了!')
elif choice == 'r':
sequence = generate_random_sequence()
print_sequence(sequence)
elif choice == 'c':
break
else:
print('无效的选择!')
play_game()
注意,这只是一个简单的实现,可能还有一些细节需要进一步完善,比如输入的数字是否在合法范围内、用户输入的行号和列号是否在合法范围内等。
原文地址: https://www.cveoy.top/t/topic/o4aS 著作权归作者所有。请勿转载和采集!