“Text interface” (created by Python interpolation string formatting)

Python interpolates string formats to create program text interfaces.

(This note is suitable for coders who are familiar with Python strings)


[The details of learning are a joyful process]

  • Python official website: python cutting edge. Unfortunately it’s the original English version. So, I want to practice English reading. “>https://www.python.org/

  • Free: Free for big names “Bible” tutorial “ python complete self-study tutorial” is not just as simple as the basics…
    Address: https://lqpybook.readthedocs.io/

Self-study is not a mysterious thing, A person’s lifelong self-study time is always longer than that of studying in school, and the time without a teacher is always longer than the time with a teacher.
Hua Luogeng

  • My CSDN homepage, My HOT blog, My Python learning personal memo
  • Highly recommended for good articles, Lao Qi Classroom


Wait for the wind to come, it is better to chase the wind...


Python interpolation string formatting


Text interface


(Create a “program interface”)

Quality score of this article:


96
This article address:
https://blog.csdn.net/m0_57158496/article/details/134045543

CSDN quality score query entrance: http://www.csdn.net/qc


Directory

  • ◆?Text interface
    • 1. Topic description
    • 2. Algorithm analysis
      • 2.1 Attribute variables
      • 2.2 Parameter collection
      • 2.3 Game Menu
      • 2.4 Game Game
      • 2.5 Game paused
      • 2.6 Exit the game
      • 2.7 Judgment of victory and defeat
      • 2.8 Loop Game
      • 2.9 Start Game
    • 3. Complete source code

◆?Text Interface

1. Title description

  • Screenshot of question description

[The question comes from the CSDN Q&A community question “Program Text Interface”]


Back to table of contents

2. Algorithm analysis

This note focuses on explaining “Text Interface“. The sample code borrows the code I typed when answering this question. According to my understanding and preference, some of the “code logic” has been changed: let two players live in the same category, so that they are not so divided. The total scores of the two players are tallied separately, and at the end of the game, the winner is determined. In this way, what I think is a “more reasonable code” is achieved.

Use Python to interpolate string formatting, easily and freely, making print() more cute and attractive.

2.1 Attribute variables

class Game:
    clear = '\033[2J' # Linux clear screen string.
    wait = f"{<!-- -->'(Any key to continue...)':^34}\\
" # Pause prompt string.
    rule = range(100) # Alternative random score.
    topScore = countScoreA = countScoreB = 0 # The highest score and the initial value of the player's total score.


Back to table of contents

2.2 Parameter collection

  • The __init__ class magic method collects parameters: name, game name; *player collects two player names into a list.
    def __init__(self, name, *player):
        self.name = name
        self.pA, self.pB = player


Back to table of contents

