Basic python exercises: several simple games and basic python exercises

Source: Internet
Author: User

Basic python exercises: several simple games and basic python exercises

Document Introduction

Using python to write "guess numbers", "guess words", and "Who is undercover" games, you can quickly get started with python programming, including python syntax/LIST/tuples/dictionaries/process control/library functions.

Environment Parameters

Linux platform, python3.4. You need to compile python3.4 in linux, so that you can save the file in. py format when writing a python program and add the execution permission to run it on the terminal (the principle is the same as that of shell scripts), which is very convenient.

Ps: The posted python program code is also compatible in windows, but the running method is not a command line, but through python software. You can download and install the python software on the official website and click the open link. During learning, you can directly input the python Statement on the python software to print the result. That is to say, python can be run without compilation, many people also call it the "script" language.

Design implementation

Guess number

Many people have played the guess digital game during their dinner. Someone randomly generates a number in the specified range, and then others can guess it one by one. The interval keeps narrowing down until the guess is in progress.

Here, the guess digital game uses a program to replace the person who generates the number. The program algorithm is designed as follows:

1. enter the number range ---> 2. random Number in the system generation interval ---> 3. enter the number you want to guess ---> 4. compare the player's guess and answer, and prompt ---> 5. 3 is returned if you have not guessed it.

There are few codes, as shown below:

#!/usr/local/bin/python3import randombot=int(input('Set range bottom\n'))top=int(input('Set range top\n'))rand=random.randint(bot,top)print ('Random number in ['+str(bot)+','+str(top)+'] generated!')num=int(input('###Guess the number###\n'))cnt=1while (num!=rand):if (num<rand):print('*_* Lower than the answer')else:print('T_T Higher than the answer')num=int(input('###Guess the number###\n'))cnt=cnt+1print('^_^ You get the answer with [%d] times'%cnt)

The first line is to let the linux system know that this is a python3 program. random is a library function that generates random numbers. Note that python has strict format requirements, because it does not use {} but uses indentation to determine the process.

Through this, you can master the basic syntax and writing rules. Next, we will try again to use phrases and loop control.

Guess words

You should have watched the TV program, and many people have also played it. The rule is that one person watches words and draws corresponding actions and says some tips, the other person can't see the words and needs to guess through the comparison action. During the guess process, the host determines whether the words comply with the rules.

The algorithm for a group of gamers to guess words is designed as follows:

1. start timing ---> 2. guess words ---> 3. if you are correct, add 1 to the correct number and return to 2. If you want to skip or foul the number, directly return to 2. If you have timed out, directly jump to 3 ---> 3. count the number of correct questions after 10 cycles or after the end of time

If a player has a num group, the system executes the num cycle of the above process. Of course, the number of words in group x must be prepared, because the words in each group are different.

The Code volume is small, as shown below:

#! /Usr/local/bin/python3import timenum = int (input ('How many players \ n') guessWord = [] correct = [] # definition list, num + 10 does not want to make the guessWord subscript invalid for I in range (0, num + 10): guessWord. append (0) correct. append (0) wordNum = 10 guessWord [0] = ['logging', 'baby sponge ', 'charming', 'golden chicken Independence ', 'gorging,' sleep ', 'stand-alone group', 'Dancing output', 'chapel', 'Crossing fire'] guessWord [1] = ['eyebrow dance ', 'league of legends', 'twist yangge', 'peat beautiful female ', 'Big swing and big swing ', 'smile and smiling', 'marketing ', 'wide-eyed and small-eyed', 'narcissism ', 'virg'] guessWord [2] = ['dog jump wall ', 'laugh in your alignge', 'Eyes inspect', 'frown *, 'zuogu Right panian ', 'Kung pao chicken ding', 'raise the flag', 'crush ', 'smelly soot', 'rob'] flag = 'n' for I in range (0, num): start = time. time () for k in range (0, wordNum): # display the word print ('% d. % s') % (k + 1, guessWord [I] [k]) flag = input ('Answer, correct, enter y, Skip, enter any key ') end = time. time () sec = end-start # statistical time if (110 <= sec <= 120): print ('Still 10 seconds') if (sec> = 120 ): print ('time! Game Terminator ') breakif (flag = 'y'): correct [I] = correct [I] + 1 continueelse: continuestr_temp = (' % d Number of correct answers: % D') % (I + 1, correct [I]) print (str_temp)

In fact, words can be read from independent files to facilitate update and management, the following describes how to use a dictionary to obtain the undercover word "who is undercover.

Who is undercover

Who is undercover is also a game that many people like. At least three or more people can play the game, which is roughly divided into several stages: 1. allocate civilian words and undercover words ---> 2. players speak in sequence ---> 3. based on the speech, I voted who is undercover ---> 4. players with the most votes are out ---> 5. when an out-of-game player is an undercover player, the civilian team wins. If the out-of-game player is a civilian, the team is killed and continues Step 4. When the remaining civilian team is only one, the undercover team wins.

In special cases, if two or more gamers have the same number of votes, the same number of gamers will speak again and then all of them will vote for these players.

Program Design Idea: Enter the number of players num and the number of players is 0 ~ Num-1, then define the list of three elements containing num: Word List, calculate the list of players' votes, the list of dead players. The list subscript ranges from 0 ~ Num-1, randomly generate the number of x in the range, representing that Player x is undercover, and then assign undercover words and civilian words. Note: When the number of gamers is an undercover player or a zombie, add the subscript of the printed information to 1. For example, the number of subscripts 0 indicates that the number of players on the first day is actually 1. In life, few people will get used to saying that they are "0th people", except programmers --;

In each round of the game, you can speak and vote in sequence. players with the most votes are out (if the same number of votes are displayed, you can speak again. Then start the next round.

So, if there are num players, how many rounds of the game can end at most? Because only two players in the game is over, so the answer is the num-2 wheel! That is to say, the above process needs to cycle num-2 times.

When the programming idea is fixed, you can tap the code. The program code is as follows:

#! /Usr/local/bin/python3import randomfrom spyword import spywordnum = int (input ('Enter the number of players (at least 3) \ n') # Undercover player spy = random. randint (0, num-1) # randomly generated word definition word list calculation list of players' votes statistics list of dead players list_rand = spyword. popitem () word = [] cnt = [] dead = [] # assign a value for I in range (0, num) to the three lists: word. append ('A') cnt. append (0) dead. append (num + 2) # for gamers, print is used for debugging. sanmeVote indicates the same number of votes, and spyWin is the final condition for undercover victory. for I in range (0, num): if (I = spy): word [I] = str (list_rand [1]) el Se: word [I] = str (list_rand [0]) print (word [I]) sameVote = 0 spyWin = 0 # Game start for x in range (0, num-1 ): for k in range (0, num): if (k not in dead) & (sameVote = 0 )): print ('% d player speech time' % (k + 1) print ('end of the speech Process') # set the number of players' votes to 0 for j in range (0, num): if (j not in dead): cnt [j] = 0for j in range (0, num): if (j not in dead ): vote2p = int (input ('Please vote for player % d' % (j + 1 ))) -1cnt [vote2p] = cnt [vote2p] + 1 sameVote = 0for y in range (0, num): if (cnt [y] = max (Cnt) & (y! = Cnt. index (max (cnt): print ('more than one player gets the highest number of votes, ask these players to speak again ') sameVote = 1if (sameVote = 0 ): dead [x] = cnt. index (max (cnt) if (dead [x] = spy): print ('Undercover gets the most votes, game Terminal ') spyWin = 1 breakprint ('% d! '% (Dead [x] + 1) # End of the game if (spyWin = 0): print (' only two players are left, undercover victory! ')

One line of code is

from spyword import spyword 

Here, spyword is a dictionary of undercover words defined by myself. You can put this file under the working directory of python during the runtime so that the python program can call this dictionary. To view the python working directory, run python and enter

>>> Importos

>>> OS. getcwd ()

You can also change the python working directory.

Python is a simple, efficient, and easy-to-understand high-level dynamic programming language. Many people also call it the "glue language". When receiving large projects, they often use python to write the main framework, then, use java, js, C ++, and other languages in some specific modules to implement specific requirements. It is not difficult to master python. I hope you can discover the fun of python and quickly find the tips for python programming through the three games mentioned in this blog.

Summary

The above is the full content of several simple games in this article on the basic python exercises, and I hope to help you. Interested friends can continue to refer to this site: Python3 list, tuples, dictionaries, string-related knowledge summary, Python crawler instance crawling funny Website Section, python Implementation of face recognition code, etc, if you have any questions, you can leave a message at any time. The editor will reply to you in a timely manner. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.