效果:

输入数字进行移动,当数字排列成为【1,2,3,4,5,6,7,8】游戏胜利!

wKiom1iVUDzyRyokAAAysfPJ8PA897.gif


代码:

# 拼图
from sys import exit
from os import system
from random import shuffle

# 游戏胜利
def victory(counter):
    system('cls')
    print('完成拼图共花了%d步!' % counter)
    print('''
* * * * *
* 6 6 6 *
*victory*
* !!!!! *
* * * * *''')
    exit()

# 定义 main
def main():
    boxs = [' ','1','2','3','4','5','6','7','8']
    shuffle(boxs)   # 打乱列表
    counter = 0     # 计数器

    while True:
        boxs_num = boxs
        system('cls')
        print('Counter:', counter)
        print('''
* * * * *
* %s %s %s *
* %s %s %s *
* %s %s %s *
* * * * *'''
        % tuple(boxs_num))

        ins = input('''输入数字进行移动, (0 退出游戏)
\> ''')
        if ins == '0':
            exit()
        if int(ins) in range(1,9):  # 判断输入是否有效
            kong_index = boxs_num.index(' ')
            num_index = boxs_num.index(ins)
            if (kong_index - num_index) in (-1,1,3,-3):
                boxs_num[num_index],boxs_num[kong_index] = boxs_num[kong_index],boxs_num[num_index]
                counter += 1        # 数字移动后计数器加1

        if boxs_num == [' ','1','2','3','4','5','6','7','8'] or boxs_num == ['1','2','3','4','5','6','7','8',' ']:
            victory(counter)

# 调用main
main()

*优化

2017-01-23 添加os.system模块,实现每次操作前清屏

2017-02-04 1.增加计数器,2.检测输入是否有效