Keeping specific items on death, rather than all

I'm searching for a method in which it would allow me to "tag" certain items (for example, those with a specific name) to be kept on death, while items that were not 'tagged' would not be kept. I haven't tried much yet as I dont know where to really start from in order to accomplish such an effect. I'm currently playing on minecraft 1.11.2, for anyone wondering.

Thanks, and happy new year :)


Solution 1:

I'm afraid the only reliable way would be to test for every single player slot of the dead player individually and depending on whether the item was found or not, you'd clear that slot (with the keepInventory gamerule set to true, obviously).

example commands (death is a stat.deaths objective):

/scoreboard players tag @r[score_death_min=1] checkMe

/testfor @a[score_death_min=1,tag=checkMe] {Inventory:[{Slot:0b,tag:{display:{Name:"Ice Blade"}}}]}
/testforblock <coords of the block one before this> chain_command_block * {SuccessCount:0}  
(cond.) /replaceitem entity @a[score_death_min=1,tag=checkMe] slot.hotbar.0 air 

<repeat the 3 commands above for every inventory slot.  
be aware that the NBT tag doesn't line up with the slots in the replaceitem command>

/scoreboard players set @a[tag=checkMe] death 0
/scoreboard players tag @a[tag=checkMe] remove checkMe

this solution is kinda-multiplayer proof, making sure only one player will get checked at a time to prevent false positives. might lead to problems if there are too many players online/dead at once and respawn quickly

this obviously only works with one item-name at a time, so having to test for multiple items in every slot will become very tedious. You could tag every item you don't want to be removed though, to make your life easier:

/give @p ... {SpecialItem:1b}  

and then the testfor would look like this

/testfor @a[score_death_min=1,tag=checkMe {Inventory:[{Slot:0b,tag:{SpecialItem:1b}}]}