首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环遍历Python列表和程序将不会访问下一项

循环遍历Python列表和程序将不会访问下一项
EN

Stack Overflow用户
提问于 2021-05-19 08:57:21
回答 1查看 49关注 0票数 0

我正在建立一个简单的景观游戏和无法程序将不会进展到下一个可用的工具列表中。它会发展成剪刀,但不会发展成割草机。我将包括所有的代码,因为它很短。

这是我的工具列表。

代码语言:javascript
复制
tools = [
  {
    'name': 'Rusty scissors',
    'cost': 5,
    'profit': 5
  },
  {
    'name': 'Old Lawn Mower',
    'cost': 25,
    'profit': 50
  },
  {
    'name': 'Battery Powered Mower',
    'cost': 250,
    'profit': 100
  },
  {
    'name': 'Team of Students',
    'cost': 500,
    'profit': 250
  }
]

这是我的玩家/景观设计师

代码语言:javascript
复制
player = {
  'money': 0,
  'tools': [],
  'current_tool': {
    'name': 'Teeth',
    'cost': 0,
    'profit': 1
  }
}

下面是我的游戏功能

代码语言:javascript
复制
def buy_tool():

  for tool in tools:
    if player['current_tool'] != tool and player['money'] >= tool['cost']:
      player['current_tool'] = tool
      player['money'] -= tool['cost']
    cut_grass()

def check_money():
  for tool in tools:
    if player['money'] >= tool['cost']:
      buy_tool()
    else:
      cut_grass()
   



def cut_grass():
  print('You currently have $' + str(player['money']) + ' and are using your ' + player['current_tool']['name'] + '.')
  start_cutting = input('Are you ready to cut grass? (y/n)')
  if start_cutting == 'y':
    player['money'] += player['current_tool']['profit']
    check_money()
    

cut_grass()
EN

回答 1

Stack Overflow用户

发布于 2021-05-19 09:03:04

您的代码将搜索您负担得起的第一个工具。一旦找到一个--它总是剪刀状的--它就会停止搜索,并递归到cut_grass (bad design)。

代码语言:javascript
复制
  for tool in tools:
    if player['current_tool'] != tool and player['money'] >= tool['cost']:
      player['current_tool'] = tool
      player['money'] -= tool['cost']
      break
  
  cut_grass()

你必须改变你的逻辑来找到最昂贵的工具。要做到这一点,最简单的方法是颠倒工具列表的顺序。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67595632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档