*Author

Offline XenocidiusTopic starter

  • Legendary Member
  • ******
  • Posts: 2696
  • Reputation Power: 49
  • Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.Xenocidius is towering like an Amethyst Dragon over their peers.
  • Fear the Darkness ...
  • Awards: Slice of Elements 3rd Birthday CakeFavorite Community Member of 2011Weekly Tournament WinnerWinner of Design a Competition Competition
The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg481488#msg481488
« on: April 15, 2012, 12:17:48 pm »
Want to make an Elements tool but can't be bothered writing out all the different properties of every single card that you need? No problem! The Ultimate Elements PHP/Javascript Library is here to help for your client-side and server-side needs.

>> The Ultimate Elements PHP/Javascript Library <<

You can find the library here in text format. Simply change the file extension to .php, upload it to your server and access it like so in PHP:

Code: [Select]
require_once('elements_lib.php');
To use the library in Javascript, go to elements_lib.php?jsupdate. This will automatically create a file called elements_lib.js and populate it. You should do this whenever you update your library. Access it like so:

Code: [Select]
<script src='elements_lib.js'></script>
To change the path of the Javascript file to write to, find the variable $jsfile and change it. You can also have a dynamic Javascript file outputted by elements_lib.php?js. Note that the Javascript will automatically be compressed by JSCompress. To see the raw Javascript, add a nocompress parameter to the URL, as in elements_lib.php?js&nocompress.



Can't be bothered uploading it to your server? Want to try it out first? No problem!

PHP:

Code: [Select]
eval('?>' . file_get_contents('http://elementscommunity.org/tools/elements_lib.txt') . '<?php;');
Javascript:

Code: [Select]
<script src='http://elementscommunity.org/tools/elements_lib.js'></script>
You are free to use the library in any of your tools without credit, as long as the tool is exclusive to the Elements community. If you plan to use it somewhere else for whatever reason, mention my name and provide a link to this topic.



How to use the library

Before we use the library, we need to understand how the game and library stores and references cards. Basically, each element is given a number, like so:

Other: 0
Entropy: 1
Death: 2
Gravity: 3
Earth: 4
Life: 5
Fire: 6
Water: 7
Light: 8
Air: 9
Time: 10
Darkness: 11
Aether: 12

Yes, this is the order of elements in the deck building screen and Bazaar.

Each card is stored as a number too. This number for non-upgraded cards is equal to the number of the element multiplied by 100 plus an arbitrary number:

Code: [Select]
Card number = element number * 100 + x
x is 0 for pillars, 20 for nymphs and 50 for pendulums. For other cards, it is merely the order in which they were added to the game.

So, Amethyst Pillar is 100, Black Nymph is 1120, Heal is 506, etc. There is one exception to this pattern - Quantum Pillar is 2, not 0.

Upgraded cards are simply the non-upgraded card + 2000. So, Amethyst Pillar is 2100, Dark Nymph is 3120, Quantum Tower is 2002, etc.

The library uses a standard format for decks. Each deck is an array of these card numbers (2, 2002, 1450, etc.). They also have a 'mark' index which stores the element number of the deck's mark. Some decks also have a 'name' index.



Card Data

Now that that's out of the way, we can look at the main feature of the library, which is the array called $__cardData.

$__cardData is essentially an array of objects. Each object represents a card, and can be accessed by cardData(card number). For example, Amethyst Pillar's object is cardData(100).

Each card object has a number of different properties. Each object has the following properties:

name

The name of the card.

ctype

This can take upon one of the following values:
  • 'creature' - Any creature except Chimera.
  • 'spell' - All spells and Chimera.
  • 'pillar' - All pillars, pendulums and marks.
  • 'shard' - All permanent shards.
  • 'weapon' - All weapons.
  • 'shield' - All shields.
  • 'permanent' - All other permanents.
atk

The ATK of a creature or damage a weapon deals. Set to 0 for everything else.

def

The HP of a creature, damage reduction of a shield or amount healed per turn by Purify. Set to 0 for everything else.

skill

The name of a card's skill.

Spoiler for List of skills:
* means that the skill is not present on both non-upgraded and upgraded cards.

