当前位置:网站首页>"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
边栏推荐
- Crawler (14) - scrape redis distributed crawler (1) | detailed explanation
- 腾讯架构师首发,2022Android面试笔试总结
- Cesium Click to draw a circle (dynamically draw a circle)
- Digital triangle model acwing 1018 Minimum toll
- PowerPivot - DAX (first time)
- Tencent Android development interview, basic knowledge of Android Development
- beegfs高可用模式探讨
- 5. 无线体内纳米网:十大“可行吗?”问题
- Notes on beagleboneblack
- Groovy basic syntax collation
猜你喜欢
5. 无线体内纳米网:十大“可行吗?”问题
【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】
Continuous test (CT) practical experience sharing
5. 無線體內納米網:十大“可行嗎?”問題
PowerPivot——DAX(初识)
Rhcsa Road
Digital triangle model acwing 1018 Minimum toll
Ideas and methods of system and application monitoring
Tencent T2 Daniel explained in person and doubled his job hopping salary
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
随机推荐
OceanBase社区版之OBD方式部署方式单机安装
Deep learning classification network -- zfnet
解剖生理学复习题·VIII血液系统
8086 instruction code summary (table)
深度学习分类网络 -- ZFNet
[cloud lesson] EI lesson 47 Mrs offline data analysis - processing OBS data through Flink
[network planning] Chapter 3 data link layer (4) LAN, Ethernet, WLAN, VLAN
PHP and excel phpexcel
Synchronization of data create trigger synchronization table for each site
爬虫(14) - Scrapy-Redis分布式爬虫(1) | 详解
Rhcsa Road
22-07-05 七牛云存储图片、用户头像上传
Anaconda安装后Jupyter launch 没反应&网页打开运行没执行
腾讯T4架构师,android面试基础
Discussion on beegfs high availability mode
POJ 3207 Ikki&#39; s Story IV – Panda&#39; s Trick (2-SAT)
B-杰哥的树(状压树形dp)
Jupyter launch didn't respond after Anaconda was installed & the web page was opened and ran without execution
腾讯安卓开发面试,android开发的基础知识
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech