当前位置:网站首页>"Penalty kick" games
"Penalty kick" games
2022-07-06 20:18:00 【Crossin's programming classroom】
Zero basis python Introductory tutorial :python666.cn
Hello everyone , Welcome to Crossin Programming classroom of !
This is an exercise from the beginning of the tutorial , Now put it in separate order , It is convenient for students to read .
After learning a little Python After foundation , We can play a penalty game , About the process :
Every round , You first Enter a direction to shoot , then The computer judges a direction randomly Put out . If the direction is different, the goal will be scored , If the direction is the same, the fight will be successful , No points .
after Offensive and defensive rotation , You choose a direction to fight , Computer shot in random direction .
The first 5 round After that , If the scores are different , The game is over .
5 In wheel , If one side scores all the remaining goals , Also cannot achieve the other party's current score , The game is over .
5 After the discussion, divide equally , The game goes on , Until a certain round is decided .
There are many ways to do this , What I offer here is just a reference . You can do it the way you like , That's your game .
Let's talk about the direction setting first . My idea is relatively simple , It's left 、 in 、 Three directions to the right , To express in a string . When shooting or saving , Enter the direction directly . So here I use input To achieve . Some students use 1-9 To represent eight directions and standing still , Enter one number at a time , That's ok . However, the probability that the goalkeeper will catch is much smaller .
As far as the computer randomly chooses the direction , If you are using numbers , Just use what we said before randint Just random . But I'm going to use random One way :choice. Its function is from a list Select an element at random in the .
therefore , The process of a free throw can be described as :
from random import choice
you = input(' Choose the direction you want to kick :( Left 、 in 、 Right )')
print(' You kicked at ' + you)
direction = [' Left ', ' in ', ' Right ']
com = chice(direction)
print (' The computer pounced on ' + com)
if you != com:
print (' Score a goal !')
else:
print (' Was thrown out ...')
vice versa , I won't repeat it here .
Next , We make it cycle 5 Time , And record the score . Don't judge the outcome for the time being .
use score_you Indicates your score ,score_com Indicates the computer score . It all started with 0, Add... For every goal scored 1.
from random import choice
score_you = 0
score_com = 0
direction = [' Left ', ' in ', ' Right ']
for i in range(5):
print('==== The first %d round - Player free throws ====' % (i+1))
you = input(' Choose the direction you want to kick :( Left 、 in 、 Right )')
print(' You kicked at ' + you)
com = choice(direction)
print(' The computer pounced on ' + com)
if you != com:
print(' Score a goal !')
score_you += 1
else:
print(' Was thrown out ...')
print(' The score : %d(you) - %d(com)\n' % (score_you, score_com))
print('==== The first %d round - Player saves ====' % (i+1))
you = input(' Choose the direction you want to go :( Left 、 in 、 Right )')
print(' You jumped at ' + you)
com = choice(direction)
print(' The computer kicked ' + com)
if you == com:
print(' I jumped out !')
else:
print(' Lost the ball ...')
score_com += 1
print(' The score : %d(you) - %d(com)\n' % (score_you, score_com))
There are two highly similar sections in this code , You can think about whether there is a way to simplify it with a function .
On top of that , Let's add the winning and losing judgment , If 5 After the round, it is divided equally , Just keep kicking .
So we take a round of process as a function kick, stay 5 After the first cycle, add another while loop .
in addition , Here's the previous score_you and score_com It merged into a score Array . Here's why , Must let kick The function uses externally defined variables , You need to use the concept of global variables . I want to avoid saying this for the time being , While using list There is no such problem .( But I hope you don't think it's natural to use variables defined outside the function , We will analyze it in detail later . Students who want to know more can go to the official account “Crossin Programming classroom of ” Reply key words in Global variables )
from random import choice
score = [0, 0]
direction = [' Left ', ' in ', ' Right ']
def kick():
print('==== Player free throws ====')
you = input(' Choose the direction you want to kick :( Left 、 in 、 Right )')
print(' You kicked at ' + you)
com = choice(direction)
print(' The computer pounced on ' + com)
if you != com:
print(' Score a goal !')
score[0] += 1
else:
print(' Was thrown out ...')
print(' The score : %d(you) - %d(com)\n' % (score[0], score[1]))
print('==== Player saves ! ====')
you = input(' Choose the direction you want to go :( Left 、 in 、 Right )')
print(' You jumped at ' + you)
com = choice(direction)
print(' The computer kicked ' + com)
if you == com:
print(' I jumped out !')
else:
print(' Lost the ball ...')
score[1] += 1
print(' The score : %d(you) - %d(com)\n' % (score[0], score[1]))
for i in range(5):
print('==== The first %d round ====' % (i + 1))
kick()
while score[0] == score[1]:
i += 1
print('==== The first %d round ====' % (i + 1))
kick()
if score[0] > score[1]:
print(' Players win !')
else:
print(' The player loses .')
Here our penalty game is almost finished , What we need to do now is to increase the mechanism of early termination of the game , Make it more real .
My idea is this : The game ended ahead of time , Is the score of the underdog , Plus he's in 5 The number of rounds left in the round , Still below the leading side's current score . Although the remaining opportunities can be calculated according to the current number of rounds , But because of the difference between kicking first and kicking later , This calculation will be a little complicated , It's easy to get wrong .
So I decided to add another one list, It records the remaining rounds of both sides , They all start with 5.
Every kick , Just subtract the count of the corresponding party 1.
Every kick , Just judge whether the loser still has a chance .
So you need to add code at the beginning :
rest = [5, 5]
Take players for example , Judgment of each goal played :
if rest[0] > 0:
rest[0] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
As early termination is limited to 5 In wheel , So judge rest[0]>0.return It can make kick The function ends prematurely . The computer's judgment is similar to this , Just change to rest[1].
Because you need a way to end the loop ahead of time , So I let kick The function returns a bool value , Normal conditions return False, Once you finish ahead of time, return to True.
Previous for The loop is also changed to while, So as to end the cycle ahead of time :
i = 0
end = False
while i < 5 and not end:
print '==== The first %d round ====' % (i+1)
end = kick()
i += 1
The complete code is as follows :
from random import choice
score = [0, 0]
rest = [5, 5]
direction = [' Left ', ' in ', ' Right ']
def kick():
print('==== Player free throws ====')
you = input(' Choose the direction you want to kick :( Left 、 in 、 Right )')
print(' You kicked at ' + you)
com = choice(direction)
print(' The computer pounced on ' + com)
if you != com:
print(' Score a goal !')
score[0] += 1
else:
print(' Was thrown out ...')
print(' The score : %d(you) - %d(com)\n' % (score[0], score[1]))
if rest[0] > 0:
rest[0] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
print('==== Player saves ! ====')
you = input(' Choose the direction you want to go :( Left 、 in 、 Right )')
print(' You jumped at ' + you)
com = choice(direction)
print(' The computer kicked ' + com)
if you == com:
print(' I jumped out !')
else:
print(' Lost the ball ...')
score[1] += 1
print(' The score : %d(you) - %d(com)\n' % (score[0], score[1]))
if rest[1] > 0:
rest[1] -= 1
if score[0] < score[1] and score[0] + rest[0] < score[1]:
return True
if score[1] < score[0] and score[1] + rest[1] < score[0]:
return True
return False
i = 0
end = False
while i < 5 and not end:
print('==== The first %d round ====' % (i + 1))
end = kick()
i += 1
while score[0] == score[1]:
i += 1
print('==== The first %d round ====' % (i + 1))
kick()
if score[0] > score[1]:
print(' Players win !')
else:
print(' The player loses .')
This program is longer than what we have written before , And the structure is more complex , It takes patience to analyze .
You can follow your own understanding , To improve the game step by step .
thank forward and give the thumbs-up The fellow ~
_ Previous articles are recommended _
Time consuming 2 God , I made a game machine
If you need to know Paid premium courses And Teaching Q & a service
Please be there. Crossin Programming classroom of Internal reply : 666
边栏推荐
- BeagleBoneBlack 上手记
- Standardized QCI characteristics
- 技术分享 | 抓包分析 TCP 协议
- [cloud native and 5g] micro services support 5g core network
- Ideas and methods of system and application monitoring
- BUUCTF---Reverse---easyre
- Groovy基础语法整理
- Special topic of rotor position estimation of permanent magnet synchronous motor -- Summary of position estimation of fundamental wave model
- 【计网】第三章 数据链路层(3)信道划分介质访问控制
- Appx代码签名指南
猜你喜欢
Cesium Click to draw a circle (dynamically draw a circle)
PowerPivot——DAX(初识)
报错分析~csdn反弹shell报错
Standardized QCI characteristics
数字三角形模型 AcWing 1018. 最低通行费
持续测试(CT)实战经验分享
Anaconda安裝後Jupyter launch 沒反應&網頁打開運行沒執行
Anaconda安装后Jupyter launch 没反应&网页打开运行没执行
[Yann Lecun likes the red stone neural network made by minecraft]
JMeter server resource indicator monitoring (CPU, memory, etc.)
随机推荐
Technology sharing | packet capturing analysis TCP protocol
腾讯云数据库公有云市场稳居TOP 2!
Event center parameter transfer, peer component value transfer method, brother component value transfer
PowerPivot——DAX(初识)
Trends of "software" in robotics Engineering
beegfs高可用模式探讨
报错分析~csdn反弹shell报错
Catch ball game 1
AsyncHandler
Rhcsa Road
Appx code signing Guide
Tencent byte and other big companies interview real questions summary, Netease architects in-depth explanation of Android Development
HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
Gui Gui programming (XIII) - event handling
01 basic introduction - concept nouns
【云原生与5G】微服务加持5G核心网
Introduction of Xia Zhigang
Method keywords deprecated, externalprocname, final, forcegenerate
腾讯字节阿里小米京东大厂Offer拿到手软,老师讲的真棒
5. Wireless in vivo nano network: top ten "feasible?" problem