'ablaze': Fire Spirit, Graviton Fire Eater
'acceleration': Acceleration*
'accretion': Shard of Focus
'adrenaline': Adrenaline, Green Nymph
'aflatoxin': Aflatoxin, Grey Nymph
'air': Dragonfly
'antimatter': Antimatter, Purple Nymph
'armor': Plate Armor*
'berserk': Rage Elixir*, Fire Nymph*
'black hole': Black Hole, Amber Nymph
'blessing': Blessing
'blitz': Sky Blitz
'bones': Bone Wall
'boneyard': Boneyard
'bow': Short Bow
'bravery': Shard of Bravery
'burrow': Antlion, Shrieker, Devourer
'butterfly': Butterfly Effect
'catapult': Catapult
'chaos': Chaos Seed*
'chaos power': Chaos Power*
'cloak': Cloak
'congeal': Congeal*, Arctic Octopus*
'cremation': Cremation*
'dagger': Dagger
'dead/alive': Schrödinger's cat
'deadly poison': Deadly Poison*
'deadly venom': Deathstalker
'deja vu': Deja Vu
'delay': Procrastination
'destroy': Deflagration, Pulverizer
'devour': Otyugh, Scarab
'dissipation': Dissipation Field*
'dive': Wyrm, Pegasus
'divineshield': Seraph
'drain life': Drain Life
'duality': Mindgate
'dusk': Dusk Mantle
'earth': Gnome Rider
'earthquake': Earthquake
'eclipse': Eclipse*
'edissipation': Dissipation Shield*
'empathy': Empathic Bond
'enchant': Enchant Artifact
'endow': Crusader
'evolve': Graboid
'fiery': Fahrenheit
'fire': Brimstone Eater*, Elite Firefly*
'fire bolt': Fire Bolt
'firewall': Fire Shield
'flood': Flooding
'flying': Flying Weapon
'fog': Fog Shield
'fractal': Fractal
'freedom': Shard of Freedom
'freeze': Freeze*, Arctic Squid*
'golem': Shard Golem
'gratitude': Shard of Gratitude
'gravity pull': Gravity Pull
'growth': Lava Golem, Forest Spirit
'guard': Iridium Warden
'hammer': Hammer
'hasten': Golden Hourglass, Sundial
'hatch': Fate Egg
'heal': Guardian Angel
'healp': Heal
'heavy armor': Heavy Armor*
'holy light': Holy Light
'hope': Hope
'ice': Ice Shield
'icebolt': Ice Bolt
'ignite': Unstable Gas
'immaterial': Immortal, Phase Dragon, Morning Star
'immolate': Immolation*
'immortality': Quintessence, Anubis, Turquoise Nymph
'improve': Improved Mutation*, Fallen Druid*
'infect': Virus*
'infection': Parasite, Toadfish*
'infest': Malignant Cell
'integrity': Shard of Integrity
'light': Ray of Light*, Firefly*
'lightning': Lightning
'liquid shadow': Liquid Shadow, Black Nymph
'lobotomize': Lobotomizer, Mind Flayer
'luciferin': Luciferin, Light Nymph
'lycanthropy': Lycanthrope
'miracle': Miracle
'mitosis': Mitosis
'momentum': Momentum, Sapphire Charger, Titan
'moo': Holy Cow
'mutation': Mutation*, Fallen Elf*
'neurotoxin': Dune Scorpion
'nightfall': Nightfall*
'nightmare': Nightmare
'none': Weapon (slot), Shield (slot)
'nova': Nova*
'nymph': Nymph's Tears, Nymph Queen
'overdrive': Overdrive*
'pandemonium': Pandemonium
'paradox': Maxwell's Demon
'parallel universe': Parallel Universe
'patience': Shard of Patience
'petrify': Basilisk's Blood, Auburn Nymph
'phaseshift': Dimensional Shield
'phoenix': Phoenix
'photosynthesis': Rustler
'plague': Plague, Retrovirus*
'poison': Poison
'precognition': Precognition, Golden Nymph
'queen': Firefly Queen
'rage': Rage Potion*, Red Nymph*
'rain of fire': Rain of Fire
'readiness': Shard of Readiness
'rebirth': Ash
'reflect': Reflective Shield, Emerald Shield
'regenerate': Druidic Staff
'reverse time': Reverse Time, Eternity
'sacrifice': Shard of Sacrifice
'sanctuary': Sanctuary
'scarab': Pharaoh
'scavenger': Vulture
'scramble': Discord
'serendipity': Shard of Serendipity
'shard': Shard of Divinity
'shield': Shield, Titanium Shield
'shockwave': Shockwave
'silence': Silence
'singularity': Singularity
'sniper': Owl's Eye
'solar': Solar Shield
'soul catch': Soul Catcher
'spines': Thorn Carapace
'steal': Steal
'steam': Steam Machine
'stone form': Gargoyle
'stoneskin': Stone Skin
'supernova': Supernova*
'sword': Short Sword
'thunderstorm': Thunderstorm
'tsunami': Trident
'unholy': Skull Shield
'unstable gas': Blue Nymph
'vampire': Minor Vampire, Vampire Stiletto
'venom': Arsenic, Forest Scorpion, Puffer Fish*
'void': Shard of Void
'web': Flesh Spider, Phase Spider
'weight': Gravity Shield
'wings': Wings
'wisdom': Shard of Wisdom
' ': Pendulums (yeah, that's right - a space)

skillcost

The cost of a skill. An empty string if the skill is not active and manually activated.

skillelement

The number of the element used to pay for a skill. Usually an empty string if the skill is not active and manually activated.

cost

The casting cost of a card.

costelement

The number of the element used to pay for a card. 0 if the card can be paid for with any quanta (Animate Weapon, etc.)

rarity

The 'tier' of a card, used in buying and selling cost calculations.

They may also have:

passive

The name of a card's passive skill.

Spoiler for List of all passives:
'burrow': Graboid
'chimera': Chimera
'devourer': Devourer
'mummy': Mummy
'obsession': Ghost of the Past
'poisonous': Chrysaora, Forest Scorpion, Deathstalker, Dune Scorpion, Toadfish, Arsenic
'ranged': Short Bow, Owl's Eye
'singularity': Singularity
'sundial': Sundial
'swarm': Scarab
'undead': Skeleton
'voodoo': Voodoo Doll

passive2

The name of a card's second passive skill. Right now this can only be 'airborne', or an empty string for weapons.



AI Decks

Getting random AI decks are made easy by this simple function:

array AIDeck(int $level, string $name = '')

Level is a number from 0 to 5, the AI level for which you want a deck to be generated. Name can be specified when level is 5 to get a specific False God deck.

One can also access the $AIDecks array, which stores AI2, AI3 and AI5 decks.



Functions

All these functions can be used the same way in both PHP and Javascript. Examples given are for PHP.

Spoiler for cardData:
mixed cardData(int $card = 0)

Returns the $__cardData object for the given card. If no card is specified, it will return the entire $__cardData array.

Spoiler for Example:
echo cardData(100)->name;

Output:

Amethyst Pillar

Spoiler for getDeck:
array getDeck(string $deck_code)

Takes a deck import code as an input. Returns an array containing the numbers of each card. Returns false if the deck code is invalid.

Spoiler for Example:
$deck = getDeck("6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj");
echo $deck['mark'];
echo implode(", ", $deck);

Output:

1
2034, 2034, 2034, 2034, 2107, 2107, 2107, 2107, 2107, 2107, 2312, 2513, 2913, 3000, 3000, 3000, 3000, 3000, 3000, 3005, 3005, 3005, 3005, 3006, 3009, 3009, 3009, 3009, 3009, 3009

Spoiler for outputDeck:
string outputDeck(array $deck)

Returns the deck import code of a deck array.

Spoiler for Example:
$deck = array(2034, 2034, 2034, 2034, 2107, 2107, 2107, 2107, 2107, 2107, 2312, 2513, 2913, 3000, 3000, 3000, 3000, 3000, 3000, 3005, 3005, 3005, 3005, 3006, 3009, 3009, 3009, 3009, 3009, 3009);
$deck['mark'] = 1;
echo outputDeck($deck);

Output:

6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj

Spoiler for cards:
array cards(array $deck)

Returns an array of a deck containing only the cards - that is, the deck without any string indexes such as 'mark'.

Spoiler for sortDeck:
array sortDeck(array &$deck)

Sorts a deck array. The sort() function/method should not be used, as it will include the mark and name indexes in PHP, and in both languages will sort alphabetically rather than numerically.

Spoiler for deckSize:
array deckSize(array $deck)

Not so important in Javascript, but should be used instead of count() in PHP, as count() will include the mark and name.

Spoiler for fromElement:
string fromElement(int $element)

Returns the name of an element. Returns "Other" for 0 or any invalid input.

Spoiler for Example:
echo fromElement(11);

Output:

Darkness

Spoiler for toElement:
int toElement(string $element_name)

Returns the number of an element. Returns 0 for "Other" or any invalid input.

Spoiler for Example:
echo toElement("Aether");

Output:

12

Spoiler for fromCardCode:
int fromCardCode(string $card_code)

Returns the number of a card from its output code, or false if the code is invalid.

Spoiler for Example:
echo fromCardCode("4sa");

Output:

2

Spoiler for toCardCode:
string toCardCode(int $card)

Returns the output code of a card from its number.

Spoiler for Example:
echo toCardCode(2);

Output:

4sa

Spoiler for fromMarkCode:
int fromMarkCode(string $mark_code)

Returns the element of a mark code, or false if the input is not a mark code.

Spoiler for Example:
echo fromMarkCode("8pt");

Output:

11

Spoiler for toMarkCode:
string toMarkCode(int $element)

Returns the mark code for an element, or false if the element is invalid.

Spoiler for Example:
echo toMarkCode(11);

Output:

8pt

Spoiler for elementOf:
int elementOf(int $card)

Returns the element of a card. Usually costelement will be enough to determine this, but in some cases such as Animate Weapon, it won't be.

Spoiler for Example:
echo elementOf(2506);

Output:

5

Spoiler for is_pillar:
boolean is_pillar(int $card)

Returns whether or not a card is a pillar. Note that the card cannot be a pendulum or a mark. To include these in the results, use cardData($card).ctype == 'pillar' instead.

Spoiler for is_pendulum:
boolean is_pendulum(int $card)

Returns whether or not a card is a pendulum.

Spoiler for is_nymph:
boolean is_nymph(int $card)

Returns whether or not a card is a nymph.

Spoiler for is_rare:
boolean is_rare(int $card)

Returns whether or not a card is rare.

Spoiler for is_upgraded:
boolean is_upgraded(int $card)

Returns whether or not a card is upgraded.

Spoiler for upgrade:
int upgrade(int $card)

Returns the upgraded version of a card.

Spoiler for downgrade:
int downgrade(int $card)

Returns the non-upgraded version of a card.

Spoiler for compressDeckCode:
string compressDeckCode(mixed $deck_code)

This compresses a deck code by removing all spaces and replacing repeating instances of a card code with z{number of copies - 1}{card code}. Accepts a deck import code or deck array as an input. Useful for things like passing deck codes as get parameters. You can also use it to link a deck image like so: <img src='http://elementscommunity.org/tools/deck/?redirect&deck={compressed code}' />.

Spoiler for Example:
echo compressDeckCode("6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj");

Output:

z36rqz56u374g7ap7n9z57q0z37q57q6z57q98pj

Spoiler for decompressDeckCode:
string decompressDeckCode(string $deck)

Decompresses a deck code compressed with compressDeckCode().

Spoiler for Example:
echo decompressDeckCode("z36rqz56u374g7ap7n9z57q0z37q57q6z57q98pj");

Output:

6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj

Spoiler for cardImage:
string cardImage(int $card)

Returns the filepath to the card image of the specified card.


Spoiler for deckImage:
string deckImage(mixed $deck, bool $raw = false)

Returns the filepath of a deck image of a given deck array or code. If raw is set to true, it will return the raw link to the forum's cache of the deck image. However, it first has to validate that the file exists and create it if not, which can cause a slight delay, particularly in Javascript. If raw is set to false (default), it will return a redirection link to the Deck Image Builder. This will be near-instantaneous, but will instead place the burden on the client once the page is loaded to load and generate the deck image. Usually this will be preferable.

Spoiler for Example:
echo deckImage("6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj") . "<br/>";
echo deckImage("6rq 6rq 6rq 6rq 6u3 6u3 6u3 6u3 6u3 6u3 74g 7ap 7n9 7q0 7q0 7q0 7q0 7q0 7q0 7q5 7q5 7q5 7q5 7q6 7q9 7q9 7q9 7q9 7q9 7q9 8pj", true);

Output:

http://elementscommunity.org/tools/deck/?redirect&deck=z36rqz56u374g7ap7n9z57q0z37q57q6z57q98pj
http://elementscommunity.org/forum/decks/cache/z36rqz56u374g7ap7n9z57q0z37q57q6z57q98pj.jpg



Examples

Let's write a quick program to calculate the cost of a deck.

In PHP ($_GET['deck'] is the input):

<?php
Code: [Select]
require_once("elements_lib.php");

$deck = getDeck($_GET['deck']);
$cost = 0;

function buy_price($card) {
return 6 * pow(cardData($card)->rarity, 2) + cardData($card)->cost;
}

foreach (cards($deck) as $card) {
$cost += buy_price($card);
}

echo "Cost of deck: " . $cost;
?>

That was easy, wasn't it? Let's try the same thing in Javascript:

Code: [Select]
<script src='elements_lib.js'></script>
<script>
deck = getDeck(prompt("Enter a deck code"));
cost = 0;

function buy_price(card) {
return 6 * Math.pow(cardData(card).rarity, 2) + cardData(card).cost;
}

for (i in cards(deck)) {
cost += buy_price(deck[i]);
}

alert("Cost of deck: " + cost);
</script>

This is just the tip of the iceberg. The library can be used and extended to fit virtually any needs you may have for your tool. Now get coding!
Don't cry because it's over, smile because it happened.

Offline euclid47

  • Newbie
  • *
  • Posts: 27
  • Country: us
  • Reputation Power: 1
  • euclid47 is a Spark waiting for a buff.
  • Smite the shepherd and the sheep will be scattered
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg487427#msg487427
« Reply #1 on: April 25, 2012, 09:58:47 pm »
This is some great work! Wow! I will try to port the code over to .Net and open source.  ;D

Offline Rutarete

  • Legendary Member
  • ******
  • Posts: 6505
  • Country: us
  • Reputation Power: 72
  • Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.Rutarete frolics as one of the Phase Dragons, timeless and superior, gargantuan beasts of peerless wisdom.
  • Creativity should be nurtured.
  • Awards: Slice of Elements 6th Birthday CakeSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday CakeRuby Shard of DeckbuildingSlice of Elements 3rd Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg487430#msg487430
« Reply #2 on: April 25, 2012, 10:02:40 pm »
THis looks fun! hehe, what should I do first?
It is the greatest mystery of all...
Rutarete: Roo tah reh teh
[22:50] <Jyi> meaning gets lost in translation... even in the same language.
My Decks

Offline Drake_XIV

  • Legendary Member
  • ******
  • Posts: 6929
  • Country: us
  • Reputation Power: 91
  • Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.Drake_XIV is a mythical and divine giver of immortality, one of the Turquoise Nymphs.
  • Powerful Harmony
  • Awards: Slice of Elements 10th Birthday CakeSlice of Elements 6th Birthday CakeSummer and Winter Competition WinnerSlice of Elements 4th Birthday CakeSlice of Elements 3rd Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg487434#msg487434
« Reply #3 on: April 25, 2012, 10:11:04 pm »
Marking for future use

Offline The_Mormegil

  • Legendary Member
  • ******
  • Posts: 2262
  • Country: it
  • Reputation Power: 32
  • The_Mormegil is a Ghost, obsessed with their Elemental pursuits.The_Mormegil is a Ghost, obsessed with their Elemental pursuits.The_Mormegil is a Ghost, obsessed with their Elemental pursuits.The_Mormegil is a Ghost, obsessed with their Elemental pursuits.The_Mormegil is a Ghost, obsessed with their Elemental pursuits.The_Mormegil is a Ghost, obsessed with their Elemental pursuits.
  • Intelligence is overrated.
  • Awards: Slice of Elements 10th Birthday CakeWar #5 Winner - Team AetherTeam PvP WinnerNew Slot Winner - FamiliarDeadly Sin Winner - GluttonyFirst Budosei of BudokanWinner of Revive the Archive
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg487694#msg487694
« Reply #4 on: April 26, 2012, 06:36:05 am »
I don't think I gave you enough Karma recently.
[18:21:43] jmdt: elements is just math over top of a GUI
Kakerlake: I believe that there is no God as in something that can think by itself and does stuff that sounds way OP.

Offline eaglgenes101

  • Hero Member
  • *****
  • Posts: 1964
  • Country: us
  • Reputation Power: 29
  • eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.
  • The rising all-'rounder of Elements
  • Awards: Slice of Elements 6th Birthday CakeSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg534253#msg534253
« Reply #5 on: August 17, 2012, 06:59:53 pm »
*Cough* Javascript under my belt. Now I'll see if I can make use of it.

EDIT: Please explain.
« Last Edit: August 18, 2012, 05:50:28 am by eaglgenes101 »
My 3 game-modification principles:
1. If it ain't broke, don't wreck it.
2. Simple fixes for simple problems.
3. Remember to fill in the holes.

Offline eaglgenes101

  • Hero Member
  • *****
  • Posts: 1964
  • Country: us
  • Reputation Power: 29
  • eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.
  • The rising all-'rounder of Elements
  • Awards: Slice of Elements 6th Birthday CakeSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg536928#msg536928
« Reply #6 on: August 27, 2012, 05:43:31 am »
How do I get the JS part?
My 3 game-modification principles:
1. If it ain't broke, don't wreck it.
2. Simple fixes for simple problems.
3. Remember to fill in the holes.

Offline ARTHANASIOS

  • Legendary Member
  • ******
  • Posts: 3766
  • Country: gr
  • Reputation Power: 53
  • ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.ARTHANASIOS brings all the vitality and activity of a Life Nymph.
  • Cockatrices ftw!
  • Awards: Slice of Elements 10th Birthday CakeCard Design Competition - Doomsday Device(TM)Weekly Tournament WinnerBrawl #2 Winner - Team FireSlice of Elements 4th Birthday CakeElemental Warrior Competition Winner
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg1003405#msg1003405
« Reply #7 on: September 28, 2012, 02:39:36 pm »
How do I get the JS part?
Here is a Javascript tutorial. I study it too. ;)
http://www.w3schools.com/js/default.asp
Brawl #1 team :time, Brawl #2 team :fire, Brawl #3 team Silver Ferns, Brawl #4,7,8 Brawlmaster
War #8 team :life, War #10,11,12 team :light, Brawl #6 team FROGS :life

Offline russianspy1234

  • Hero Member
  • *****
  • Posts: 1842
  • Country: ru
  • Reputation Power: 26
  • russianspy1234 is a proud Wyrm taking wing for the first time.russianspy1234 is a proud Wyrm taking wing for the first time.russianspy1234 is a proud Wyrm taking wing for the first time.russianspy1234 is a proud Wyrm taking wing for the first time.russianspy1234 is a proud Wyrm taking wing for the first time.
  • Crucible Bombarder
  • Awards: Slice of Elements 14th Birthday CakeSlice of Elements 12th Birthday CakeSlice of Elements 11th Birthday CakeSlice of Elements 9th Birthday CakeSlice of Elements 8th Birthday CakeSlice of Elements 7th Birthday CakeArt Competition - Meta Master Card Design Competition: New Year's ResolutionsSlice of Elements 6th Birthday CakeSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday CakeSlice of Elementshifted 3rd Birthday Cake -Fire-DIAC Ray of SunshineSlice of Elements 3rd Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg1003418#msg1003418
« Reply #8 on: September 28, 2012, 03:48:40 pm »
Now to try and make a random card generator...
My Portfolio
Brawl 7 is occurring.  Come follow along.

Offline eaglgenes101

  • Hero Member
  • *****
  • Posts: 1964
  • Country: us
  • Reputation Power: 29
  • eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.eaglgenes101 is a proud Wyrm taking wing for the first time.
  • The rising all-'rounder of Elements
  • Awards: Slice of Elements 6th Birthday CakeSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg1003633#msg1003633
