The examples in this article share the specific code of python to realize the guessing game for your reference. The specific content is as follows
**1. Problem description: **
Use python to develop a small number guessing game. The program randomly generates a number between 0 and 1024. The user enters the guessed number, and the program tells the user whether the guess is big or small. The user who guesses right within a certain number of times wins, otherwise the user loses.
Each round of the game requires users to enter a username
The program will continue to run until the user enters "3" to stop the game. Enter "1" before each round of the game to view user input history.
**2. Knowledge points involved: **
1、 Randomly generate numbers, design random number module of python.
2、 The user enters a number and the program outputs the result. Involving python input and output modules.
3、 The program automatically proceeds to the next round, involving the python loop module.
4、 Judging user input involves the p ython condition judgment module.
5、 Query user input history, involving python dictionary and list modules.
Three, code construction
# Call the random number generation module
import random
# Start the game control module
def start():
name =input('Please enter your name:')if name =='drop out':returnif name not in history:
history[name]=[]
answer = random.randint(0,1024)try_to_guess(name, answer)
def try_to_guess(name ,answer): #Guess the main module of the game
try_nume =0while try_nume <100:
guess_answer =int(input('Please enter a number you guessed:'))if guess_answer < answer :print('The number you entered is less than the correct answer')
elif guess_answer answer:print('The number you entered is greater than the correct answer')else:print('Congratulations on your correct answer!')
history[name].append('success!')break
try_nume +=1else:print('Too many wrong guesses, the game fails!')
history[name].append('failure!')
# History module
history ={}#Create collection, store history
def show_history():for name, data in history.items():print('user:{},The record is as follows:{}'.format(name, data))
# Prevent input options that are not available
def default():print('input error! please enter again')print('='*40)if __name__ =='__main__':
select_dict ={'1': start,'2': show_history,'3': exit}while True:
select =input('1.Start the game\n2.history record\n3.exit the game\nPlease enter the number to choose:')
select_dict.get(select,default)()
Four, debugging and running
Regardless of success or failure, press 1 to start the game, press 2 to view the record, press 3 to exit the game, and enter other characters to report an error.
For more wonderful articles about python games, please click to view the following topics:
python tetris game collection
Python classic games summary
Python WeChat Jump Jump Game Collection
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts