Login
A   A   A  
welcome

 Album 

米Teen唔鐘意玩現成品,喜歡由零件開始砌。99次失敗唔係問題,最緊要係有1次成功!

米Teen總部設在聖公會白約翰會督中學506室,在午膳後和放學後集會。有興趣參與的同學,請與會長或導師聯絡。

米Teen專頁

506室內 2020-11-04 21:43:57
溫度 26℃ 濕度 95%
街景 2020-11-04 21:41:52
街景
5樓室外 2020-11-04 21:43:43
溫度 22℃ 濕度 95%
街景 2020-11-04 21:34:34
街景

21 Candies

icon

Home>ICT>Python for...>21 Candies

Author: HUNG TSZ LOK (SKH Bishop Baker Secondary School, class 4C)

Last modified: 2018.9.7

Game rule: There are total 21 candies, user and computer take turns to take 1 to 4 candy(ies). You lose if you take the last candy.

1a = 21 #Assign the candy count into the variable ‘a’.
2while True: #Start a loop
3 try: #Determine if there is any error when running the code below.
4 t = int(input ("%d candies left, take 1-4:" % a)) #Let the user input a number and change its format from string to integer.
5 except: #If an error occurs, run the code below. The user is expected to input a number. If they enter anything else, the ‘int()’ function can not convert it into an Internet. Therefore, an error will occur.
6 print("please enter an integer between 1 and 4.\n")
7 continue #Restart the loop.
8 if (t >= 1 and t <= 4): #Determine the the number input by user is between 1 and 4 as expected.
9 a = a - t #This part will be explained below.
10 b = 5 - t
11 print ("\n%d candies left,\nI take %d.\n" % (a , b))
12 a = a - b
13 else:
14 print("please enter a number between 1 ,and 4.\n")
15 continue #Restart the loop.
16 if a == 1: #If there is only 1 candy remaining after the computer taking candy(ies), namely, the user lose.
17 break #End the loop
18print ("1 candy left, you lose.")
19
20input()
21#End

Download source code

The main algorithm of this game is very simple. If the player takes turn first, the computer will have 100% chance to win. Therefore we do not need to consider if the user wins.

When the user and the computer finish taking candy(ies) by one time, we call it ‘1 turn’. If the player takes 1 candy, the computer is going to take 4; If the player take 2 candies, the computer is going to take 3, and so on. In other words, if the player takes t candy(ies), the computer is going to take (5 - t) candy(ies).

Therefore, every turn there will be 5 candies taken. After 4 turns, there will be 1 candy left. It will be the turn of player and they will lose according to the game rule.

welcome

 Album 

米Teen唔鐘意玩現成品,喜歡由零件開始砌。99次失敗唔係問題,最緊要係有1次成功!

米Teen總部設在聖公會白約翰會督中學506室,在午膳後和放學後集會。有興趣參與的同學,請與會長或導師聯絡。

米Teen專頁

506室內 2020-11-04 21:43:57
溫度 26℃ 濕度 95%
街景 2020-11-04 21:41:52
街景
5樓室外 2020-11-04 21:43:43
溫度 22℃ 濕度 95%
街景 2020-11-04 21:34:34
街景
 ⇧