« Reply #9 on: September 29, 2012, 05:34:41 am »
To use the library in Javascript, go to elements_lib.php?jsupdate. This will automatically create a file called elements_lib.js and populate it. You should do this whenever you update your library. Access it like so:

Code: [Select]
<script src='elements_lib.js'></script>
To change the path of the Javascript file to write to, find the variable $jsfile and change it. You can also have a dynamic Javascript file outputted by elements_lib.php?js. Note that the Javascript will automatically be compressed by JSCompress. To see the raw Javascript, add a nocompress parameter to the URL, as in elements_lib.php?js&nocompress.


Can someone detail this further so I can use it on my own computer? Where do I enter the part referred to by elements_lib.php?jsupdate? Command Prompt?
« Last Edit: September 29, 2012, 05:36:19 am by eaglgenes101 »
My 3 game-modification principles:
1. If it ain't broke, don't wreck it.
2. Simple fixes for simple problems.
3. Remember to fill in the holes.

Offline Pineapple

  • Legendary Member
  • ******
  • Posts: 4105
  • Country: us
  • Reputation Power: 0
  • Pineapple hides under a Cloak.
  • Master of Cake
  • Awards: Silver DonorSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday CakeSlice of Elements 3rd Birthday CakeSlice of Elements 2nd Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg1028317#msg1028317
