当前位置:  开发笔记 > 编程语言 > 正文

写一个简单的"岩石剪刀"游戏机器人

如何解决《写一个简单的"岩石剪刀"游戏机器人》经验,为你挑选了2个好方法。

这就是我为我的摇滚剪刀游戏提出的:

import random 

from time import sleep 

print "Please select: " 
print "1  Rock" 
print "2  Paper" 
print "3  Scissors" 

player = input ("Choose from 1-3: ") 

if player == 1: 
    print "You choose Rock" 
    sleep (2) 
    print "CPU chooses Paper" 
    sleep (.5) 
    print "You lose, and you will never win!" 

elif player == 2: 
    print "You choose Paper" 
    sleep (2) 
    print "CPU chooses Scissors" 
    sleep (.5) 
    print "You lose, and you will never win!" 

else: 
    print "You choose Scissors" 
    sleep (2) 
    print "CPU chooses Rock" 
    sleep (.5) 
    print "You lose, and you will never win!"

而我想要的程序是随机选择三个选项中的一个(石头剪刀),无论用户输入什么.我怎么能做到这一点?



1> sykora..:

好吧,你已经导入了随机模块,这是一个开始.

尝试random.choice函数.

>>> from random import choice
>>> cpu_choice = choice(('rock', 'paper', 'scissors'))



2> gumuz..:
import random

ROCK, PAPER, SCISSORS = 1, 2, 3
names = 'ROCK', 'PAPER', 'SCISSORS'

def beats(a, b):
    if (a,b) in ((ROCK, PAPER), (PAPER, SCISSORS), (SCISSORS, ROCK)): 
        return False

    return True


print "Please select: " 
print "1  Rock" 
print "2  Paper" 
print "3  Scissors" 

player = int(input ("Choose from 1-3: "))
cpu = random.choice((ROCK, PAPER, SCISSORS))

if cpu != player:
    if beats(player, cpu):
        print "player won"
    else:
        print "cpu won"
else:
    print "tie!"

print names[player-1], "vs", names[cpu-1]


你的节拍功能有点笨重...为什么不只是"返回(a,b)in((纸张,摇滚),(剪刀,纸张),(剪刀,摇滚))"?
推荐阅读
手机用户2402852307
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有