The basic programming methodology of top-down design and bottom-up execution is illustrated by this example

IPO description

The examples used are abstracted from the general rules of various ball games, and the convention is as follows:

  • The two players start the match, with one player serving first.
  • Players then alternate shots until a score can be judged (this process is called a round –> hence the idea of extending this to a turn-based online game).
  • The round ends when a player fails to make a legal shot
    • The player who fails to hit the ball loses the turn
    • If the server loses the turn, the right to serve goes to the other side
    • If the receiving side loses, the serving side of the turn continues to serve.
  • Anyway, at the end of each round, the team that won that round serves.
  • The first player to reach 15 points wins the game

Input and output

  • Input: the ability probability of two players A and B and the number of simulated matches
  • Output: Player A, the probability of each winning the match

Design steps:

  1. An introductory informational form of the print program;printInfo()
  2. Obtain program running parameters: proA, proB, n;getInputs()
  3. Using player A and player B’s ability value, simulate n games;simNGames()
  4. Output players A and B win matches and probability;printSummary()

The problem is divided into four separate functions whose names, output parameters, and expected return values are determined

Top-down design process (think of it as the process of discovering and abstracting functionality)

The general idea: determine the input and output, and refine the code from the algorithm description at each level down, with the details encapsulated by functions

Specific steps

  1. The algorithm is expressed as a series of small problems
  2. Design interfaces for each small problem
  3. The algorithm is refined by expressing it as a number of small problems associated with the interface
  4. Repeat the process for each small problem

code

import random
def printIntro() :
    print("This program simulates some kind of competitive competition involving players A and B.")
    print("The capability values (expressed as A decimal between 0 and 1) required for the program to run.")
 
def getInputs() :
    a = eval(input("Please enter player A's ability value (0-1) :"))
    b = eval(input("Please enter player B's ability value (0-1) :"))
    n = eval(input("Number of simulated games:"))
    return a, b, n
 
def printSummary(winsA, winsB) :
    n = winsA + winsB
    print("Competitive analysis begins. Simulate {} matches.".format(n))
    print("Player A wins {} matches by {:0.1%}".format(winsA, winsA/n))
    print("Player B wins {} matches by {:0.1%}".format(winsB, winsB/n))
 
def gameOver(a, b) :
    return a == 15 or b == 15
    
def simOneGame(probA, probB) :
    scoreA, scoreB = 0.0
    serving = "A"
    while not gameOver(scoreA, scoreB):
        if serving == "A":
            if random.random() < probA:
                scoreA += 1
            else:
                serving = "B"
        else:
            if random.random() < probB:
                scoreB += 1
            else:
                serving = "A"
    return scoreA, scoreB
 
def simNGames(n ,probA, probB) :
    winsA, winsB = 0.0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB
 
def main() :
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB = simNGames(n, probA, probB)
    printSummary(winsA, winsB)
main()
Copy the code

Comment the code

Use reserved words to reference the Random library
import random

# Output print necessary instructions
def printIntro() :
    print("This program simulates some kind of competitive competition involving players A and B.")
    print("The capability values (expressed as A decimal between 0 and 1) required for the program to run.")

# Get user input, encapsulate or hide input prompt statement and input format details, calls can get A, B capability values and the number of sessions
def getInputs() :
    a = eval(input("Please enter player A's ability value (0-1) :"))#eval() restricts the user from entering a number. Try :-except: is used for exception handling
    b = eval(input("Please enter player B's ability value (0-1) :"))
    n = eval(input("Number of simulated games:"))
    return a, b, n

# Output results
def printSummary(winsA, winsB) :
    n = winsA + winsB
    print("Competitive analysis begins. Simulate {} matches.".format(n))#fomat() converts numbers into strings
    print("Player A wins {} matches by {:0.1%}".format(winsA, winsA/n))
    print("Player B wins {} matches by {:0.1%}".format(winsB, winsB/n))

Wrap this function to allow you to modify different rules for different matches
def gameOver(a, b) :
    return a == 15 or b == 15

# Simulate every game according to the rules (core code block)
def simOneGame(probA, probB) :
    scoreA, scoreB = 0.0
    serving = "A"# Default A holds the ball
    while not gameOver(scoreA, scoreB):
        if serving == "A":
            if random.random() < probA:#random.random() is used to generate a number of random characters from 0 to 1:0 <= n < 1.0
                scoreA += 1
            else:
                serving = "B"
        else:
            if random.random() < probB:If random()
                scoreB += 1
            else:
                serving = "A"
    return scoreA, scoreB

# Count, count the results of each game
def simNGames(n ,probA, probB) :
    winsA, winsB = 0.0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB
 
The #main() function is called the top-level structure, and it builds the framework of the program, encapsulating and hiding the details through functions
def main() :
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB = simNGames(n, probA, probB)
    printSummary(winsA, winsB)
main()
Copy the code

The results

This program simulates A competitive competition involving players A and B0to1Please enter contestant A's ability value (0-1) :0.5Please enter contestant B's ability value (0-1) :0.4Simulated games:25Competitive analysis begins, co-simulation25The match was won by Player A17Game, ratio68.0Contestant B won8Game, ratio32.0%
Copy the code

The operation screenshot