First time poster...need help with a snippet - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Game Development (https://python-forum.io/forum-11.html) +--- Thread: First time poster...need help with a snippet (/thread-20012.html) |
First time poster...need help with a snippet - globalcooldown - Jul-24-2019 I'm having a problem with a snippet of code for a game I decided to make. All this code snippet does is on player death it iterates through the item list the player had and removes half of their items (rounded up) I'm a bit new to coding so if anyone has suggestions on how to clean this up I would also appreciate that as well. What I think the problem seems to be, is when the it flips the coin and they get to keep the items the counter doesn't go up and so when it reaches the end of the list of items it doesn't start over at 0 it just stops...if that makes any sense. Any help would be greatly appreciated! import random item_list = [ 'Heart of Gold', 'Rod of Ages', "Rabadon's Deathcap", 'Guardian Angel', 'Bloodthirster', 'Ionic Spark', "Mejai's Soustealer" ] number_of_items = len(item_list) player_death = True def on_death_items(item_list, number_of_items): items_to_destroy = (number_of_items/2) if isinstance(items_to_destroy, float): items_to_destroy += .5 else: pass counter = 0 while counter != items_to_destroy: for x in item_list: coin_flip = random.randint(0,1) if coin_flip == 0: item_list.remove(x) counter += 1 else: counter += 0 return item_list print(item_list) while player_death: on_death_items(item_list, number_of_items) player_death = False print(item_list) RE: First time poster...need help with a snippet - Windspar - Jul-24-2019 First mistake. You can't remove items while iterating through them. Example. First thing you should notice it doesn't print them all. def main(): item_list = [ 'Heart of Gold', 'Rod of Ages', "Rabadon's Deathcap", 'Guardian Angel', 'Bloodthirster', 'Ionic Spark', "Mejai's Soustealer" ] item_list2 = item_list[:] # shallow copy # Show error for i, item in enumerate(item_list): print(item) # remove every odd one if i % 2 == 1: item_list.remove(item) print() print(item_list) # build another list dump_list = [] for i, item in enumerate(item_list2): if i % 2 == 1: dump_list.append(item) print() print(dump_list) for item in dump_list: item_list2.remove(item) print(item_list2) main()1. Use random.choice over random.randint(0, 1) 2. Use for loop and range over while. for counter in range(len(item_list)). Only look at this. If you want to see how I would do it. |