前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >学习python:实例3.终端版拼图游戏

学习python:实例3.终端版拼图游戏

作者头像
py3study
发布2020-01-08 10:42:47
3660
发布2020-01-08 10:42:47
举报
文章被收录于专栏:python3python3

效果:

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

wKiom1iVUDzyRyokAAAysfPJ8PA897.gif
wKiom1iVUDzyRyokAAAysfPJ8PA897.gif

代码:

代码语言:javascript
复制
# 拼图
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.检测输入是否有效

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

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