当前位置:   article > 正文

python小游戏:猜数字和石头、剪刀、布_小游戏类似石头剪刀布用python

小游戏类似石头剪刀布用python

一、猜数字

用python写一个简单的“猜数字”游戏,运行该程序,输出结果如下:

 代码如下:

  1. import random
  2. secretNumber = random.randint(1, 20) #随机产生1~20中的数字
  3. print("I am thinking a number between 1 and 20")
  4. # ask the player for 6 times
  5. for guessesTaken in range(1, 7):
  6. print("Take a guess")
  7. guess = int(input())
  8. if guess < secretNumber:
  9. print('Your guess is too low')
  10. elif guess > secretNumber:
  11. print("Your guess is too high")
  12. else:
  13. break
  14. if guess == secretNumber:
  15. print('good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
  16. else:
  17. print('Nope.The number I was thinking of was ' + str(secretNumber))

二、石头、剪刀、布

和“猜数字”一样,“石头、剪刀、布”小游戏主要用到了random模块,实现计算机随机出“石头、剪刀、或 布”。

代码如下:

  1. import random, sys
  2. print('石头、剪刀、布')
  3. # 初始化
  4. wins = 0
  5. losses = 0
  6. ties = 0
  7. while True:
  8. print('%s Wins,%s Losses,%s Ties' % (wins, losses, ties))
  9. while True:
  10. print('Enter your move:r(石头)、s(剪刀)、p(布)、q(退出)')
  11. playerMove = input()
  12. if playerMove == 'q':
  13. sys.exit() # 退出游戏
  14. if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
  15. break
  16. print('Type one of r , p ,s or q')
  17. # Display the player chose:
  18. print('the player:')
  19. if playerMove == 'r':
  20. print('石头')
  21. if playerMove == 's':
  22. print('剪刀')
  23. if playerMove == 'p':
  24. print('布')
  25. # Display the computer chose:
  26. randomNumber = random.randint(1, 3)
  27. print('the computer:')
  28. if randomNumber == 1:
  29. computerMove = 'r'
  30. print('石头')
  31. elif randomNumber == 2:
  32. computerMove = 's'
  33. print('剪刀')
  34. elif randomNumber == 3:
  35. computerMove = 'p'
  36. print('布')
  37. # Display and record the win/loss/tie:
  38. if playerMove == computerMove:
  39. print('It is a tie!') # 平局
  40. ties += 1
  41. elif playerMove == 'r' and computerMove == 's':
  42. print("石头 VS 剪刀")
  43. print('You win!')
  44. wins += 1
  45. elif playerMove == 'p' and computerMove == 'r':
  46. print("布 VS 石头")
  47. print('You win!')
  48. wins += 1
  49. elif playerMove == 's' and computerMove == 'p':
  50. print("剪刀 VS 布")
  51. print('You win!')
  52. wins += 1
  53. elif playerMove == 'r' and computerMove == 'p':
  54. print("石头 VS 布")
  55. print('You lose!')
  56. losses += 1
  57. elif playerMove == 'p' and computerMove == 's':
  58. print("布 VS 剪刀")
  59. print('You lose!')
  60. losses += 1
  61. elif playerMove == 's' and computerMove == 'r':
  62. print("剪刀 VS 石头")
  63. print('You lose!')
  64. losses += 1

运行如下:

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/405834
推荐阅读
相关标签
  

闽ICP备14008679号