Today's challenge is a smaller part of a larger idea.
You are creating a board game, similar to a mix between Fire Emblem and Chess. The game features four unique pieces: Swordsman, Cavalry, Archer, and Pikeman. Each piece has its own advantages and weaknesses in combat against other pieces.
You must write a function fightResolve
that takes the attacking and defending pieces as input parameters and returns the winning piece.
The outcome of the fight between two pieces depends on which piece attacks, the type of the attacking piece and the type of the defending piece.
Archers > Swordsmen > Pikemen > Cavalry > Archers
Archers always win against swordsmen, swordsmen always win against pikemen, pikemen always win against cavalry and cavalry always win against archers.
If a matchup occurs that was not previously mentioned (for example Archers vs Pikemen) the attacker will always win.
This challenge comes from user Brysen on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (19)
CSS
Add the attributes
data-piece1
anddata-piece2
to any element, and it will announce the winner:In CSS Selectors Level 4, there is an option to make some selectors case-insensitive (adding an
i
at the end as displayed above). And it is fairly well supported (haven't tried on IE). So it doesn't matter if the user writes "archers" or "Archers" or "aRcHeRs", all of them will be matched.This is by far the most clever CSS I have ever seen. I applaud you.
Mad
Okay close it all, we have a winner!
Look ma, pattern matching!
Ahh, pattern matches. So elegance, much match ( *-*)
I'm surprised no-one has used the age old xor-the-second-bit-of-the-first-characters-and-xor-the-fifth-bit-of-first-and-second-characters trick 😉
In C:
Clearly, this doesn't really need any testing, but here's an exhaustive dump, err, full set of trials, just to be pedantic
prints:
Care to explain how it works? I don't get it 😅
Sure thing. It's a "don't look behind the curtain" kind of thing 🧙♂️
here's the rest of the code...
winner_mank
is reducible to the one posted wheni1=i3=0, i2=i4=1, i5=1,i7=0, i6=i8=4
. And I felt it was may as well be in C.I was lying about the age old trick thing. Upside is it's really really quick, downsides are all the other things 😂
Rust Solution: Playground
Perl solution, using a hash of known fight results.
Rust:
How bout some G O L F
If I understood the problem correctly, the defender only wins if it is the "previous" element on the list. Hence, I just store a string with the initials in the correct order, check the initial index. If the defender is just before the attacker, it wins.
I put a front end on it with React:
I kept the actual method super simple though with a bunch of if statements! Though there are a whole bunch of more clever ways to do it :)
ruby <3