« Reply #10 on: January 04, 2013, 09:22:29 am »
Okay, so I made a function in python that reads the "elements_lib.txt" file (assuming it is in the same directory as the script) and returns a 2D dictionary (well, one dictionary nested within another) of the card database.
It's rather crude and poorly commented, but I thought I'd share it nonetheless.
It's the best thing you could have until someone does that php-to-python library conversion :P

Code: [Select]
import sys,os
phplib=open(os.path.join(sys.path[0], "elements_lib.txt"), "r")

def setCardData():
        cardData=dict()
        index=0
        for line in phplib:
                if line[ :7]=='//Decks': return cardData
                if line[len(line)-2: ]=='(\n':
                        while not str(index) in line:
                                index+=1
                        cardData[index]=dict()
                elif line[ :2]=='\t\'':
                        key_val=line[2:len(line)-2].split('\' => ')  #'key'=>'val' to key_val=[key,'val]
                        key_val=line[2:len(line)-2].split('\' =>')  #for exceptions (Colossal Dragon)
                        key=key_val[0]; val=key_val[1]
                        if key=='def': key='hp'  #def Python keyword; replaced with hp
                        val=val[1: ] #trimming ''val' to 'val'
                        try: int(val)
                        except ValueError: val=val[1:len(val)-1]  #trimming ''string'' to 'string'
                        cardData[index][key]=val


