Python game programming (a), "Guess the Number" game

Some people say that the task-driven approach to learning will be more efficient, it was said interest is the best teacher.

So I'm going to design a good number of debugging previous games, teaching introductory Python do for themselves.

The following is an analysis of the existing code, while analysis of the role played by each line of code in the game, code analysis related to the programming syntax.

By designing a small game to learn the Python programming language, first of all in the most basic of "Guess" game start with a detailed description of each line of code, and explain other features and attributes of the code, learn programming in the preparation of the game.

(A) Source:

#This is a Guess The Number game. 
import random

#赋值过程自动创建变量
guessesTaken = 0

print("Hello! What is your name?")
myName = input()

number = random.randint(1, 20)
print("Well," + myName + ", I an thinking of a number between 1 and 20.")

for i in range(6):
    print("Take a guess.")
    guess = input()
    guess = int(guess)
    
    if guess < number:
        print("Your guess is too low.")
        
    if guess > number:
        print("Your guess is too high.")
        
    if guess == number:
        break    #跳出for循环
    
if guess == number:
    guessesTaken = i
    guessesTaken = str(guessesTaken)
    print("Good job," + myName + "Your guessed my number in " + guessesTaken +" guesses!")
    
if guess != number:
    number = str(number)
    print("Nope. The number I was thinking of was" + number +".")

operation result:

runfile('D:/Z/Python/Python游戏编程/游戏编程代码/猜数字.py', wdir='D:/Z/Python/Python游戏编程/游戏编程代码')
Hello! What is your name?

低头写作业
Well,低头写作业, I an thinking of a number between 1 and 20.
Take a guess.

13
Your guess is too low.
Take a guess.

16
Your guess is too low.
Take a guess.

18
Your guess is too high.
Take a guess.

177
Your guess is too high.
Take a guess.

17
Good job,低头写作业Your guessed my number in 4 guesses!

The game uses the most basic grammar. A detailed analysis of the following:

(B) Detailed analysis:

Game Contents:

  • import statements;
  • Module;
  • the randint () function;
  • for statement
  • Statement block
  • str () function, int () function, float () function;
  • Boolean type;
  • Comparison operator;
  • = == and distinction;
  • if statement;

First introduced to the random module can call the random.randint () function, which will generate a random number for a user to guess.

#导入random模块
import random  

Introducing random module so that the program can call the random.randint () function, which will generate a random number for a user to guess.

import statements:
Statement is an instruction to execute certain actions, unlike expression that calculates a value.
For example assignment: to store a value to a variable.

Python includes many built-in functions, some stored in the module, use the import statement after our program, you can use these functions a.

guessesTaken = 0

New variable to hold the number of times a player guesses before. Python variables are created directly after the assignment.

print("Hello! What is your name?")
myName = input()

Call to print () function, the string parameter passed to it to the screen. It functions like a program in a small program. input () function used to obtain the player's name, attention input () function is passed a string input by the player.

number = random.randint(1, 20)

Call module the randint random () function generates a random number, assigned to the variable number. randint (1, 20) code function returns an integer between 1 and 20 and assigned to the variable number.

print("Well," + myName + ", I an thinking of a number between 1 and 20.")

Call print () function to welcome the player based on the player's name, and tells the player guesses range of numbers.

for i in range(6):
    print("Take a guess.")
    guess = input()
    guess = int(guess)
    
    if guess < number:
        print("Your guess is too low.")
        
    if guess > number:
        print("Your guess is too high.")
        
    if guess == number:
        break    #跳出for循环

for loop:

Through the code for loop over and over again, the execution of the code will be repeated six times. for statement starts with the keyword for, followed by a new variable, in keywords, to range () function is called once, range () function to specify the number of cycles to be executed, in addition to including a colon.

break out of for loop statement immediately block the jump to the first line after the end of the for loop.

for statement indicating the start of a cycle, the cycle may be repeated to execute the same code. When the program execution to a for statement, it goes into the back of the block for statement After running all the blocks of code, execution will return to the top of the block of statements, and run all the code again. With each execution cycle, called iteration. It can be understood as a for statement: "The following statement block code execution in a certain number of times."

Organization statement block:

Python statement with different code blocks to determine the indentation (i.e. body statements) boundary flow control structure. Each line of code in a block of statements in the indentation has the same value and the first line of code blocks of statements, by changing the start and end indents statement a new statement block, the block can be nested statement block. After the line, any line has the same or more indent code, are considered part of the statement block.

    guess = int(guess)

int () function takes one parameter and returns an integer parameter. Although it is possible to pass a string int () function, but can not pass any string, the string passed to int () must be made numbers.
Similar, float () and str () functions return a string and floating point types.
Using int (), float () and str () function can accept value of a data type, and returns a value of another data type.

type of data

Each value in Python, belong to a data type. Python data types include integer, floating point, string and Boolean data type. Boolean data type has only two values: True or False, the first letter of the two values ​​must be capitalized, the rest lowercase.

Comparison operators

Comparison operator compares two values, and will be a Boolean value of True or Flase.

Understood in comparison operator code

a = 21
b = 10
c = 0
 
if ( a == b ):
   print ("1 - a 等于 b")
else:
   print ("1 - a 不等于 b")
 
if ( a != b ):
   print ("2 - a 不等于 b")
else:
   print ("2 - a 等于 b")
 
if ( a < b ):
   print ("3 - a 小于 b")
else:
   print ("3 - a 大于等于 b")
 
if ( a > b ):
   print ("4 - a 大于 b")
else:
   print ("4 - a 小于等于 b")
 
# 修改变量 a 和 b 的值
a = 5;
b = 20;
if ( a <= b ):
   print ("5 - a 小于等于 b")
else:
   print ("5 - a 大于  b")
 
if ( b >= a ):
   print ("6 - b 大于等于 a")
else:
   print ("6 - b 小于 a")

Output

1 - a 不等于 b
2 - a 不等于 b
3 - a 大于等于 b
4 - a 大于 b
5 - a 小于等于 b
6 - b 大于等于 a

Python operator further comprises arithmetic operators, assignment operators, and other logical operators.

Wherein "equals" assignment operator (=) for assignment, to the value stored in the variable; "equal to" comparison operator sign (==) for expression to determine whether two values ​​are equal.

The if statement
if statement starts with the keyword if, followed by a colon condition and, as a result of which conditions are just another name for True or False expressions only. if statement back condition is True, the code block is executed after the colon, if block of code in Flase is skipped.

if guess == number:
    guessesTaken = i
    guessesTaken = str(guessesTaken)
    print("Good job," + myName + "Your guessed my number in " + guessesTaken +" guesses!")
    
if guess != number:
    number = str(number)
    print("Nope. The number I was thinking of was" + number +".")

String value can only strings and other connection, if an integer and a string concatenation error.

The game will introduce here.

Outbreak, they can only stay at home, school delay. To stop learning is also closed. For updated one day before the summary content learning, but also continue to learn new content before school starts.

reference:

  1. Rookie Tutorial
  2. http://inventwithpython.com/invent4thed/chapter3.html
  3. "Python Game Programming Quick Start" fourth edition, AI Sweigart with, Li Qiang translation
Released nine original articles · won praise 1 · views 419

Guess you like

Origin blog.csdn.net/weixin_45755966/article/details/103994226