中培伟业IT资讯频道
您现在的位置:首页 > IT资讯 > 软件研发 > 如何用Python制作自己的游戏

如何用Python制作自己的游戏

2020-08-04 19:11:35 | 来源:中培企业IT培训网

众所周知,在众多编程语言当中,Python是这些编程语言当中比较流行的。很多软件开发人员利用Python可以制作很多自己喜欢的东西,例如简单的小爬虫、简便的编辑器等,还有些开发人员用Python制作一款自己喜欢的游戏。那么如何用Python制作自己的游戏今天将分享一些技巧,用python创建一个简单的石头剪刀布游戏,该游戏将是人类与计算机的游戏。

  · 通过以下方式导入随机模块:

import random

为什么?这样计算机将产生自己的选择。

放置一个无限的while循环(您不必一次又一次地运行程序。)

while True:

  · 陈述游戏规则。

# Rules of the game

print("""Enter your choice :

a. Press '1' to select 'Stone'.

b. Press '2' to select 'Paper'.

c. Press '3' to select 'Scissor'. """)

  · 根据上述规则从用户那里获取输入。

user_choice = int(input("Enter YOUR choice: "))

  · 用户输入超出范围时,对条件进行编码。

while user_choice > 3 or user_choice < 1:

user_choice = int(input("Enter valid input: "))

  · 为用户选择分配编号。

if user_choice == 1:

choice_name = 'Stone'

elif user_choice == 2:

choice_name = 'Paper'

else:

choice_name = 'Scissor'

  · 让计算机选择其选择,然后为计算机的选择分配编号。

computer_choice = random.randint(1, 3) # Assigning numbers to the computer's choices

if computer_choice == 1:

computer_choicehoice_name = 'Stone'

elif computer_choice == 2:

computer_choicehoice_name = 'Paper'

else:

computer_choicehoice_name = 'Scissor'

  · 编写游戏的主要逻辑。

if((user_choice == 1 and computer_choice == 2) or

(user_choice == 2 and computer_choice ==1 )):

print("Paper wins !!! ", end = "")

result = "Paper"

elif((user_choice == 1 and computer_choice == 3) or

(user_choice == 3 and computer_choice == 1)):

print("Stone wins !!! ", end = "")

result = "Stone"

else:

print("Scissor wins !!! ", end = "")

result = "Scissor"

  · 声明结果。

if result == choice_name:

print(" YOU WIN !!! ")

else:

print(" COMPUTER WINS !!! ")

  · 提出重播问题,并编写条件以打破无限的while循环。

print("Do you want to play again? (y/n)")

ans = input()

if ans == 'n' or ans == 'N':

break

好了关于如何用Python制作自己的游戏介绍到这里就结束了,想了解更多关于Python的信息,请继续关注中培伟业。