So:
Quote
>>>print setCardData()[2406]

Gives the following output:
Quote
{'name': 'Shard of Freedom', 'skillelement': 6, 'atk': 0, 'ctype': 'shard', 'rarity': 18, 'cost': 3, 'costelement': 0, 'skillcost': '', 'skill': 'freedom', 'def': 0}
« Last Edit: January 06, 2013, 06:17:53 am by Pineapple »

Offline Pineapple

  • Legendary Member
  • ******
  • Posts: 4105
  • Country: us
  • Reputation Power: 0
  • Pineapple hides under a Cloak.
  • Master of Cake
  • Awards: Silver DonorSlice of Elements 5th Birthday CakeSlice of Elements 4th Birthday CakeSlice of Elements 3rd Birthday CakeSlice of Elements 2nd Birthday Cake
Re: The Ultimate Elements PHP/Javascript Library https://elementscommunity.org/forum/index.php?topic=38705.msg1029831#msg1029831
« Reply #11 on: January 08, 2013, 11:09:48 am »
Okay, I finished translating many of the functions into python. There are plenty of differences, for example two new functions (set/get custom card), a few name/functionality changes, and most data stored in arrays are stored in dictionaries instead. I also changed some of the program logic if I thought there was a more pythonic alternative. Perhaps I should put together a small list of all the changes..

