Wednesday, August 11, 2010

How to create a simple trading system (exchange items between 2 lists)

This tutorial will teach you how to create 2 lists of several items, where user can put items from the first list to the second and vice versa.

Here's a sreenshot from the game Fallout 3 showing off the game's trading system:


As you can see, there are 2 lists of objects. One for the character and second for the merchant. You can click an item to put it in the other list. This can be used for games and various applications (online shops, maybe?).

Start off by creating 2 List components by dragging them from your component list to the stage, or create them dynamically through Actionscript, it doesn't really matter. Give the lists instance names of list1 and list2. First of all, we add some items, using the addItem() method:

list1.addItem({label:"Apple"});
list1.addItem({label:"Pear"});
list1.addItem({label:"Pineapple"});
list1.addItem({label:"Orange"});
list1.addItem({label:"Lemon"});

list2.addItem({label:"Grapes"});
list2.addItem({label:"Pumpkin"});
list2.addItem({label:"Cherry"});
list2.addItem({label:"Peach"});
list2.addItem({label:"Tomato"});

Pretty simple. Note that you can also set a second parameter for an item, data, which can hold more information that won't be shown to the user (unless you want to show it to him). But it is not used in this tutorial, so we're not touching that.

Next step, creating 2 listeners for 2 lists. Use Event.CHANGE, and the function will be called when the user clicks an item. When an item is clicked, it is created in the second list and removed from the current (remember - first create, then remove, or else you will get errors).

list1.addEventListener(Event.CHANGE, giveItem);
function giveItem(event:Event) {
list2.addItem(event.target.selectedItem);
list1.removeItem(event.target.selectedItem);
}

list2.addEventListener(Event.CHANGE, takeItem);
function takeItem(event:Event) {
list1.addItem(event.target.selectedItem);
list2.removeItem(event.target.selectedItem);
}

And here's the final product:



Related:

How to create a simple trading system: Part 2

No comments:

Post a Comment