首页 > 解决方案 > 为什么我的代码适用于在线编译器但不适用于代码编辑器

问题描述

为什么我的代码卡在 while 循环中?我无法理解为什么会这样。此代码在 Thorny 等在线代码检查器和编译器上照常运行。但是在代码编辑器上运行它时,它会进入一个无限的 while 循环。有一些我无法删除的错误。请解决我的问题。

import random

WIN_SCORE = 100
DICE_FACES = 6

Position_of_snakes = {17: 7, 54: 34, 62: 19, 98: 79}
Position_of_ladders = {3: 38, 24: 33, 42: 93, 72: 84}


def starting_title():
    print("###### Welcome to Snake & Ladder Game ######")
    print("###### Lets us Start ######")


def players_name():
    player1_name = None
    while not player1_name:
        player1_name = input("Please enter Player 1 name: ")
    player2_name = None
    while not player2_name:
        player2_name = input("Please enter Player 2 name: ")
    return player1_name, player2_name


def roll_the_dice():
    dice_value = random.randint(1, DICE_FACES)
    return dice_value


def snake_and_ladder(player_name, current_position, value_of_dice):
    previous_position = current_position
    current_position = current_position + value_of_dice

    if current_position > WIN_SCORE:
        return previous_position

    if current_position in Position_of_snakes:
        final_position = Position_of_snakes.get(current_position)
    elif current_position in Position_of_ladders:
        final_position = Position_of_ladders.get(current_position)
    else:
        final_position = current_position
    return final_position


def win_check(player_name, position):
    if WIN_SCORE == position:
        print(f"Congratulations!!! {player_name} won the Game")


def game_start():
    starting_title()

    player1_position = 0
    player2_position = 0

    player1_name, player2_name = players_name()
    while True:
        player_input_1 = input("Enter 'roll' to Roll the Dice").lower()
        dice_value = roll_the_dice()
        player1_position = snake_and_ladder(player1_name, player1_position, dice_value)
        win_check(player1_name, player1_position)
        player_input_2 = input("Enter 'roll' to Roll the Dice").lower()
        dice_value = roll_the_dice()
        player2_position = snake_and_ladder(player2_name, player2_position, dice_value)
        win_check(player2_name, player2_position)

game_start()

标签: python

解决方案


你有 while True 这是一个无限循环。您需要在此处声明一个变量并在每次移动后更新其值。您可以使用 win_check 函数返回条件值。

while win_check()

并在 win_check

if WIN_SCORE == position:
    print(f"Congratulations!!! {player_name} won the Game")
    return false
else
    return true

推荐阅读