Python通过类的组合模拟街道红绿灯


Posted in Python onSeptember 16, 2020

一,红绿灯揭示板案例思路

1. 创建Traffic_light红绿灯类

(1)静态属性 :

<1> 绿灯时间,<2> 黄灯时间 , <3> 红灯时间, <4> 两块显示时间的电子屏

(2)动态属性

<1> 输入红黄绿时间函数(静态函数),<2> 红黄绿时间倒计时函数 ,
<3> 构造电子屏数字的显示函数,<4> 显示两块电子屏绑定两位数的显示函数
<5> 实例化对象展示电子屏函数

2. 电子屏类的创建(Light):

python中没有数组,因此自己创建函数把获取到的值存放到数组中

(存放内容: 20行,10列的布尔值)

3. input_time(color:str)函数的创建

<1> 导入colorama包并初始化实现windows命令行下颜色字体打印效果
<2> 输入红黄绿时间的字体成对应的颜色
<3> 通过colorama类方法实现输入的红黄绿时间为对应的颜色展示
<4> 对输入的数字进行校验(必须为1-99之间的正数。因为一块电子屏只记录一位数字)
<5> 返回相应的值

4. Countdown数字倒计时函数的创建

<1> 通过while循环让三个灯的状态一直循环持续
<2> 对于红黄绿灯输入的数字进行递减打印流程如下
#流程: 清屏-->打印完后 -->暂停1秒钟-->清屏 -->数字减一后再打印-->再暂停1秒钟-->清屏-->再数字减一打印
<3> 导入time,os,colorama等需要的包

5.build_LED_number函数的创建

之前创建的电子屏是默认False的状态。分别构造0-9的状态在电子屏中True的状态的显示

6.print_LED函数的创建

两块电子屏,分别显示输入时间的第一位和第二位数字.如果数字为单数则前面用零补齐的方法显示。两块屏并排显示每一位数字,从而展示电子版的效果

7.注意事项:

因为我们用到了os,及colorama类。所以最终效果的展示不是在pycharm中展示。而是在windows的cmd命令行中展示。

原因是因为我们代码中调用了os.system("cls")这个清屏命令。在pycharm中是很难做到清屏的效果。

另外在pycharm中对于电子屏的展示效果也不如windows cmd中展示的效果俱佳。因此运行程序是请在windows命令行中运行。

二,红绿灯揭示板代码的呈现

import time
import os
from colorama import init,Fore,Back,Style
#命令行模式字体颜色初始化
init(autoreset=True)

#电子屏类
class Light:
  #构造函数
  def __init__(self):
    self.light = [] #存储行列数组的集合

    #自动初始化
    self.prepare_light()

  def prepare_light(self):
    """
    电子屏的创建
    python中没有数组.因此通过类,函数来创建数组得到一个20行10列的数组
    :return:
    """
    for row in range(20): #20行
      temp = [] # 临时存储每行10个圈
      for col in range(10): #10列
        temp.append(False) #默认灯都是不亮的因此通过布尔类型的False表示不亮的状态
      #把行列排的200个灯的状态存入到light集合中
      self.light.append(temp)

