Python--猜拳小游戏

首先我们要明白,猜拳这个小游戏是怎么做的。简单点说就是要明白,玩家要怎么玩,电脑要怎么跟玩家玩这个游戏。猜拳小游戏很简单,就是石头剪刀布,石头对剪刀,石头胜。这个就是规则,那么我们就需要电脑帮我们出一个石头剪刀或者是布,而玩家同样需要输入是出石头剪刀还是布。那么首先第一阶段代码就是先让电脑能出石头剪刀或者是布

import random

print(random.randint(1, 3))
# 随机打印出一个数字,范围为1-3包含1和3
# 那么我们就可以把1当成石头,2当成剪刀,3当成布

那么电脑这边就弄好了,下面是玩家。第二阶段代码就是让玩家出石头剪刀布

import random

computer = random.randint(1, 3)

player = input("""1:石头 \t  2:剪刀  \t 3:布
请输入:""")

那么下面就需要我们对其进行比较了。使用if语句,如果电脑为石头,玩家为剪刀则电脑胜利,以此类推。得到第三阶段代码

import random

computer = random.randint(1, 3)
computer = str(computer)

player = input("""1:石头 \t  2:剪刀  \t 3:布
请输入:""")

if computer == '1' and player == '2':
    print('computer win!')
elif computer == '2' and player == '1':
    print('player win!')
elif computer == '2' and player == '3':
    print('computer win!')
elif computer == '3' and player == '2':
    print('player win!')
elif computer == '3' and player == '1':
    print('computer win!')
elif computer == '1' and player == '3':
    print('player win!')
elif computer == player:
    print('draw')

那么这么一个小游戏就做好了,但是这里存在简单的bug,就是如果玩家不按照规定输入1 - 3,怎么办?那么我们就需要再游戏开始前添加一个if,如果他不在1-3里就终止或者让玩家重新输入。得到第四阶段代码:

import random
import sys

computer = random.randint(1, 3)
computer = str(computer)
num = ['1', '2', '3']

player = input("""1:石头 \t  2:剪刀  \t 3:布
请输入:""")

if player not in num:
    print('请重新输入!')
    sys.exit(1)

if computer == '1' and player == '2':
    print('computer win!')
elif computer == '2' and player == '1':
    print('player win!')
elif computer == '2' and player == '3':
    print('computer win!')
elif computer == '3' and player == '2':
    print('player win!')
elif computer == '3' and player == '1':
    print('computer win!')
elif computer == '1' and player == '3':
    print('player win!')
elif computer == player:
    print('draw')

这样我们的代码就算是完成了。如果想要玩家赢了才能退出,那么可以在第二个if前加一个while True循环,直到玩家赢才结束。感想大家的阅读!(下面是演示过程,和新的代码)

import random


while True:
    computer = random.randint(1, 3)
    computer = str(computer)
    print(computer)
    num = ['1', '2', '3']

    player = input("""1:石头 \t  2:剪刀  \t 3:布
请输入:""")

    if player not in num:
        print('请重新输入!')
        continue

    if computer == '1' and player == '2':
        print('computer win!')
        print('请继续!!!')
    elif computer == '2' and player == '1':
        print('player win!')
        break
    elif computer == '2' and player == '3':
        print('computer win!')
        print('请继续!!!')
    elif computer == '3' and player == '2':
        print('player win!')
        break
    elif computer == '3' and player == '1':
        print('computer win!')
        print('请继续!!!')
    elif computer == '1' and player == '3':
        print('player win!')
        break
    elif computer == player:
        print('draw!')
        print('请继续!!!')

 Python--猜拳小游戏_第1张图片

使用python制作一个猜拳小游戏就结束了,这里不最好的代码,这里是可以使用try了抓错的 

Python--猜拳小游戏_第2张图片

你可能感兴趣的:(Python,python,开发语言)