大爽Python入门教程 7-2 面向对象编程 使用类`class`组织代码

大爽Python入门公开课教案 点击查看教程总目录

在之前的,第六章第7小节,实现了一个小游戏:
简易单行翻转点灯游戏(Lights Out Flip Game)

其代码是面向过程的,换言之使用函数来组织的。

这里我们把这个游戏,功能不变,换种写法。
使用类来重新组织下代码。

这种写法是不唯一的,有非常多种写法,以下本人只是展示了一种,供大家参考。

游戏文件lights.txt如下

-O-O-O-

1 思路分析

这里用一个类去实现,直接给其起名为LightsGame
这个LightsGame

应该有以下属性(内部容器,存放核心数据)

  • lights: 存储灯的信息的一个列表

值示例如下

['-', 'O', 'O', '-', 'O', 'O', '-']

原来的教程中,其有以下函数

  • get_lights: 读取文件
  • show_light: 展示灯的信息
  • switch_light: 切换灯的开关状态
  • check_all_on: 检查灯是否全部打开
  • main: 主函数或者说主逻辑

我们这里基本参照函数,实现LightsGame类的方法,
除了写法格式上需要调整,有部分的名字或者说实现机制需要简单做一个改动:

  1. get_lights其应该放在类的构造器函数中__init__实现
  2. main改名为run,意思更适合。

2 代码框架

初步代码框架如下

WELCOME = "Welcome to light out flip game!"
ENTER  = "Select one lamp to light On/Off (Enter the index, start from 0): "
WIN = "Great!You light up all the lights"

class LightsGame():
    def __init__(self, light_file):
        pass

    def show(self):
        pass

    def switch_light(self, li):
        pass

    def check_all_on(self):
        pass

    def run(self):
        pass


light_file = "lights.txt"
lg = LightsGame(light_file)
lg.run()

3 初步实现

实现除去run之外的代码,效果如下

WELCOME = "Welcome to light out flip game!"
ENTER  = "Select one lamp to light On/Off (Enter the index, start from 0): "
WIN = "Great!You light up all the lights"

class LightsGame():
    def __init__(self, light_file):
        with open(light_file, 'r') as f:
            line = f.readline()

        self.lights = [item for item in line]

    def show(self):
        print("".join(self.lights))

    def switch_light(self, li):
        if 0 <= li < len(self.lights):
            if self.lights[li] == "-":
                self.lights[li] = "O"
            elif self.lights[li] == "O":
                self.lights[li] = "-"

    def check_all_on(self):
        for light in self.lights:
            if light == "-":
                return False

        return True

    def run(self):
        # TODO: Practice
        pass


light_file = "lights.txt"
lg = LightsGame(light_file)
lg.run()

其中run方法的代码,作为练习,可以先尝试下。

4 总代码

全部实现后如下

WELCOME = "Welcome to light out flip game!"
ENTER  = "Select one lamp to light On/Off (Enter the index, start from 0): "
WIN = "Great!You light up all the lights"

class LightsGame():
    def __init__(self, light_file):
        with open(light_file, 'r') as f:
            line = f.readline()

        self.lights = [item for item in line]

    def show(self):
        print("".join(self.lights))

    def switch_light(self, li):
        if 0 <= li < len(self.lights):
            if self.lights[li] == "-":
                self.lights[li] = "O"
            elif self.lights[li] == "O":
                self.lights[li] = "-"

    def check_all_on(self):
        for light in self.lights:
            if light == "-":
                return False

        return True

    def run(self):
        print(self.lights)

        print(WELCOME)
        while True:
            self.show()

            if self.check_all_on():
                print(WIN)
                return

            li = input(ENTER)

            if li.isdigit():
                li = int(li)
                if 0 <= li < len(self.lights):
                    self.switch_light(li)
                    self.switch_light(li - 1)
                    self.switch_light(li + 1)
                    continue

            print()


light_file = "lights.txt"
lg = LightsGame(light_file)
lg.run()

运行效果和原来的(第六章第7节)是一样的,
这里就不额外展示了。

posted @ 2021-12-21 22:20  大爽歌python编程辅导  阅读(64)  评论(0编辑  收藏  举报