#红绿灯类
class Traffic_light:
  #构造函数,静态属性
  def __init__(self,green_time,yellow_time,rea_time):
    self.green_time = green_time #绿灯时间
    self.yellow_time = yellow_time #黄灯时间
    self.red_time = rea_time #红灯时间

    #通过类的组合调用Light类函数
    self.number01 = Light() #创建第一个电子屏
    self.number02 = Light() #创建第二个电子屏

  #红黄绿等时间倒计时函数
  def countdown(self):
    while True:
      #流程: 清屏-->打印完后 -->暂停1秒钟-->清屏 -->数字减一后再打印-->再暂停1秒钟-->清屏-->再数字减一打印
      for number in range(self.green_time,-1,-1):
        #第一个-1代表取值到0,如果设置0则取值取不到0.第二个-1代表数字减一
        os.system("cls") #清屏
        self.start_display(number,"green") #调用start_display函数传数字及颜色
        time.sleep(1) #停止一秒钟

    # 黄灯倒计时
      for number in range(self.yellow_time,-1,-1):
        os.system("cls") #清屏
        self.start_display(number,"yellow")
        time.sleep(1) #停止一秒钟


    # 红灯倒计时
      for number in range(self.red_time,-1,-1):#第一个-1代表取值到0,如果设置0则取值取不到0.第二个-1代表数字减一
        os.system("cls") #清屏
        self.start_display(number,"red")
        time.sleep(1) #停止一秒钟

  @staticmethod  #静态方法不需要初始化
  def input_time(color:str):
    # 设置全局变量(便于静态方法使用)
    time = ""
    while True:
      if color.lower() in ["green","绿色","绿","绿灯"]:
        print(Fore.GREEN + "请输入绿灯的时间:",end="") #实现打印字体呈现颜色效果
        time = input()
      if color.lower() in ["yellow", "黄色", "黄", "黄灯"]:
        print(Fore.YELLOW + "请输入黄灯的时间:", end="")
        time = input()
      if color.lower() in ["red", "红色", "红", "红灯"]:
        print(Fore.RED + "请输入红灯的时间:", end="")
        time = input()

      #校验输入的是否合规
      if not time.isdigit():
        print("输入的值不符合要求。【要求:必须是1-99之间的正数。】")
        continue
      else:
        time_number = int(time) # 因为time是字符串.拿到数字后转成Int类型再判断
        if time_number < 1 or time_number > 99:
          print("输入的值不符合要求。【要求:必须是1-99之间的正数。】")
          continue
        else:
          return time_number

  def build_LED_number(self,char:str):
    """
    :param char: LED灯数字的构造
    :return: 返回temp_LED这个数组
    """
    temp_LED = Light() #临时创建新的数组

    if char == "0": #构造0
      for row in range(20):
        for col in range(10):
          if row < 2: #最上面两列
            temp_LED.light[row][col] = True
          if row > 17: #最下面两列
            temp_LED.light[row][col] = True
          if col < 2:#最左边两列
            temp_LED.light[row][col] = True
          if col > 7: #最后面两列
            temp_LED.light[row][col] = True

    elif char == "1": #构造1
      for row in range(20):
        for col in range(10):
          if col > 7: #最后面两列
            temp_LED.light[row][col] = True

    elif char == "2": #构造2
      for row in range(20):
        for col in range(10):
          if row < 2: # 最上面两列
            temp_LED.light[row][col] = True
          if col > 7 and row < 9: # 最后面两列
            temp_LED.light[row][col] = True
          if row == 9 or row == 10: # 中间两行
            temp_LED.light[row][col] = True

          if col < 2 and row >10: #左边列
            temp_LED.light[row][col] = True
          if row > 17: # 最下面两列
            temp_LED.light[row][col] = True
    elif char == "3": #构造3
      for row in range(20):
        for col in range(10):
          if row < 2: # 最上面两列
            temp_LED.light[row][col] = True
          if col > 7 : # 最后面两列
            temp_LED.light[row][col] = True
          if row == 9 or row == 10: # 中间两行
            temp_LED.light[row][col] = True
          if row > 17: # 最下面两列
            temp_LED.light[row][col] = True
    elif char == "4": # 构造4
      for row in range(20):
        for col in range(10):
          if col < 2 and row <9: # 最上面两列
            temp_LED.light[row][col] = True
          if col > 7: # 最后面两列
            temp_LED.light[row][col] = True
          if row == 9 or row == 10: # 中间两行
            temp_LED.light[row][col] = True
    elif char == "5": # 构造5
      for row in range(20):
        for col in range(10):
          if row < 2:
            temp_LED.light[row][col] = True
          if col < 2 and row < 9:
            temp_LED.light[row][col] = True
          if row == 9 or row == 10:
            temp_LED.light[row][col] = True
          if col > 7 and row > 10:
            temp_LED.light[row][col] = True
          if row > 17:
            temp_LED.light[row][col] = True
    elif char == "6": # 构造6
      for row in range(20):
        for col in range(10):
          if row < 2:
            temp_LED.light[row][col] = True
          if col < 2:
            temp_LED.light[row][col] = True
          if row == 9 or row == 10:
            temp_LED.light[row][col] = True
          if col > 7 and row > 10:
            temp_LED.light[row][col] = True
          if row > 17:
            temp_LED.light[row][col] = True
    elif char == "7": # 构造7
      for row in range(20):
        for col in range(10):
          if row < 2:
            temp_LED.light[row][col] = True
          if col > 7:
            temp_LED.light[row][col] = True


    elif char == "8": #构造8
      for row in range(20):
        for col in range(10):
          if row < 2: #最上面两列
            temp_LED.light[row][col] = True
          if row > 17: #最下面两列
            temp_LED.light[row][col] = True
          if row == 9 or row == 10: # 中间两行
            temp_LED.light[row][col] = True
          if col < 2:#最左边两列
            temp_LED.light[row][col] = True
          if col > 7: #最后面两列
            temp_LED.light[row][col] = True

    elif char == "9": # 构造9
      for row in range(20):
        for col in range(10):
          if row < 2: # 最上面两列
            temp_LED.light[row][col] = True
          if col < 2 and row < 9:
            temp_LED.light[row][col] = True
          if row > 17: # 最下面两列
            temp_LED.light[row][col] = True
          if row == 9 or row == 10: # 中间两行
            temp_LED.light[row][col] = True
          if col > 7: # 最后面两列
            temp_LED.light[row][col] = True

    #返回值
    return temp_LED

  def print_LED(self,color:str):
    for row in range(20):
      #打印第一个数
      for col01 in range(10):
        if self.number01.light[row][col01] == True:
          if color == "green":
            print(Fore.GREEN + "●",end="")
          elif color == "yellow":
            print(Fore.YELLOW + "●",end="")
          elif color == "red":
            print(Fore.RED + "●",end="")
        else:
          print(" ",end="") # 两个全角空格 注释:○占用的字符相当于两个全角空格的占位
      print("\t",end="")
      #打印第二个数
      for col02 in range(10):
        if self.number02.light[row][col02] == True:
          if color == "green":
            print(Fore.GREEN + "●",end="")
          elif color == "yellow":
            print(Fore.YELLOW + "●",end="")
          elif color == "red":
            print(Fore.RED + "●",end="")
        else:
          print(" ",end="")
      #换行
      print()

  def start_display(self,number:int,color:str):
    """
    电子屏展示
    :param number:电子屏上展示的数字
    :param color: 电子屏上展示的颜色
    :return:
    """
    number_str = "%02d" % number #传进来的数字2位显示
    self.number01 = self.build_LED_number(number_str[0]) #把数字的第一位给第一个电子屏
    self.number02 = self.build_LED_number(number_str[1]) #把数字的第二位给第二个电子屏

    #在电子屏上显示
    self.print_LED(color)

