繁体   English   中英

高/低卡号猜谜游戏

[英]Higher/Lower Card Number guessing game

我的导师给我们布置了一项任务:用随机整数创建一个高/低数字猜谜游戏。 我们必须向用户询问要生成的最大值以及我们想要玩多少个值。

例如:

max value: 12
number of values: 6

3 Hi(H) Lo(L):H
7 Hi(H) Lo(L):L
9 Hi(H) Lo(L):L
12 Hi(H) Lo(L):L
10 Hi(H) Lo(L):L
4
Your score is:4

我试过的代码:

import random

print("This program plays out HI/LO game with random integer values")

mx_val = int(input("Enter maximun value: "))
num_val = int(input("Enter how many values to play(less than max value): "))

print("Get ready to play the game")

a = []

while len(a) != num_val:
    r = random.randint(1, mx_val)
    if r not in a:
        a.append(r)

score = 0

for i in a:
    print(a[0], end=" ")
    guess = input("Enter Hi(H)or Lo(L): ")
    while guess != "H" and guess != "L":
        guess = input("You must enter 'H' or 'L': ")

    if guess == "H" and a[1] > a[0]:
        score += 1

    if guess == "L" and a[1] < a[0]:
        score += 1

    a.pop(0)

print("Final score is ", score)

这是我的代码,但它没有提出正确数量的问题。 它总是很短。

  • 不要迭代列表并同时从该列表中删除项目
  • a列表中的值不够。 你需要增加一

代码:

import random

print("This program plays out HI/LO game with random integer values")

mx_val = int(input("Enter maximun value: "))
num_val = int(input("Enter how many values to play(less than max value): "))

print("Get ready to play the game")

a = []

while len(a) != num_val+1:
    r = random.randint(1, mx_val)
    if r not in a:
        a.append(r)

score = 0

for i in range(num_val):
    print(a[0], end=" ")
    guess = input("Enter Hi(H)or Lo(L): ")
    while guess != "H" and guess != "L":
        guess = input("You must enter 'H' or 'L': ")

    if guess == "H" and a[1] > a[0]:
        score += 1

    if guess == "L" and a[1] < a[0]:
        score += 1

    a.pop(0)

print("Final score is ", score)

Output:

This program plays out HI/LO game with random integer values
Enter maximun value: 12
Enter how many values to play(less than max value): 6
Get ready to play the game
10 Enter Hi(H)or Lo(L): H
4 Enter Hi(H)or Lo(L): L
8 Enter Hi(H)or Lo(L): H
7 Enter Hi(H)or Lo(L): L
9 Enter Hi(H)or Lo(L): H
11 Enter Hi(H)or Lo(L): L
Final score is  2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM