缤纷假期:用Python编写8款趣味小游戏

作者:狼烟四起2024.01.17 17:31浏览量:5

简介:在假期里,让我们用Python编写8款简单而有趣的小游戏,享受编程的乐趣。这些游戏包括经典游戏如猜数字、石头剪刀布等,还有创意新游戏如颜色识别和简单AI对战。附赠源码,让您轻松上手!

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

游戏一:猜数字

游戏简介:程序随机生成一个1-100之间的数字,玩家有10次机会猜出这个数字。
源码

  1. import random
  2. def guess_number():
  3. number_to_guess = random.randint(1, 100)
  4. attempts = 10
  5. while attempts > 0:
  6. guess = int(input('请猜一个1-100之间的数字: '))
  7. if guess < number_to_guess:
  8. print('太小了!')
  9. elif guess > number_to_guess:
  10. print('太大了!')
  11. else:
  12. print('恭喜你,猜对了!')
  13. attempts -= 1
  14. else:
  15. print('很遗憾,你没有猜中。答案是:', number_to_guess)
  16. if __name__ == '__main__':
  17. guess_number()

游戏二:石头剪刀布

游戏简介:玩家与计算机进行石头剪刀布的对决。
源码

  1. import random
  2. def play_game():
  3. print('请输入你的选择(石头、剪刀、布)或输入q退出游戏: ')
  4. while True:
  5. user_choice = input().lower()
  6. if user_choice == 'q':
  7. break
  8. computer_choice = random.choice(['石头', '剪刀', '布'])
  9. if user_choice == computer_choice:
  10. print('平局!')
  11. elif (user_choice == '石头' and computer_choice == '剪刀') or \n (user_choice == '剪刀' and computer_choice == '布') or \n (user_choice == '布' and computer_choice == '石头'):
  12. print('你赢了!')
  13. else:\n print('计算机赢了!')
  14. print('游戏结束.')
  15. if __name__ == '__main__':
  16. play_game()
article bottom image

相关文章推荐

发表评论