if __name__ == "__main__":
  green_time = Traffic_light.input_time("绿灯")
  yellow_time = Traffic_light.input_time("黄灯")
  red_time = Traffic_light.input_time("红灯")

  #实例化
  traffic01 = Traffic_light(green_time,yellow_time,red_time)
  traffic01.countdown()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现zencart产品数据导入到magento(python导入数据)
Apr 03 Python
Python 'takes exactly 1 argument (2 given)' Python error
Dec 13 Python
python实现的二叉树定义与遍历算法实例
Jun 30 Python
Python 查找字符在字符串中的位置实例
May 02 Python
Python数据可视化教程之Matplotlib实现各种图表实例
Jan 13 Python
【python】matplotlib动态显示详解
Apr 11 Python
Python控制台输出时刷新当前行内容而不是输出新行的实现
Feb 21 Python
Python模块相关知识点小结
Mar 09 Python
python+gdal+遥感图像拼接(mosaic)的实例
Mar 10 Python
Django数据结果集序列化并展示实现过程
Apr 22 Python
Python利用imshow制作自定义渐变填充柱状图(colorbar)
Dec 10 Python
Python采集爬取京东商品信息和评论并存入MySQL
Apr 12 Python
python如何绘制疫情图
Sep 16 #Python
如何用Python绘制3D柱形图
Sep 16 #Python
Python Merge函数原理及用法解析
Sep 16 #Python
简单了解Python字典copy与赋值的区别
Sep 16 #Python
python 服务器运行代码报错ModuleNotFoundError的解决办法
Sep 16 #Python
pycharm2020.2 配置使用的方法详解
Sep 16 #Python
python Matplotlib模块的使用
Sep 16 #Python
You might like
php addslashes及其他清除空格的方法是不安全的
2012/01/25 PHP
合并ThinkPHP配置文件以消除代码冗余的实现方法
2014/07/22 PHP
php中静态类与静态变量用法的区别分析
2015/01/15 PHP
php实现头像上传预览功能
2017/04/27 PHP
PHP那些琐碎的知识点(整理)
2017/05/20 PHP
PHP面向对象五大原则之依赖倒置原则(DIP)详解
2018/04/08 PHP
基于CI(CodeIgniter)框架实现购物车功能的方法
2018/04/09 PHP
PHP一致性hash分布式算法封装类定义与用法示例
2018/08/04 PHP
wordpress自定义标签云与随机获取标签的方法详解
2019/03/22 PHP
php fread函数使用方法总结
2019/05/28 PHP
php 多进程编程父进程的阻塞与非阻塞实例分析
2020/02/22 PHP
php+iframe 实现上传文件功能示例
2020/03/04 PHP
[原创]图片分页查看
2006/08/28 Javascript
childNodes.length与children.length的区别
2009/05/14 Javascript
Dojo 学习笔记入门篇 First Dojo Example
2009/11/15 Javascript
JS防止用户多次提交的简单代码
2013/08/01 Javascript
JavaScript动态添加列的方法
2015/03/25 Javascript
JavaScript中的普通函数与构造函数比较
2015/04/07 Javascript
拥有一个属于自己的javascript表单验证插件
2016/03/24 Javascript
详解JavaScript中this的指向问题
2017/01/20 Javascript
微信小程序模板之分页滑动栏
2017/02/10 Javascript
深究AngularJS之ui-router详解
2017/06/13 Javascript
Vue.js常用指令的使用小结
2017/06/23 Javascript
JS+Canvas绘制动态时钟效果
2017/11/10 Javascript
实例讲解javascript实现异步图片上传方法
2017/12/05 Javascript
JavaScript实现读取与输出XML文件数据的方法示例
2018/06/05 Javascript
jQuery 同时获取多个标签的指定内容并储存为数组
2018/11/20 jQuery
微信小程序非跳转式组件授权登录的方法示例
2019/05/22 Javascript
[02:01]BBC DOTA2国际邀请赛每日综述:八强胜者组鏖战,中国队喜忧参半
2014/07/19 DOTA
Django自定义分页效果
2017/06/27 Python
Python产生一个数值范围内的不重复的随机数的实现方法
2019/08/21 Python
解决python3.6用cx_Oracle库连接Oracle的问题
2020/12/07 Python
如何写出高质量、高性能的MySQL查询
2014/11/17 面试题
大学教师个人总结
2015/02/10 职场文书
pytorch分类模型绘制混淆矩阵以及可视化详解
2022/04/07 Python
Python+SeaTable实现计算两个日期间的工作日天数
2022/07/07 Python