效果:
輸入數字進行移動,當數字排列成爲【1,2,3,4,5,6,7,8】遊戲勝利!
代碼:
# 拼圖 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.檢測輸入是否有效