Python games: guess numbers and rock, scissors, cloth

1. Guess the number

Write a simple "guess the number" game in python, run the program, the output is as follows:

 code show as below:

import random

secretNumber = random.randint(1, 20) #随机产生1~20中的数字
print("I am thinking a number between 1 and 20")

# ask the player for 6 times
for guessesTaken in range(1, 7):
    print("Take a guess")
    guess = int(input())
    if guess < secretNumber:
        print('Your guess is too low')
    elif guess > secretNumber:
        print("Your guess is too high")
    else:
        break
if guess == secretNumber:
    print('good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope.The number I was thinking of was ' + str(secretNumber))

2. Rock, scissors, cloth

Like "Guess the Number", the "Rock, Scissors, and Paper" mini-game mainly uses the random module to realize that the computer randomly generates "Rock, Scissors, or Paper".

code show as below:

import random, sys

print('石头、剪刀、布')
# 初始化
wins = 0
losses = 0
ties = 0

while True:
    print('%s Wins,%s Losses,%s Ties' % (wins, losses, ties))
    while True:
        print('Enter your move:r(石头)、s(剪刀)、p(布)、q(退出)')
        playerMove = input()
        if playerMove == 'q':
            sys.exit()  # 退出游戏
        if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
            break
        print('Type one of r , p ,s or q')

    # Display the player chose:
    print('the player:')
    if playerMove == 'r':
        print('石头')
    if playerMove == 's':
        print('剪刀')
    if playerMove == 'p':
        print('布')

    # Display the computer chose:
    randomNumber = random.randint(1, 3)
    print('the computer:')
    if randomNumber == 1:
        computerMove = 'r'
        print('石头')
    elif randomNumber == 2:
        computerMove = 's'
        print('剪刀')
    elif randomNumber == 3:
        computerMove = 'p'
        print('布')

    # Display and record the win/loss/tie:
    if playerMove == computerMove:
        print('It is a tie!')  # 平局
        ties += 1
    elif playerMove == 'r' and computerMove == 's':
        print("石头 VS 剪刀")
        print('You win!')
        wins += 1
    elif playerMove == 'p' and computerMove == 'r':
        print("布 VS 石头")
        print('You win!')
        wins += 1
    elif playerMove == 's' and computerMove == 'p':
        print("剪刀 VS 布")
        print('You win!')
        wins += 1
    elif playerMove == 'r' and computerMove == 'p':
        print("石头 VS 布")
        print('You lose!')
        losses += 1
    elif playerMove == 'p' and computerMove == 's':
        print("布 VS 剪刀")
        print('You lose!')
        losses += 1
    elif playerMove == 's' and computerMove == 'r':
        print("剪刀 VS 石头")
        print('You lose!')
        losses += 1

Run as follows:

 

 

Guess you like

Origin blog.csdn.net/weixin_44686138/article/details/130418534