高/低卡号猜谜游戏

2024-05-20 08:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

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)

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


Tags: andloinputifisvaluerandomval
1条回答
网友
1楼 · 发布于 2024-05-20 08:20:47
  • 不要迭代列表,同时从列表中删除项目
  • 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)

输出:

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

相关问题 更多 >