码迷,mamicode.com
首页 > 其他好文 > 详细

随机数之石头剪刀布游戏

时间:2015-04-22 22:14:37      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:石头剪刀布   random   

此问题源于Ptyhon核心编程上的一道题:

Random Numbers. Design a “rock, paper, scissors” game,sometimes called “Rochambeau,” a game you may have played as a kid. Here are the rules. At the same time, using specified hand motions, both you and your opponent have to pick from one of the following: rock, paper, or scissors. The winner is determined by these rules, which form some-what of a fun paradox:
(a) the paper covers the rock,
(b) the rock breaks the scissors,

(c) the scissors cut the paper. In your computerized version,
the user enters his/her guess, the computer randomly chooses, and your program should indicate a winner or draw/tie. Note: The most algorithmic solutions use the fewest number of  if statements.

最后一句提到,最好的算法要尽可能的少使用if语句。

所以在求解这个问题的时候,我在思索如何归纳三个选项之间的关系。user有三个选项,computer有三个选项,相互比较的话,应该是比较9次。然而,计算机无法识别三个选项到底那个能胜出。所以必须将石头剪刀布转化成计算机能识别的符号,再加以高效的算法,这个问题就解决了。

(1)函数应该有两个参数,分别是user和computer的选择。

(2)将选项分别与数字映射,让计算机通过比较数字的大小来判定结果。

(3)通过两个选项所对应数字的绝对值进行判定,再配合min(),max()就可以很简单的实现。

Ptyhon代码:

# -*- coding: utf-8 -*-
import random
def Rochambeau(num1, num2):
    num1 = int(num1)
    dic = {1:'stone', 2:'shears', 3:'cloth'}
    re = {num1:'user', num2:'computer'}
    if num1 == num2:
        return 'the same choose:' + dic[num1]
    elif abs(num1 - num2) == 1:
        return 'your choice is: ' + dic[num1] + '\n'         + 'computer\'s choice is:' + dic[num2] + '\n'             'the winner is ' + re[min(num1, num2)]
    else:
        return 'your choice is: ' + dic[num1] + '\n'         + 'computer//s choice is:' + dic[num2] + '\n'         'the winner is ' + re[max(num1, num2)]
        
print Rochambeau(raw_input(
"""
Enter the number of choice:
    1 -> stone
    2 -> shears
    3 -> cloth
"""
), random.randint(1, 3))
注意:dic和re两个字典都有各自的用处。用于本人的英语不太好,所以元素命名有些随意,阅读代码时还望谅解,日后逐步提高。

随机数之石头剪刀布游戏

标签:石头剪刀布   random   

原文地址:http://blog.csdn.net/wzqnls/article/details/45201035

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!