首页 > 解决方案 > 无需 Enter 键即可接受键盘输入

问题描述

基本上在我的代码中,我有一点你必须点击 1 然后输入然后输入 2 然后输入,我想这样做,所以当我按下 1 时我不必点击输入按钮。所以我所要做的就是按 1,然后它会掷骰子。

我做了一个快速的研究,似乎无法找到如何/在互联网上输入什么(如果有我需要写的具体内容)

def Game_Round1():
    while player1_dice1_round1_dice != "1":
        player1_dice1_round1_dice = input("Press 1 to roll dice!: ")
    else:
        player1_dice1_round1_answer = random.randint(1, 6)
        print("You rolled the first dice and the answer is: ", player1_dice1_round1_answer)    

    player1_dice2_round1_roll_start = input("Press 2 to roll dice 2: ")
    while player1_dice2_round1_roll_start != "2":
        player1_dice2_round1_roll_start = input("Press 2 to roll dice2!: ")
    else:
        player1_dice2_round1_answer = random.randint(1, 6)
        print("You rolled the second dice and the answer is: ", player1_dice2_round1_answer)

    p1_round1_answer = (player1_dice1_round1_answer + player1_dice2_round1_answer)

    odd_or_even_checker = p1_round1_answer % 2
    if odd_or_even_checker > 0:
        print("as your number is even you will loose 5  points ")
        p1_round1_answer -= 5
    else:
        print("as your number is even you will gain an extra 10 points ")
        p1_round1_answer += 10

标签: python

解决方案


您可以使用该readchar软件包。这个包的readchar方法会阻塞控制台,只等待一个字符,然后输出这个字符。

import readchar

def Game_Round1():
    while player1_dice1_round1_dice != "1":
        player1_dice1_round1_dice = readchar.readchar("Press 1 to roll dice!: ")
    else:
        player1_dice1_round1_answer = random.randint(1, 6)
        print("You rolled the first dice and the answer is: ", player1_dice1_round1_answer)    

    player1_dice2_round1_roll_start = readchar.readchar("Press 2 to roll dice 2: ")
    while player1_dice2_round1_roll_start != "2":
        player1_dice2_round1_roll_start = input("Press 2 to roll dice2!: ")
    else:
        player1_dice2_round1_answer = random.randint(1, 6)
        print("You rolled the second dice and the answer is: ", player1_dice2_round1_answer)

    p1_round1_answer = (player1_dice1_round1_answer + player1_dice2_round1_answer)

    odd_or_even_checker = p1_round1_answer % 2
    if odd_or_even_checker > 0:
        print("as your number is even you will loose 5  points ")
        p1_round1_answer -= 5
    else:
        print("as your number is even you will gain an extra 10 points ")
        p1_round1_answer += 10

推荐阅读