Below is the script. If you run the script, you'll be stuck in the "test loop" where you can type any of the functions to have its return value printed into the console.
Spoiler for Hidden:
Code: [Select]
import sys
import os
import re
import string

# Adapted from 'Elements Library by Xenocidius - version 1.31'

def getDefaultCardData(): #returns cardData array from elements_lib.txt as a dict
        phplib=open(os.path.join(sys.path[0], "elements_lib.txt"), "r")
cardData=dict()
index=0
for line in phplib:
if line[ :7]=='//Decks': return cardData
if line[len(line)-2: ]=='(\n':
while not str(index) in line:
index+=1
cardData[index]=dict()
elif line[ :2]=='\t\'':
key_val=line[2:len(line)-2].split('\' => ')  #'key'=>'val' to key_val=[key,'val]
key_val=line[2:len(line)-2].split('\' =>')  #for exceptions (Colossal Dragon)
key=key_val[0]; val=key_val[1]
if key=='def': key='hp'  #def Python keyword; replaced with hp
val=val[1: ] #trimming ''val' to 'val'
try: int(val)
except ValueError: val=val[1:len(val)-1]  #trimming ''string'' to 'string'
cardData[index][key]=val

def getDefaultElements():
return ('Other','Entropy','Death','Gravity','Earth','Life','Fire',
'Water','Light','Air','Time','Darkness','Aether')

def getCardData(card=False): #originally cardData()
global cardData
if card:
if card<=3300:
try:
return cardData[card]
except KeyError:
showError("Card number "+str(card)+"does not exist!")
else:
return getCustomCardData(card-3300)
else:
return cardData


def getCustomCardData(card=False):
global customCardData
if card:
try:
return customCardData[card]
except KeyError:
showError("Card number "+str(card+3300)+" does not exist!")
else:
return customCardData

