I believe that many friends have played the number bomb game, which means that in a certain number range (usually an integer, excluding boundaries), a player selects a number as a bomb, and the other players guess the number in this range, as long as they don’t guess each time. If the bomb number is hit, the range is narrowed according to the number guessed by the players until one of the players guesses the bomb number, and the game ends.
Here, we can try to use the idea of Python programming to disassemble the game process (purely boring), the core is mainly the following two questions:
(1) The production of digital bombs
(2) How to narrow the scope
The first question is very simple. You can use the random module to generate randomly. It should be noted that the digital bomb does not contain a boundary. The randint function can generate a specified range of integers, but includes the boundary, so some processing is needed. I use a loop method to filter out the generated digital bombs that do not meet the requirements; the second problem is a more core problem, constantly narrowing the scope, we can easily think of using the while loop, and finally guess the number break to jump out of the loop, the game End.
import random
def user_num():
num =int(input('Please enter your numbers:\n'))return num
def max_num():
max_num =int(input('Please enter the highest number:\n'))return max_num
def min_num():
min_num =int(input('Please enter the starting number:\n'))return min_num
min_num,max_num =min_num(),max_num()while True:
res = random.randint(min_num,max_num)#res may include numbers at both ends, which need to be eliminated
if res!=min_num and res!=max_num:break
f =[min_num,max_num]
# Core code
def comp(a,b):if a b:
f[1]= a
else:
f[0]= a
print('Game continues, scope{}To{}, Please enter again'.format(f[0],f[1]))
flag =0while True:
num =user_num()if num not inrange(f[0],f[1]):print('Not within the range, please re-enter')continue
elif num!=res:comp(num,res)
elif num==res:print("You guessed it, the game is over!")break
flag +=1print("You guessed it altogether%d times"%flag)
In the core code, I defined a comparison function to replace the two ends of the range, so that the range of guessing can be reduced. The code can still be improved, but I am still a rookie, and I have been thinking about this problem for a long time.
More interesting classic mini game implementation topics, share with you:
C++ classic games summary
Python classic games summary
python tetris game collection
JavaScript classic games are constantly playing
Summary of classic java games
JavaScript classic games summary
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts