- #!/usr/bin/python
- import random
- guess_dict = {'stone' : 0, 'scissors' : 1, 'cloth' : 2}
- guess_list = ['stone', 'scissors', 'cloth']
- def compare(x, y):
- if x == y:
- return 0
- if x == guess_list[0] and y == guess_list[1]:
- return 1
- if x == guess_list[0] and y == guess_list[2]:
- return -1
- if x == guess_list[1] and y == guess_list[0]:
- return -1
- if x == guess_list[1] and y == guess_list[2]:
- return 1
- if x == guess_list[2] and y == guess_list[0]:
- return 1
- if x == guess_list[2] and y == guess_list[1]:
- return -1
- def genPriorList():
- rz = []
- for x in guess_list:
- res = []
- for y in guess_list:
- res.append(compare(x, y))
- rz.append(res)
- return rz
- if __name__ == '__main__':
- info = 'please input: (stone, scissors, cloth) or stop to exit:\\n'
- priorList = []
- priorList = genPriorList()
- print '\\n--------------------------guess begin----------------------------------\\n'
- while True:
- computer_guess = random.choice(guess_list)
- people_guess = raw_input(info)
- if people_guess == 'stop':
- break
- if not people_guess in guess_list :
- print 'input error'
- else:
- m = guess_dict[computer_guess]
- n = guess_dict[people_guess]
- res = priorList[m][n]
- if res == 0:
- print ('computer guess is : [%s] \\npeople guess is : [%s] \\nnone win!!!\\n'
- % (computer_guess, people_guess))
- elif res == 1:
- print ('computer guess is : [%s] \\npeople guess is : [%s] \\ncomputer win!!!\\n'
- % (computer_guess, people_guess))
- else:
- print ('computer guess is : [%s] \\npeople guess is : [%s] \\npeople win!!!\\n'
- % (computer_guess, people_guess))
- print '\\n--------------------------next guess cycle----------------------------------\\n'
- //该片段来自于http://www.codesnippet.cn/detail/130920135855.html
来源: http://www.codesnippet.cn/detail/130920135855.html