iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >学习python:实例3.终端版拼图游戏
  • 597
分享到

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

终端实例拼图游戏 2023-01-31 06:01:01 597人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

效果:输入数字进行移动,当数字排列成为【1,2,3,4,5,6,7,8】游戏胜利!代码:# 拼图 from sys import exit from os import system from random import shuffle

效果:

输入数字进行移动,当数字排列成为【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.检测输入是否有效

--结束END--

本文标题: 学习python:实例3.终端版拼图游戏

本文链接: https://www.lsjlt.com/news/189477.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作