python - 为什么我的代码适用于在线编译器但不适用于代码编辑器
问题描述
为什么我的代码卡在 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()
解决方案
你有 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
推荐阅读
- bitcoind - 如何在内存池中禁用 Bitcoind ZeroMQ 通知发布块或交易
- python - 无法使用 tsfresh 包中的“extract_features”方法从时间序列数据中提取特征
- angular - 如何在覆盖层内的点击事件上关闭primeng p-overlaypanel [Angular]
- calendar - 使用 Velocity 查找当前月末
- cpu-architecture - 如果长时间闲置,缓存是否会自行清空?
- postgresql - 如何将文件中定义的模式与数据库上运行的实际模式进行比较?
- simulink - 在 FMIKit-Simulink 中创建所有当前变量及其各自值的列表
- ms-word - 如何使用openxml合并具有不同标题的word文档?
- python - 如何使用 h5py 模块访问存储在 .mat 文件中的单元格变量?
- javascript - API 数据不能在 innerHTML 中放置数组