2.3 Game Menu

  • Screenshot of code running effect

    Menu selection error

    The advantage of the for loop printing menu lines is that adding a menu does not require adding code. You only need to append the menu display content string to the for traversal sequence. That’s it.

    def menu(self):
        print(f"{<!-- -->self.clear}\\
{<!-- -->'':=^40}\\
\\
{<!-- -- >f' {<!-- -->self.name} ':^38}\\
\\
{<!-- -->'':~^40}\\
" )
        
        for k, i in enumerate(['Game starts', 'Game pauses', 'Game ends']):
            print(f"{<!-- -->f'{<!-- -->k + 1}. {<!-- -->i}':^36}")

        print(f"\\
{<!-- -->'':=^40}\\
")


Back to table of contents

2.4 Game Game

  • Screenshot of code running effect

    def startGame(self):
        from random import choices
        print(f"{<!-- -->self.clear}\\
{<!-- -->f' {<!-- -->self.name}game':=^36 }\\
\\
{<!-- -->f' {<!-- -->self.pA} and {<!-- -->self.pB} start the game':.^ 31}")
        a, b = choices(self.rule, k=2) # Randomly give game scores (0~100).
        self.countScoreA + = a
        self.countScoreB + = b
        score = a if a > b else b
        self.topScore = score if self.topScore < score else self.topScore # Update the highest score of the recorded game.
        print(f"\\
{<!-- -->f' The current highest score in a single round: {<!-- -->self.topScore:>3} ':~^32}\\
 \\
{<!-- -->f' {<!-- -->self.pA}Current score: {<!-- -->a:>3} ':^33}\ n{<!-- -->f' {<!-- -->self.pB}Current score: {<!-- -->b:>3} ':^33}\\
\ \
{<!-- -->'':=^40}")
        input(self.wait)


Back to table of contents

2.5 Game paused

  • Screenshot of code running effect

    def pauseGame(self):
        print(f"\\
{<!-- -->f' Pause {<!-- -->self.name} game ':.^34}\\
")
        input(self.wait)


Back to table of contents

2.6 Exit the game

  • Screenshot of code running effect

    Character color setting uses the magical \033 control code (you can click on the blue text to jump and browse my study notes), which is only valid on Linux. Windows
    A string will be printed. If you run it in win, please remove it from the code.
    def exitGame(self):
        print(self.clear)

        if not self.topScore:
            print(f"\\
{<!-- -->f' The game hasn't started yet!':~^32}\\
")
            input(self.wait)
            self.play()
 
        green = '\033[32m'
        off = '\033[0m'
        yellow = '\033[33m'
        print(f"\\
{<!-- -->f' {<!-- -->self.name}game':=^36}\\
{<!-- --> green}\\
{<!-- -->' Exited the game':.^35}\\
{<!-- -->off}{<!-- -->yellow}\ n{<!-- -->f' Looking forward to playing next time':~^33}\\
{<!-- -->off}")


Back to table of contents

2.7 Judgement of victory and defeat

  • Screenshot of code running effect

    def showScore(self):
        winer = self.pA if self.countScoreA > self.countScoreB else self.pB
        print(f"{<!-- -->self.clear}\\
{<!-- -->f' {<!-- -->self.name}game':=^36 }\\
\\
{<!-- -->' Game is Over! ':.^40}\\
\\
{<!-- -->f' The highest score in a single game :{<!-- -->self.topScore:>3} ':~^32}\\
\\
{<!-- -->f' {<!-- -->self. pA} score: {<!-- -->self.countScoreA} ':^36}\\
{<!-- -->f' {<!-- -->self.pB} score: {<!-- -->self.countScoreB} ':^36}\\
\\
{<!-- -->f' {<!-- -->winer} won!' :*^35}\\
\\
{<!-- -->'':=^40}\\
")


Back to table of contents

2.8 Loop Game

  • Call the function module according to the menu if branch to complete the menu instructions
    Call yourself to implement menu loop.
    def play(self):
        self.menu()
        choice = input(f"{<!-- -->'Please choose:':>12}")

        if choice == '1':
            self.startGame()
        elif choice == '2':
            self.pauseGame()
        elif choice == '3':
            self.exitGame()
            self.showScore()
            exit()
        else:
            print(f"\\
{<!-- -->f' Wrong menu selection!':~^34}\\
")
            input(self.wait)
        
        self.play() # Call yourself to implement the game menu loop.


Back to table of contents

2.9 Start the game

  • The class instance calls the play function to start the game
if __name__ == '__main__':
    Game("Mine Sweeper", "Xiao Su", "Xiao Shuai").play() # Start the game.


Back to table of contents

3. Complete source code

(The source code is long, click here to skip the source code)

#!/sur/bin/nve python
# coding: utf-8


class Game:
    clear = '\033[2J' # Linux clear screen string.
    wait = f"{'(Any key to continue...)':^34}\\
"
    rule = range(100) # Alternative random score.
    topScore = countScoreA = countScoreB = 0 # Initial score value.
    
    def __init__(self, name, *player):
        self.name = name
        self.pA, self.pB = player
 
    def menu(self):
        print(f"{self.clear}\\
{'':=^40}\\
\\
{self.name} ':^38}\\
\\
{'':~^40}\\
" )
        
        for k, i in enumerate(['Game starts', 'Game pauses', 'Game ends']):
            print(f"{f'{k + 1}. {i}':^36}")
        print(f"\\
{'':=^40}\\
")


    def startGame(self):
        from random import choices
        print(f"{<!-- -->self.clear}\\
{<!-- -->f' {<!-- -->self.name}game':=^36 }\\
\\
{<!-- -->f' {<!-- -->self.pA} and {<!-- -->self.pB} start the game':.^ 31}")
        a, b = choices(self.rule, k=2) # Randomly give game scores (0~100).
        self.countScoreA + = a
        self.countScoreB + = b
        score = a if a > b else b
        self.topScore = score if self.topScore < score else self.topScore # Update the highest score of the recorded game.
        print(f"\\
{<!-- -->f' The current highest score in a single round: {<!-- -->self.topScore:>3} ':~^32}\\
 \\
{<!-- -->f' {<!-- -->self.pA}Current score: {<!-- -->a:>3} ':^33}\ n{<!-- -->f' {<!-- -->self.pB}Current score: {<!-- -->b:>3} ':^33}\\
\ \
{<!-- -->'':=^40}")
        input(self.wait)

    def pauseGame(self):
        print(f"\\
{<!-- -->f' Pause {<!-- -->self.name} game ':.^34}\\
")
        input(self.wait)

    def exitGame(self):
        print(self.clear)

        if not self.topScore:
            print(f"\\
{<!-- -->f' The game hasn't started yet!':~^32}\\
")
            input(self.wait)
            self.play()
 
        green = '\033[32m'
        off = '\033[0m'
        yellow = '\033[33m'
        print(f"\\
{<!-- -->f' {<!-- -->self.name}game':=^36}\\
{<!-- --> green}\\
{<!-- -->' Exited the game':.^35}\\
{<!-- -->off}{<!-- -->yellow}\ n{<!-- -->f' Looking forward to playing next time':~^33}\\
{<!-- -->off}")

    def showScore(self):
        winer = self.pA if self.countScoreA > self.countScoreB else self.pB
        print(f"{<!-- -->self.clear}\\
{<!-- -->f' {<!-- -->self.name}game':=^36 }\\
\\
{<!-- -->' Game is Over! ':.^40}\\
\\
{<!-- -->f' The highest score in a single game :{<!-- -->self.topScore:>3} ':~^32}\\
\\
{<!-- -->f' {<!-- -->self. pA} score: {<!-- -->self.countScoreA} ':^36}\\
{<!-- -->f' {<!-- -->self.pB} score: {<!-- -->self.countScoreB} ':^36}\\
\\
{<!-- -->f' {<!-- -->winer} won!' :*^35}\\
\\
{<!-- -->'':=^40}\\
")

    def play(self):
        self.menu()
        choice = input(f"{'Please choose:':>12}")

        if choice == '1':
            self.startGame()
        elif choice == '2':
            self.pauseGame()
        elif choice == '3':
            self.showScore()
            input(self.wait)
            self.exitGame()

            exit()
        else:
            print(f"\\
{f' Wrong menu selection!':~^34}\\
")
            input(self.wait)
        
        self.play() # Call yourself to implement the game menu loop.


if __name__ == '__main__':
    Game("Mine Sweeper", "Xiao Su", "Xiao Shuai").play() # Start the game.


Back to top


Previous article:? Classic circular proposition: One hundred coins and one hundred chickens(One cub has five coins, the female has three coins, and the chick has three coins. Only one coin; a hundred coins, a hundred chickens, a hundred chickens, a hundred coins)
Next article:?

My HOT blog:

A total of 246 blog post note information were collected this time, with a total reading volume of 40.46w and an average reading volume of 1644. 16 blog post note index links with a reading volume of no less than 4,000 have been generated. Data collection was completed at 2023-10-12 05:41:03, taking 4 minutes and 41.10 seconds.

  1. First experience of ChatGPT domestic mirror site: chat, Python code generation, etc.
    ( 59262 reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/129035387
    Like: 126 Dislike: 0 Collection: 798 Reward: 0 Comment: 71
    This blog post was first published on 2023-02-14 23:46:33 and modified at the latest on 2023-07-03 05:50:55.
  2. The magic code that changes the nickname of QQ group
    ( 58086 reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122566500
    Like: 24 Dislike: 0 Collection: 83 Reward: 0 Comment: 17
    This blog post was first published at 2022-01-18 19:15:08 and was modified at the latest at 2022-01-20 07:56:47.
  3. pandas data type DataFrame
    ( 9173 reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124525814
    Like: 6 Dislike: 0 Collection: 31 Reward: 0 Comment: 0
    This blog post was first published on 2022-05-01 13:20:17 and modified at the latest on 2022-05-08 08:46:13.
  4. Personal information extraction (string)
    ( 7215 Reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124244618
    Like: 1 Dislike: 0 Collection: 13 Reward: 0 Comment: 0
    This blog post was first published on 2022-04-18 11:07:12 and modified at the latest on 2022-04-20 13:17:54.
  5. 7 ways to implement reverse order (descending order) of Python lists
    ( 7161 Reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/128271700
    Like: 5 Dislike: 0 Collection: 22 Reward: 0 Comment: 8
    This blog post was first published at 2022-12-11 23:54:15 and was modified at the latest at 2023-03-20 18:13:55.
  6. Roman Numeral Converter | Roman Numeral Generator
    ( 7035 Reading)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122592047
    Like: 0 Dislike: 0 Collection: 1 Reward: 0 Comment: 0
    This blog post was first published at 2022-01-19 23:26:42 and was modified at the latest at 2022-01-21 18:37:46.
  7. Python string displayed in the center
    ( 6966 Reading)
    Blog address: https://blog.csdn.net/m0_57158496/article/details/122163023
    Like: 1 Dislike: 0 Collection: 7 Reward: 0 Comment: 1
    Notes for this blog
  8. Recursive implementation and for implementation of Fibonacci sequence
    ( 5523 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122355295
    Like: 4 Dislike: 0 Collection: 2 Reward: 0 Comment: 8
    Notes for this blog
  9. python clear screen
    ( 5108 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/120762101
    Like: 0 Dislike: 0 Collection: 8 Reward: 0 Comment: 0
    Notes for this blog
  10. Exercise: String statistics (pit: fstring error report)
    ( 5103 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121723096
    Like: 0 Dislike: 0 Collection: 1 Reward: 0 Comment: 0
    Notes for this blog
  11. Carriage return, line feed, and carriage return and line feed
    ( 5093 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/123109488
    Like: 1 Dislike: 0 Collection: 2 Reward: 0 Comment: 0
    This blog post was first published at 2022-02-24 13:10:02 and modified at the latest at 2022-02-25 20:07:40.
  12. Exercise: Nim game (smart version/fool style? Man-machine battle)
    ( 4943 reads)
    Blog address: https://blog.csdn.net/m0_57158496/article/details/121645399
    Like: 14 Dislike: 0 Collection: 42 Reward: 0 Comment: 0
    Notes for this blog
  13. Password strength detector
    ( 4323 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121739694
    Like: 1 Dislike: 0 Collection: 4 Reward: 0 Comment: 0
    This blog post was first published at 2021-12-06 09:08:25 and modified at the latest at 2022-11-27 09:39:39.
  14. Exercise: Generate 100 random positive integers
    ( 4274 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122558220
    Like: 1 Dislike: 0 Collection: 6 Reward: 0 Comment: 0
    This blog post was first published at 2022-01-18 13:31:36 and was modified at the latest at 2022-01-20 07:58:12.
  15. My Python.color() (Python color printing control)
    ( 4159 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/123194259
    Like: 2 Dislike: 0 Collection: 8 Reward: 0 Comment: 0
    This blog post was first published on 2022-02-28 22:46:21 and modified at the latest on 2022-03-03 10:30:03.
  16. Roman numeral converter (implemented using the modulus of the value of the Roman numeral construction element)
    ( 4149 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122608526
    Like: 0 Dislike: 0 Collection: 0 Reward: 0 Comment: 0
    This blog post was first published at 2022-01-20 19:38:12 and modified at the latest at 2022-01-21 18:32:02.


Recommended conditions
Reads exceeded 3,000


(For more hot blogs, please click on the blue text to jump to read)


Back to top



Lao Qi's comic avatar

Excellent articles:

  • Highly recommended for good articles:Qi Wei’s Manuscript “Python Complete Self-Study Tutorial” FreeSerial(The manuscript has been completed and compiled into a book. There is also a PDF version for permanent sharing on Baidu Netdisk. Click Jump to download for free.)
  • Three major features of OPP: property in encapsulation
  • Understand python’ through built-in objects
  • regular expression
  • The role of “*” in python
  • Python complete self-study manual
  • walrus operator
  • `!=` in Python is different from `is not`
  • The right way to learn programming

Source: Lao Qi Classroom


Back to top

◆ Python Getting Started Guide[Python 3.6.3]

Highly recommended for good articles:

  • A high-quality creator in the full-stack field – [Hanlao](still a student at a domestic university) blog post “Non-technical article – about English and how to “Correct Questions”, “English” and “Knowing Questions” are two powerful tools for learning programming.
  • [Applicable fields of 8 major programming languages] Don’t rush to choose linguistic programming first, first look at what they can do
  • Good habits of reliable programmers
  • The three major elements of “Function function, end condition, and function equivalence” in the high-quality and good article by the boss Shuaidi will help you understand recursion.

CSDN Practical Tips Blog:

  • 8 Python practical tips that are extremely useful
  • python ignore warning
  • Python code writing specifications
  • Python’s docstring specification (standard way of writing documentation)