def setCustomCardData(
card=False, data=False, name=False, ctype='empty',
atk=0, hp=0, skill='', skillcost='', skillelement=0,
cost=0, costelement=0, rarity=0, passive=False, passive2=False):
global customCardData
if not card:
i=0
while i in customCardData.keys(): i+=1
card=i
if not card in customCardData:
if name:
customCardData[card]={'name':name}
else:
customCardData[card]={'name':'Custom'+str(card)}
if data:
try: customCardData[card]=dict(data)
except ValueError,e: showError("ValueError: "+e)
return
details={'ctype':ctype, 'atk':atk, 'hp':hp,
'skill':skill, 'skillcost':skillcost, 'skillelement':skillelement,
'cost':cost, 'costelement':costelement, 'rarity':rarity,
'passive':passive, 'passive2':passive2}
for key in details:
if str(details[key])!=str(False):
customCardData[card][key]=details[key]
return ''

def toDeck(deckCode): #originally getDeck, returns card numbers and mark from deck code
deckMark=False
deckCards=list()
ex=deckCode.split(' ')
for current in ex:
mark=fromMarkCode(current)
if mark:
deckMark=markCode
else:
card=fromCardCode(current)
if card:
i=0
while i in deck: i+=1
deckCards.append(card)
else:
return showError("Invalid deck code!")
deck=dict(deckCards.sort())
deck['mark']=deckMark
return deck

def toDeckCode(deck): #originally outputDeck(), returns deck code from card numbers
deckCode_list=[]
for card in cardsOf(deck):
deckCode_list.append(toCardCode(card))
try:
deck['mark']
deckCode_list.append(toMarkCode(deck['mark']))
except KeyError:
pass
return ' '.join(deckCode_list)

def cardsOf(deck): #originally cards()
cards=[]
for key,card in deck.items():
try: int(key); cards.append(card)
except ValueError: pass
return cards

def getDeckSize(deck): #originally deckSize()
return len(cardsOf(deck))

def fromElement(element_number):  #returns name of element from its number
global elements
try:
return elements[element_number]
except IndexError:
return 'Other'

def toElement(element):  #returns element number from its name
global elements
try:
return elements.index(element)
except ValueError:
return 0

def base10to32(num):  #converts from a base10 int to a base32 str with lowercase letters
        base10to32.output=[]
        numerals=string.digits+string.lowercase
        def remLoop(num):  #remainder method of base conversion
                q_r=divmod(num,32)
                base10to32.output.append(numerals[q_r[1]])
                if q_r[0]==0:
                        return
                else:
                        remLoop(q_r[0])
        remLoop(num)
        base10to32.output.reverse()
        return ''.join(base10to32.output)

def fromCardCode(cardCode):  #returns card number from its card code
if len(cardCode)!=3 or re.search('[^a-v0-9]',cardCode)!=None:
return False
return int(cardCode,32)-5000

def toCardCode(card):  #returns card code from its card number
return base10to32(card+5000)

def fromMarkCode(markCode):  #returns element number from its mark code
element = fromCardCode(markCode) - 4010
global elements
try:
elements[element]
return element
except KeyError:
return False

def toMarkCode(element):  #returns mark code from its element number
try:
elements[element]
return toCardCode(element+4010)
except KeyError:
return False

def elementOf(card):  #returns element number of a card from its card number
return int(downgrade(card)/100)

def is_upgraded(card):  #returns whether a card is upgraded from its card number
return card>2000

def upgrade(card):  #returns the upgraded version of a card from its card number
if is_upgraded(card):
card+=2000
return card

def downgrade(card): #returns the downgraded version of a card from its card number
if not is_upgraded(card):
card-=2000
return card

def compressDeckCode(deck):
numerals=string.digits+string.uppercase+string.lowercase
deck=deck.split(' ')
cards={}
output=[]
for card in deck:
try:
cards[card]+=1
except KeyError:
cards[card]=0
for card,occurences in cards.items():
if occurences>0:
output.append('z'+numerals[occurences])
output.append(card)
return ''.join(output)

def decompressDeckCode(deck):
numerals=string.digits+string.uppercase+string.lowercase
i=0
cards={}
output=[]
while(i<len(deck)):
if deck[i]=='z':
cards[deck[i+2:i+5]]=numerals.index(deck[i+1])
i+=5
else:
cards[deck[i:i+3]]=0
i+=3
for card,occurences in cards.items():
output.append(card)
for i in xrange(occurences):
output.append(card)
return ' '.join(output)


def showError(msg):
print msg

#load global variables
cardData=getDefaultCardData()
customCardData=dict()
elements=getDefaultElements()

#test loop
while 1:
print input("Command?\n")

 

blarg: