当前位置:网站首页>"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
边栏推荐
- OceanBase社区版之OBD方式部署方式单机安装
- Anaconda安装后Jupyter launch 没反应&网页打开运行没执行
- 腾讯安卓开发面试,android开发的基础知识
- recyclerview gridlayout 平分中间空白区域
- Database specific interpretation of paradigm
- In line elements are transformed into block level elements, and display transformation and implicit transformation
- Unity writes a timer tool to start timing from the whole point. The format is: 00:00:00
- PowerPivot - DAX (first time)
- 系统与应用监控的思路和方法
- 【每周一坑】信息加密 +【解答】正整数分解质因数
猜你喜欢
【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】
[network planning] Chapter 3 data link layer (4) LAN, Ethernet, WLAN, VLAN
HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
枚举根据参数获取值
案例 ①|主机安全建设:3个层级,11大能力的最佳实践
腾讯字节阿里小米京东大厂Offer拿到手软,老师讲的真棒
【每周一坑】输出三角形
Learn to punch in Web
棋盘左上角到右下角方案数(2)
夏志刚介绍
随机推荐
01 basic introduction - concept nouns
Le lancement du jupyter ne répond pas après l'installation d'Anaconda
【云原生与5G】微服务加持5G核心网
Error analysis ~csdn rebound shell error
技术分享 | 抓包分析 TCP 协议
夏志刚介绍
beegfs高可用模式探讨
5. Wireless in vivo nano network: top ten "feasible?" problem
腾讯字节等大厂面试真题汇总,网易架构师深入讲解Android开发
爬虫(14) - Scrapy-Redis分布式爬虫(1) | 详解
Speech recognition (ASR) paper selection: talcs: an open source Mandarin English code switching corps and a speech
JS get browser system language
Web security - payload
枚举根据参数获取值
Node.js: express + MySQL实现注册登录,身份认证
Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
腾讯云数据库公有云市场稳居TOP 2!
In line elements are transformed into block level elements, and display transformation and implicit transformation
What happened to the kernel after malloc() was transferred? Attached malloc () and free () implementation source
设计你的安全架构OKR