0% found this document useful (0 votes)
66 views167 pages

Probability and Programming To Excel at Yu-Gi-Oh!-Independently Published (2021)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
66 views167 pages

Probability and Programming To Excel at Yu-Gi-Oh!-Independently Published (2021)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 167

Probability and Programming to excel

at Yu-Gi-Oh!

Asiel Corpus
Copyright © 2021 Asiel Corpus

All rights reserved


No part of this book may be reproduced, distributed or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without express written permission of the publisher, except in the
case of brief quotations or references for non-commercial uses.

Disclaimer

Yu-Gi-Oh!, Yu-Gi-Oh! Trading Card Game, characters, names, cards and


content related are trademarks owned by Kazuki Takahashi and Konami
Holdings Corporation. Any trademarks, images of cards, names of cards, and
names of sealed products are property of their respective companies and
owners. This book is not authorized, endorsed, licensed, or sponsored in any
way by Kazuki Takahashi or Konami Holdings Corporation.

The content of this book is educational and informational. Although the


content of this book is written to improve the performance of Yu-Gi-Oh!
players at tournaments, there is no guarantee of this happening.

Table of contents
Welcome duelist!
What you WILL NOT find in this book
What you WILL find in this book
Requirements to follow this book
It’s time to duel!

1. Basic probabilities at the Dawn of Duel


1.1 Definition of probability
1.2 Basic probabilities in R

2. Follow the rules of probability


2.1 The intersection and union of events
2.2 Probability of a simple combo
2.3 Shuffling and drawing cards in R

3. Hypergeometric combos
3.1 Permutations
3.2 Combinations
3.3 Multivariate hypergeometric distribution
3.4 Permutations and combinations in R

4. Accelerate with the law of the large numbers


4.1 The law of the large numbers
4.2 Probabilities via simulations in R

5. Binomial eXperYmentZ
5.1 The binomial and cumulative probability
5.2 Binomial and cumulative probability in R

6. Swing pendulum! Draw the network diagram


6.1 Network diagrams
6.2 Network diagrams in R

7. Link your skills to the top of the duel


7.1 A complete and final code to test your strategy in R

8. The end of a journey and the beginning of another

Bonus chapter. The big battle of the monsters


Appendix
Installing R and RStudio
Getting used to RStudio
Customize RStudio
Input your first command in the console
Write your first script
Data types
Data structures
Load, shuffle, and draw some cards
The If – Else statement
The For loop
Custom functions
Simple plots
Install new packages and load libraries

Acknowledgments

About the author

Welcome duelist!
To a journey into the use of Probability and Programming to excel at Yu-Gi-
Oh!

It is a pleasure for me to share these pages with you. What you have at
your service is not only a book, but also the result of a passion I have
developed through more than 18 years as a Yu-Gi-Oh! duelist plus some
scientific and technical knowledge acquired during my professional life. But
no, this is not a book about the interesting, or rather, not so interesting details
of my dueling story. Instead, this book is a carefully selected blend of
probability theory and programming examples applied through the history of
Yu-Gi-Oh! to advance your dueling skills to the next level.
However, I warn you that you need a good amount of dedication to
complete this book and to obtain its maximum benefit. This is because most
of the chapters here presented require you to follow multiple calculations that
involve the use of basic algebra. Also, you will need some time to implement
and understand the even greater amount of programming examples included.
This may sound somewhat scary depending on your math and programming
skills. But fear not! I bet that most Yu-Gi-Oh! duelists are naturally attracted
to logical and thought provoking activities, and that they are already good
enough to follow the math in this book. Also, Yu-Gi-Oh! duelists are
unconsciously trained into programming logic. This training happens as they
conduct their turn in an ordered way from Draw Phase to End Phase, when
they methodically resolve a chain with multiple links, and when they
carefully read the text of a new card. Therefore, I ask you, are you a duelist?
Are you willing to make the effort? If both answers are positive, the
successful completion of this book will earn you an amazing weapon to
accelerate the testing process and evaluation of any Yu-Gi-Oh! strategy. This
way, you will see a huge improvement in your deck building skills that will
allow you to reach the top tables more consistently. Now that your mind is
set, let me give you more details about this book.

What you WILL NOT find in this book


● A detailed guide about how to play Yu-Gi-Oh! You surely know that
already, have an instruction manual with you, or can easily find a free tutorial
online.
● Lists of “the top cards of all time” which will get outdated a few
months later.
● Comments on specific cards to play or what decks to play. You are
the one who decides. Instead, you will develop skills and tools to take smarter
decisions the next time you build a deck.
● Nonsense recommendations such as, “trust your gut” or “follow your
instincts”.

What you WILL find in this book


Most chapters in this book follow a triple approach which includes:
1. An introduction that describes the state of the competitive game over
a certain period of time. These sections include multiple mentions to
outstanding cards, archetypes and strategies. The totality of the book covers
the history of Yu-Gi-Oh! from year 2002 until the end of 2019. This helps the
younger readers to understand the evolution of the game through time.
2. A math section with probability theory applied to situations described
in each introductory section. As a result, the theory explained gets more
detailed as the history of the game develops from chapter to chapter. All
theory is immediately applied to Yu-Gi-Oh!
3. A programming section ready to implement the probability theory in
the R programming language and RStudio development environment. Every
example is complete and fully detailed. Here is more information about what
you can expect in every single chapter.
Here is more information about what you can expect in every single
chapter.
Chapter 1: Basic probabilities at the Dawn of Duel
The first chapter describes the early stage of the game on 2002. This is
convenient to explain the most basic concepts of probability as well as the
most basic commands in R.
Chapter 2: Follow the rules of probability
This chapter describes the popular Magical Scientist + Catapult Turtle
combo used on 2003 to win a duel in the first turn. Then, it introduces the
rules of probability to evaluate how likely you are to get a combo.
Chapter 3: Hypergeometric combos
The history of Yu-Gi-Oh! continues from 2004 until the end of 2006.
This includes the reign of Chaos, the popular Goat Format, and the increased
use of One Turn Kill combos. Here, you will learn the multivariate
hypergeometric distribution to calculate the probability of getting more
complex combos. I guarantee you that this chapter alone is already good
enough to give you an edge over most duelists.
Chapter 4: Accelerate with the law of the large numbers
There is no better moment to accelerate your programming skills than
with the introduction of Synchro Monsters! This chapter will teach you to
simulate thousands of sample hands within a matter of seconds. Then, you
will use the concept of experimental probability to find out how likely you
are to get a popular Blackwing combo.
Chapter 5: Binomial eXperYmentZ
Chapter 5 continues with the introduction of Xyz Monsters and the
binomial probability to find out how reliable is your strategy over the course
of a tournament. Here, you will use the Tempest Dragunity strategy to test for
not 1, but 63 combos at the same time. At this point, you will be far ahead
from other duelists.
Chapter 6: Swing pendulum! Draw the network diagram
As Pendulum Monsters, this chapter does things its own way. Here, you
will expand the default capabilities of R to create wonderful visualizations of
the interactions available in a Zefra Yang Zing deck. Furthermore, this
chapter could as well guide you to develop a new way to build a deck.
Chapter 7: Link your skills to the top of the duel
This is where your technical training in the use of Probability and
Programming to excel at Yu-Gi-Oh! comes to an end. In this chapter, you
will use all your acquired skills to test the Crusadia Guardragon strategy
against possible disruptions hidden in the hand of your opponent.
Chapter 8: The end of a journey and the beginning of another
Our journey together concludes in this chapter. Then, you will start your
own. This time, however, you will be armed with more dueling skills.
Bonus chapter! The big battle of the monsters
Just for fun, what do you think would happen if all the monsters of the
game join in a massive battle?
Appendix
This section is a quick guide to get you familiar with the R programming
language and RStudio. The appendix also includes short descriptions of the
most common functions used in this book. You can consult it at any time as
you read this book.

Requirements to follow this book


Just your commitment to work, basic algebra to follow the math, and a
computer to program in R. I have put a great effort to provide you with
complete and clear examples so you can understand and implement code
even if you have 0 experience with R or any other programming language.
There is also a good amount of illustrations and tables to facilitate your
reading experience. Finally, there are code snippets that show you the input
command on top and its respective output at the bottom as shown below.

Optionally, you can use the official Yu-Gi-Oh! Trading Card Game –
Card Database available at https://www.db.yugioh-card.com/yugiohdb/ to
consult all the details about every single card mentioned in this book.

It’s time to duel!


All I am left to say now is, good luck and have fun! I hope you enjoy
Probability and Programming to excel at Yu-Gi-Oh! as much as I did writing
it.
1. Basic probabilities at the Dawn of
Duel
Long time ago, when the pyramids were still young, the Egyptian Kings used
to play a game of great and terrible power…

Get excited because this is where our quest begins! The simplicity of the
rules of Yu-Gi-Oh! in its early days is the best place to learn and apply the
basic concepts of probability as well as the basic use of R.
O nImmediately,
March 2002, a legendary dragon took flight across North America.
it was recognized as a powerful engine of destruction.
Virtually invincible, the awesome creature faced a multitude of
challengers and very few of them lived to tell the tale. Well, that is probably
not the way things happened, but it is a nice way to say that the release of
Legend of Blue Eyes White Dragon marked the beginning of the Yu-Gi-Oh!
Trading Card Game (TCG).
I like to refer to this moment in the history of Yu-Gi-Oh! as the Dawn of
Duel. This, due to the simple game mechanics and small card pool available
back then. In fact, young players would be surprised to find that Skull Red
Bird, a Level 4 Normal Monster with 1550 ATK, used to be the most
powerful being a duelist could summon without paying a Tribute. Anyway, I
bet most players don’t remember Skull Red Bird, but they probably remember
a mightier Level 4 monster released just a few weeks later in Starter Deck
Kaiba. This is, of course, La Jinn the Mystical Genie of the Lamp, whose
presence on the field was overwhelming with 1800 ATK. At the same time,
Starter Deck Yugi introduced the impressive Summoned Skull, a Level 6
Fiend who set the benchmark of 1 – Tribute monsters due to its exceptional
2500 ATK. Only few 2 – Tribute monsters were capable to defeat the fiend in
battle, therefore, some duelists accepted Summoned Skull as the game –
defining monster. However, most duelists during the Dawn of Duel used to
play with the cards at their disposal rather than with a strategy carefully
selected to increase their chance to win. This was probably a consequence of
the novelty of the game, the young community of players, the lack of official
tournaments, and the absence of a convenient communication channel such as
YouTube or social media. Sure, nobody denied the advantage of cards such
as Monster Reborn, Change of Heart, Dark Hole, Fissure, Trap Hole, and
few others, but there was hardly any discussion about the optimal cards or the
ideal Monster – Magic – Trap ratio to use. Now, you may be surprised to read
about Magic cards. Believe it or not, that was the original name of Spell
cards. The change in the term occurred about one year later to avoid potential
confusion and legal trouble with Magic: The Gathering, another popular card
game. Anyway, going back to deck building during the Dawn of Duel, no one
really applied mathematics to develop game strategies. There was probably
no need to do it. Cards had close to none interaction between them. Also, the
most powerful cards were powerful enough by themselves, therefore, duelists
had no hesitation to include them in their deck. There was not much deck
building involved to be honest. This situation became more notorious with
the release of cards such as Delinquent Duo, Confiscation, The Forceful
Sentry, Snatch Steal, and the overwhelming Jinzo. Fortunately, we can take
advantage of the simplicity of the early game to introduce and learn the basic
concepts of probability needed to understand more advanced stuff later in this
book. So, grab a deck of Yu-Gi-Oh! cards and follow me in the next
examples.

1.1 Definition of probability


Given the random nature of the game, we cannot expect to get the right
cards to win all of the time. Instead, we rely on probability, which is, a
numerical value that represents the chance or possibility of an event
happening. And, what is an event? you may ask. Well, that is up to you to
define. It could be getting your single Pot of Greed when you draw 1 random
card from your 40 – card deck, it could be Time Wizard flipping a coin in
your favor, or it could be rolling a 5 or 6 with Skull Dice. In any case, the
probability of the event happening is denoted as P(E), and it is expressed
with a number between 0 and 1, or in terms of percentage from 0 to 100 %.
This is calculated as the quotient of the number of outcomes for the event and
the total number of outcomes, as shown in Eq. 1.1.

It is also possible to calculate the probability of the complementary


event, P(E’), as shown in Eq. 1.2. This represents the probability of the event
E not happening.

As an example, Figure 1.1 shows a visualization of the different


outcomes related to the three events previously mentioned. In event a), you
draw 1 random card from a 40 – card deck that includes a single Pot of
Greed. This means that there is only 1 outcome among a total of 40 to draw
Pot of Greed. Therefore, P(E) = 1/40 = 0.025, or 2.5%. In practical terms,
you may expect to draw the card 2 or 3 times for every 100 times you repeat
the experiment. In event b), you have the mythical Time Wizard, which
allows you to flip a coin once per turn. If you call it right, your opponent is in
trouble, but if you call it wrong, then you are in deep trouble. Thus, there are
a total of 2 outcomes, which are, right or wrong. However, only 1 of them is
in your favor, therefore, P(E) = 1/2 = 0.5 or 50%. Do you think you would
accept the risk of flipping the coin? Finally, in event c), Skull Dice allows
you to roll a six-sided die and make the opponent monsters lose ATK and
DEF equal to 100 times the result rolled. If for some reason you need the
monsters to lose at least 500 ATK and DEF, then you can have 2 possible
outcomes in your favor from a total of 6. As a result, P(E) = 2/6 ≈ 0.333.

Figure 1.1 Calculation of P(E) and P(E’) for 3 different events.

For all cases, the probability of the complementary event can be


calculated as P(E’) = 1 - P(E). These values are 0.975, 0.5, and 0.667 for the
3 events respectively. Alternatively, you can also calculate P(E’) with the
number of outcomes that do not fulfill the event as 39/40 = 0.975, 1/2 = 0.5,
and 4/6 ≈ 0.667.
1.2 Basic probabilities in R
Maybe the calculation of basic probabilities is… well, too basic for you,
however, I guarantee you that things will get more advanced soon. For this
reason, it is convenient to learn to use new tools in order to facilitate our
calculations. The tool I like is R, an open source programming language
popular for its use in statistical analysis, data cleaning, data visualization, and
machine learning, but in this book, we are going to use it for Yu-gi-oh! Do
not worry if you are not experienced in programming, all you need is covered
in this book. Alternatively, if you are experienced in programming, you can
try to replicate the examples shown here in your favorite programming
language. So, start your trip by downloading and installing R from
https://www.r-project.org/ as well as RStudio from https://rstudio.com/. Then,
follow me in the next examples. Also, make sure to check the Appendix at
the end of this book to get more familiar with R and RStudio.
First, let us start with the console panel at the bottom-left corner of
RStudio. Just type 1/40 and press the Enter key to do a simple division.
Immediately after, you will see 0.025 as the answer. Then, make sure to try
some basic operations with the symbols you are already familiar (+, -, *, /).
You can also try exponentiation and square root, for example, 3^2 = 9, and
sqrt(9)= 3, respectively.

Now, try the factorial of a positive integer, n. This is the product of all
positive integers less than and equal to n, as expressed in Eq. 1.3. For
example, type factorial(5) to evaluate 5! = (5)(4)(3)(2)(1) = 120.

Then, assign numeric values to variables. In the example below, the


number 2 is saved in the variable, Numerator, with Numerator <− 2. Then, 6
is saved in Denominator with Denominator <− 6. Finally, the quotient
Numerator / Denominator is saved in P and the result is displayed with P. If
you prefer, you can give different names to your variables.

Finally, create a vector of elements with the c() function as c(element1,


element2, element3, … , elementn). Here, the elements can be numbers,
characters, or other type of data. For example, v1 <− c(2, 3, 5, 7, 11) saves
the numbers 2, 3, 5, 7, and 11 in v1, whereas v2 <− c(“Pot of Greed”,
“Graceful Charity”, “Painful Choice”) saves the names of the cards in v2.
Notice how text elements require the use of quotation marks. Also, make sure
to check the Appendix section to learn more about data types used in R.

Great! This is all the programming you need for now. In the next chapter
you will learn how to apply these and other functions to read data files into R.
This way you will be able to introduce a complete decklist.
2. Follow the rules of probability
When Magical Scientist and Catapult Turtle were released, nobody
thought they were too special. However, the combination of both of them had
lethal consequences as never seen before. Eventually, we all learned the
importance of the “once per turn” quote in card effects. This time, we will
follow the rules of probability to find out how likely was to win with these
cards.
T hetournaments
year 2003 gave duelists the chance to compete in national-level
to earn a place in the first Yu-gi-oh! World Championship.
This allowed players to observe and learn the most effective strategies
from other players. This time, beatdown strategies were even stronger than
before thanks to Gemini Elf and its 1900 ATK. However, the finalists of the
event found success with a more control-oriented strategy. This was possible
with the inclusion of the Spell Ruler cards mentioned in Chapter 1 plus Don
Zaloog and Drop Off to decrease the cards in the hand of the opponent. At the
same time, they maintained their card advantage and presence on the field
with monsters such as Witch of the Black Forest, Sangan, and Mystic Tomato.
Believe it or not, these last 3 cards were probably the first competitive
monsters to ignite the creativity and deck building skills of duelists. The
reason for this is because they were not specifically designed to shine by
themselves, but rather, with other monsters. Sure, they had a common goal
such as attacking the opponent and defending your field, but they also had
synergy to add or summon certain monsters from the deck. This required the
player to invest some time to think about the optimal cards to use with Witch
of the Black Forest and the others. In contrast, most of the other cards in the
deck had common goals but no synergy at all. For example, the goal of
Nobleman of Crossout and Ring of Destruction was to remove annoying
monsters summoned by the opponent, but there was no particular benefit
from having both of them in the deck or in the same hand. Other cards with
basic synergy around that time were the Gravekeeper’s released on the
Pharaonic Guardian core booster. These were a group of cards with the word
Gravekeeper’s written in their name and a variety of effects with mutual
benefit when played together. Unfortunately for them, they were not relevant
enough in the competitive scene until many years later when they received
extra support. Still, they established the base for modern archetypes, which
are, groups of cards with shared naming, mutual lore, a common strategy and
effects to aid each other.
The known strategies updated with the release of the Magician’s Force
core booster on October, 2003. Some chased cards in that set were the
powerful and versatile Breaker the Magical Warrior, the devastating Tribe-
Infecting Virus, and the shiny Luster Dragon. Other hyped and popular,
although not very effective cards, were the X-Head Cannon, Y-Dragon Head,
and Z-Metal Tank Machine monsters, as well as the lovely Dark Magician
Girl and other Spellcaster monsters. However, despite the introduction of
powerful cards and new game mechanics such as Spell Counters, none of
them really offered something truly novel to the competitive game as much
as Magical Scientist (MS) did. This apparently weak monster introduced the
possibility to decimate the opponent’s Life Points even on the first turn
without the need of a Battle Phase. However, this required the use of other
cards such as Catapult Turtle, Gilasaurus, Last Will, and a bunch of Fusion
Monsters. This way, the first turn kill (FTK) was born. Alternatively, some
duelists used Mother Grizzly (MG) to facilitate the Special Summon of
Catapult Turtle. This made it possible to win with as low as 2 cards. Sure,
this didn’t work on the first turn, but it was a quick and interesting way to
win. This, was a new case of synergy between cards. But what was the
probability P(E) to succeed with this 2-card combo? Let’s find it one step at a
time.

2.1 The intersection and union of events


There are 2 rules that we need to understand to calculate P(E) for of our
event of interest. These are, the addition rule for the union of events, and the
multiplication rule for intersecting events.
The addition rule
We use the addition rule to calculate probabilities that involve the sum of
probabilities for two or more events. This means that the probability of either
of two events E1 or E2 happening is equal to the sum of probabilities of each
event occurring separately. Similarly, this situation can be extended for more
than 2 events, as shown in Eq. 2.1. However, this rule applies only when
events are mutually exclusive, which means that no more than 1 event can
occur at a time. For example, rolling a die can result in only one number, not
more.

The addition rule is useful to calculate the probability of drawing a card


when there are multiple copies of it in the deck. For example, let’s consider a
40-card deck with 3 copies of Mystic Tomato. What is the probability of
drawing 1 of them if you draw 1 random card? In this case, the probability of
drawing a specific tomato, T1, T2, or T3, is 1/40 for each one of them.
Therefore, the probability of drawing any of the 3 tomatoes is the sum of
probabilities for the 3 events.

If for some reason the events are not mutually exclusive, then we need to
consider the probability of both events occurring at the same time. This is
shown in Eq. 2.2 with the term P(E1 and E2). However, this requires some
help of the multiplication rule.

The multiplication rule


We use the multiplication rule to find the probability of events that occur
together. For example, to obtain the probability of flipping 2 coins and
getting Heads in both of them. In this case, each coin has an independent
P(Heads) = 1/2, but the probability of both being heads is obtained by
multiplying each probability. Therefore, P(Heads and Heads) = (1/2)(1/2) =
1/4, or 25%. Moreover, the multiplication rule can be extended to include
multiple events as shown in Eq. 2.3, in which all individual and independent
probabilities are multiplied to obtain the probability to satisfy all of the
events. This condition in which all events are satisfied is called the
intersection of events. I often think about this intersection when I see the
Spell Card, United We Stand, in which two arms are seen holding hands
together and agreeing on the same objective.

However, Eq. 2.3 does not apply anymore when the outcome of one event
is dependent on another. If this situation appears, we then use the general
multiplication rule shown in Eq. 2.4. Here, P(E2|E1) is the probability of E2
dependent on E1, and P(E3|(E1 and E2)) is the probability of E3 dependent on
the intersection of E2 and E1.

This general multiplication rule is useful to calculate the probability of


drawing a specific card in the starting hand. For example, let’s say that you
want to find the probability of drawing your single Harpie’s Feather Duster
(HFD) from your 40-card deck. You already know that P(E) = 1/40 when
you draw a random card, but, what happens if you draw 2 cards instead?
Well, in that case, there is an initial 1/40 chance of drawing HFD in the first
draw, but the probability of getting HFD in the second draw changes
according to the result of the first draw. The reason why this happens is
because if you didn’t get HFD on the first draw, now you have a second
chance to draw it from a deck with 39 remaining cards. As a result, the
probability slightly increases to 1/39 ≈ 0.0256. However, if you get HFD on
the first draw, then there is no chance of drawing it on the second draw, since
there is just a single HFD in the deck. As you can see, this is a clear example
of dependent events, which becomes more complicated as the starting hand
increases in size. Fortunately, we can also take advantage of the
complementary event discussed in chapter 1 to find the probability of
drawing HFD in an initial hand of 6 cards. This is shown in Table 2.1, where
6 consecutive cards are drawn from a 40-card deck and none of them is HFD.
Since there are only 40 cards in the deck, 39 of them are not-wanted cards
and there is a probability of 39/40 of drawing any of them. If a second card is
drawn without returning the first drawn card to the deck, then the probability
of drawing a non-wanted card slightly decreases to 38/39. Then, it keeps
decreasing to 37/38, 36/37, 35/36, and 34/35 for the next four draws.
Table 1. Probability of not drawing a desired card (HFD) in 6 consecutive random draws.

As a result, the probability of not drawing HFD at all can be calculated


with the multiplication rule as follows.

Therefore, the probability of drawing HFD in an initial hand of 6 cards


simplifies with the complementary event as,

2.2 Probability of a simple combo


Now that we are armed with the rules of probability, let’s figure out our
chances to succeed with the old MG + MS duo. First, let’s understand that
there are multiple factors involved in the mentioned combo. Some of these
include, 1) drawing the cards needed or drawing cards that facilitate finding
the cards needed, 2) going first or second in the duel, 3) the possibility of the
opponent being unable or unwilling to attack and destroy MG in battle, 4) the
possibility of getting the combo interrupted, and many others factors. All
these factors complicate the calculation of P(E) to a point beyond our current
skills. However, it is still possible to obtain an approximation of P(E) with
the addition and multiplication rules under simplified game assumptions. To
start, let’s assume that all that we need to succeed and win the duel is to draw
at least 1 MS and at least 1 MG in our initial 6-card hand. Also, let’s consider
a 40-card deck with 3 copies of MS, 3 copies of MG, and 34 other cards that
do not contribute to our strategy in any way. Finally, let’s say that the
opponent plays exactly the way we want it, and we consider that our setup
and combo requires only 1 turn. With this in mind, we can first segregate the
deck into 3 groups, which are, 3 Grizzly Cards, 3 Scientist Cards, and 34
Other Cards. However, there is a trick involved, which is that, as soon as a
Grizzly card is drawn, the other 2 remaining copies automatically transfer to
the Other Card group because they are not needed in the combo anymore.
The same situation occurs with the Scientist Cards. This is, of course, a case
of dependent probability.
To understand its complexity, imagine yourself drawing 6 cards from the
deck one by one. What is coming first? MG, MS or other? If you get MS on
the first draw, your options for the second draw are either MG or Other. On
the other hand, if you get Other first, then you still have the 3 options
available for the second draw. I bet you now realize that the problem
becomes much more complicated due to the multiple ways in which we can
draw the cards. Thus, let’s have a look at Table 2.2 to facilitate the
visualization of these multiple outcomes. There, each row shows a possible
way in which the combo can be completed. For example, row 1 shows a hand
in which MG is obtained in the 1st draw with P1=3/40 and MS in the 2nd draw
with P2 = 3/39. Then, draws 3rd to 6th have all cards from the Other group
where P3 = 38/38, P4 = 37/37, P5 = 36/36, P6 = 35/35, in other words, P3-6 = 1
since they are not relevant for the combo anymore. However, row 7 shows a
starting hand in which the order of cards drawn belong to the Other, Grizzly,
Other, Scientist, Other, and Other groups respectively. As you can see, the
Other group starts with 34 remaining cards, but 2 more cards are added to it
each time a combo piece is drawn. This happens when MG is obtained in the
2nd draw, and then again when MS appears in the 4th draw. Eventually, only
Other Cards are left after the 4th draw, thus, P5-6 = 1. The same reasoning
applies for the other outcomes. Then, the individual outcome probability, PO,
is obtained as the product of the probability for each draw in that particular
outcome, in other words, PO = P1P2P3P4P5P6.

Table 2.2. Possible outcomes to combo when MG is drawn before MS.

As you can see some outcomes are more likely than others, and it is more
probable to complete the combo with the early draws rather than with the
later ones. However, these are only half of the possible outcomes to complete
the 2-card combo. The other half are those in which MS is drawn before MG.
Fortunately, the probabilities for outcomes 16 to 30 share the same values
than those from 1 to 15, therefore, the final combo probability, PC, is obtained
with the addition rule as follows.

Since the probabilities for outcomes 16 to 30 are the same than 1 to 15,
then,

Finally, the calculated probability of our 2-card combo is 0.139 or


13.9%. This is, of course, under the assumptions made. This number
increases with the help of other cards such as Card Destruction or Graceful
Charity, but it also decreases when we consider the probability of drawing all
the copies of Catapult Turtle, which is the monster that MG ultimately looks
to summon from the deck. Anyway, more constraints and larger size combos
surely looks like a more demanding shore. But don’t worry, next chapter
introduces the hypergeometric distribution, which hugely simplifies the
calculation of combo probabilities using the concept of combinations.
Meanwhile, let’s continue with our R training.

2.3 Shuffling and drawing cards in R


Previously, you used R to introduce a vector of characters. If you have
not figure it out yet, vectors are useful to input the name of cards in order to
simulate the actions of shuffling and drawing. So, let’s input the cards shown
in Table 2.2 to run some experiments with them. First, create a vector with, 1
MG, 1 MS, and 4 Other cards, and assign them to an object, for example,
Combo <− (“MG”, “MS”, “O”, “O”, “O”, “O”). Remember that you can
change the names as you please, just make sure to not forget the quotation
marks for each element of the vector.

Now, you can see the 6 elements of the vector every time you type
Combo in the console. Here, the order of appearance of the elements is
always the same as introduced in the original vector, but we can shuffle them
with the function sample(vector) over the vector. This order changes each
time you input the instruction, so do not be surprised if your results shows in
a different order than mine.

You can even draw a specific amount of cards from the vector by
specifying the quantity of cards to draw with the sample(vector, n) function.
For example, if you want 2 random cards, then type sample(Combo, 2).

As you can imagine, this simple function already offers you the option to
introduce a full decklist and to sample a starting hand. However, it could be
somehow annoying to type, see, and edit the name of 40 or more cards in the
R console, so here is an alternative way to load a deck from a csv (comma
separated values) file. To do this, first type all of your cards in your favorite
spreadsheet software from top to bottom as shown in Figure 2.1. Here you
can see not one, but two complete decklists in columns A and B. These
correspond to the main decks used by Shigeki Kitamura and Ng Yu Leung in
the final of the Yu-gi-oh! World Championship 2003, respectively. As you
can see, the top cell includes an identifier label such as the name of duelist,
whereas the following cells include the name of the cards included.
Figure 2.1. Example of decklists in a spreadsheet software.

Once you have filled your cards in the same format, make sure to save
your document as a csv file with the Save As menu. Then, just import your
data to an R object in a structure known as dataframe with the read.csv(file)
function and the full path of your csv file. In the example below, I saved
Kitamura and Leung decks to the object, Decks. If you write multiple
decklists of unequal size in the same csv file as I did, you also need to add the
na.strings parameter in the read.csv() function. If that is not the case, you do
not need to worry about na.strings. Once ready, have a look to your object
with the View(object) function.

The advantage of using csv files is that you can easily store and edit your
decklists in your computer without the need to type them in R every time you
start a new session. Maybe you prefer to have a single csv file for all the
decklists you want to analyze, or maybe you prefer different csv files for
different types of decks. Whatever the case, it is up to you. Another
advantage of having your data in a dataframe structure is that you can use the
View() function to visualize your decks in a more effective way than in the
console. In this case, notice that whatever you type in the first row of your
csv file becomes an identifier label for each decklist instead of an actual card
in it. This allows you to access each decklist in the form of a vector by typing
the name of your dataframe followed by the $ sign and the identifier label.
For example, Decks$Kitamura shows the first column of the dataframe as a
vector, whereas Decks$Leung shows the second column. This way, you can
shuffle and draw cards as you did before.

However, if you read a csv file with decklists on unequal size as I did
here, you may have already noticed that the na.strings parameter
automatically adds NA values to all the empty cells of the dataframe. This is
because columns in a dataframe must contain the same number of elements.
This can cause you to sample the NA values once in a while as if they were
cards in your decklist. To prevent this situation, you can type your vector
inside the na.omit(vector) function inside the sample() function as shown
below. This allows you to ignore these NAs during the sample process and
draw just the actual cards in the vector. Once again, if there is only one vector
in the dataframe, or all vectors are of the same size, then you do not need to
worry about na.strings, NAs, or na.omit(). Just keep in mind that you may end
up with an erroneous sampling process if you ignore the NAs.

Awesome! You can now sample random cards from your deck. Wait just
2 more chapters and you will be able to automate the sampling of thousands
of opening hands to facilitate the evaluation of probabilities. Until then, have
fun!
3. Hypergeometric combos
"You are a duelist, aren’t you?"

"Why don’t you take this? Something just tells me that it belongs with
you."

"Good luck!"

Time to get your game on! This chapter describes one of the most
beloved times in the history of Yu-Gi-Oh! at the same time it introduces you
to the multivariate hypergeometric distribution. This tool alone will put you
ahead of most duelists.
A ndsummarizes
then, Chaos invaded the world! Believe it or not, this short sentence
the state of the game during the following years. Everything
started on 2004 with the release of Invasion of Chaos, a core booster that
raised the power of Monster Cards so much that following sets had a hard
time to keep on pace with it. As a consequence, competitive strategies
stagnated for quite a while.
But what was inside Invasion of Chaos to initiate such change? Well,
let’s start with the mighty Dark Magician of Chaos prior to its errata, an
overwhelming Level 8, 2800 ATK monster with the effect to recover a Spell
Card from the Graveyard, which usually meant a conclusion to the game.
Then, some low rarity Level 4 monsters with 1900 ATK or more such as
Berserk Gorilla, Mad Dog of Darkness, Granadora, and Gigantes to make
raw power accessible to every duelist. Also, influential Spell and Trap Cards
such as Smashing Ground, and Compulsory Evacuation Device to clear away
the opposition, as well as Dimension Fusion to conduct a massive Special
Summon. There were even some cards that found their place in the
competitive scene in the years to come, for example, Ryu Kokki for its easy
access in zombie decks, Manju of the Ten Thousand Hands as a versatile
searcher in ritual decks, and Gren Maju Da Eiza as an insane attack force in
some anti-meta variants. However, nothing in the set compared to the
devastating Chaos duo forged by Black Luster Soldier – Envoy of the
Beginning and Chaos Emperor Dragon – Envoy of the End. Two monsters
with 3000 ATK points, obstacle removing effects, and the possibility to deal
extra damage just by destroying a monster in battle or by paying 1000 Life
Points. All they needed to be summoned was to banish 1 Light and 1 Dark
monster from the Graveyard. Therefore, their insane power and their
ridiculously easy summon method made these pair the most feared monsters
at that time. Their arrival to the field usually announced the winner of the
duel. I even remember my friends at local tournaments often saying, “bajo,
pago y gano!” which is Spanish for “I summon, I pay, I win!”. As a
consequence, duelists adapted their strategies to include Light monsters, such
as, D. D. Warrior Lady, Reflect Bounder, Magician of Faith, and Shinning
Angel to facilitate the summon of the Envoys. Some players even used Chaos
Sorcerer, a weaker but still powerful version of the Envoys.
These Chaos-based strategies dominated and stagnated the game for the
rest of the year despite the release of new, although not as effective, cards.
This was when the Forbidden & Limited Card List, or more commonly
known as banlist, entered the game on October 2004. Its purpose was to
balance the strategies played and to reignite the creativity and deck-building
skills of duelists by restricting the use of cards usually found in dominant
strategies. Still, the first banlist was not good enough to balance the
competitive scene. On the other hand, the second banlist released on March
2005 somehow managed to diminish the power of Chaos to allow other
contenders such as zombies and machines in a popular and well-remembered
period of the game known as, Goat Format.
Goat Format was definitely a fun time to be a duelist. It is even deeply
appreciated by retro players around the world nowadays. One reason for this
is that Goat Format reduced the pool of overpowered cards and encouraged a
more diverse, slower and thought-provoking game style. This included the
use of more Flip effect monsters and a mixture of defensive and aggressive
Spells Cards such as Scapegoat, Book of Moon, Nobleman of Crossout, and
Metamorphosis. Duels were generally longer and players had to adapt to an
often changing environment in which the advantage used to swing from side
to side, as an exciting duel of the Yu-gi-oh! anime show. Furthermore, the
variety of situations and decisions faced by duelists during a tournament
served as feedback to modify their strategies week to week. As a
consequence, players found utility on a variety of tech-cards that could
potentially become meaningful according to the situation. This increased the
diversity of the game even further. At this point, the key to succeed as a
duelist was the correct management of resources. Powerful cards were not
good enough to win duels and the calculation of probabilities was not needed.
Instead, players had to recognize when to use or not to use a particular card
according to the conditions of the game.
Goat Format continued until September 2005 when a new banlist arrived
to debilitate the existing strategies. Another big change to the game was the
release of Cybernetic Revolution, a set which gave players the chance to
reinforce their decks with Cyber Dragon, a Level 5 monster with 2100 ATK.
The ATK and Special Summon effect of Cyber Dragon discouraged the use
of old Level 4 monsters as main combatants. At the same time, it opened up
the possibility to conduct Tribute Summons early in the game in a convenient
way, which increased the popularity of high Level monsters such as
Monarchs.
Other important cards included in Cybernetic Revolution were the Fusion
Monsters, Cyber Twin Dragon and Cyber End Dragon. These two combined
very well with cards such as Cyber-Stein and Megamorph to deplete all of the
opponents’ Life Points in a single turn. And as expected, duelists did not stop
there. They searched for more ways to conduct one-turn-kill (OTK) plays for
the rest of 2005 and most of 2006. A popular OTK going second used Cyber
Dragon to Tribute Summon Zaborg the Thunder Monarch to destroy any
opposing monster. Next, came the activation of Last Will to Special Summon
Cyber-Stein from the deck to further Special Summon Cyber Twin Dragon
and deal more than enough damage.
Unfortunately, I did not have Cyber Dragon cards back then to
experience the excitement of such an epic win, but now I can have a good
time figuring out the probability to pull this combo in the initial hand, and
soon you will too. In fact, we can follow the same approach used in Chapter 2
to evaluate the combo probability, however, it becomes much more difficult
with a 3-card combo. Therefore, let’s introduce the concepts of permutations
and combinations to apply one of the most important techniques you will
learn in this book, the multivariate hypergeometric distribution!

3.1 Permutations
Grab any 3 different Yu-gi-oh! cards. I am going to choose Dekoichi the
Battlechanted Locomotive (DBL), Graceful Charity (GC), and Call of the
Haunted (CH). Once you have your cards at hand, place them one next to
each other and note the order of placement in paper or device. Then, swap the
position of the cards and note again. Repeat this process until you cannot find
a completely new way to order them. As an example, Figure 3.1 shows all the
possible ways in which my chosen cards can be arranged. Each of these
possible arrangements is known as a permutation, in this case, permutations
of DBL, GC, and CH. Basically, all of the permutations have the same cards,
it is just the order of them that makes them different from each other. Finally,
the quantity of permutations for n different cards is found with Eq. 3.1,
therefore, our example with 3 cards has a total of 3!=(3)(2)(1)=6
permutations.

As you can see, just a simple factorial is good enough to calculate the
number of permutations for a complete deck, for example, a deck with 40
cards has a total of 40! permutations, which is such a large number that it is
beyond our imagination.
However, the number of permutations for a deck that contains repeated
cards is calculated with Eq. 3.2 instead, where n is the total number of cards
in the deck, and c1, c2, c3, and so on represent the number of each card that is
different in the deck. In our case, each c takes a value between 1 and 3 since
no card can be included more than 3 times in any deck according to the rules.

Figure 3.1. Different permutations of a 3-card set composed by DBL, GC, and CH. All have the same
cards but their arrangement is different.

There are other interesting equations to calculate permutations. For


example, to find the number of permutations for objects arranged in circles,
or the permutations for objects selected from a larger group. However, we as
duelists usually do not care about the order of cards. Instead, we care about
the probability to draw groups of cards in a starting hand. Therefore, we are
going to put most of our effort to understand a more useful concept according
to our needs, which is, the concept of combination.

3.2 Combinations
Combinations are also arrangements of objects but without considering
the order. As an example, the 6 permutations of DBL, GC, and CH shown in
Figure 3.1 belong to a unique combination, DBL-GC-CH, regardless of the
order of arrangement. Therefore, there is only 1 combination for any group of
objects, however, the number of combinations increases when the original
group is divided into smaller groups. For instance, we can separate the DBL-
GC-CH group into smaller 2-card groups to get 3 combinations, which are,
DBL-GC, DBL-CH, and GC-CH as shown in Fig. 3.2.

Figure 3.2. Possible 2-card combinations of a 3-card group.

As the size of groups and subgroups increase, the number of


combinations increases too and it becomes more difficult to recognize them
or even count them. Fortunately, Eq. 3.3 allows us find the quantity of
combinations for k objects selected from a group of n objects, which is
simplified as nCk and reads as “n choose k”.

So, according to Eq. 3.3, we can substitute n = 3 and k = 2 to calculate


the number of 2-card combinations that exist in our 3-card set composed by
DBL, GC, and CH. As a result, we obtain the same 3 combinations shown in
Figure 3.2, which are, DBL-GC, DBL-CH, and GC-CH.

Similarly, we can substitute n = 40 and k = 6 to obtain 3838380. If you


prefer, you can also type “40 choose 6” in the Google search engine to get the
same result. Now, this result is important because it tell us the number of 6-
card combinations possible in a 40-card deck. In other words, if you shuffle
your deck and draw 6 cards, you can expect to obtain just 1 of the 3838380
available combinations. The question here is, how many of these more than 3
million possible combinations have the power and synergy to guide you to
victory? You are now only one calculation away to find it!

3.3 Multivariate hypergeometric distribution


In previous chapters you learned that the probability of an event
happening is equal to the number of outcomes available for that particular
event divided by the total number of outcomes. That simple operation was
good enough to calculate simple probabilities such as drawing a singular card
from a deck or solving coin flip and dice effects. Then, you used the rules of
probability to evaluate events that involve drawing multiple cards. And
although the use of the rules was straightforward, the calculation of combo
probabilities for events with lots of cards and multiple draws became an
arduous task. Fortunately, the concept of combination allows us to
significantly reduce the quantity of operations and to simplify the
calculations. This way, we can spend less time with the numbers and rather,
invest more time on the definition of the event. Thus, all that knowledge
obtained so far has brought us to Eq. 3.4, the most important in this whole
book.

As you can see, Eq. 3.4 looks similar to Eq. 1.1, but it includes the
concept of combinations in the outcomes. Therefore, all that is needed to find
the probability of a combo in a starting hand is to obtain the number of
combinations that include that combo, and divide it by the total number of
combinations in the deck. As an example, let’s find the probability to win
with that popular OTK combo mentioned before. Once again, suppose that
your opponent does not represent a threat to you and that all you need is to
draw the combination of Cyber Dragon (CD), Zaborg the Thunder Monarch
(ZTM), and Last Will (LW) as shown in Figure 3.3. The deck and your
starting hand have 40 and 6 cards respectively. Furthermore, let’s consider
that the deck contains 3 CD, 2 ZTM, and 1 LW, so these extra copies of CD
and ZTM increase your number of combinations, and therefore, your combo
probability.
Figure 3.3. Key cards of a popular OTK combo used in Yu-gi-oh! at the end of 2006.

Now that all the conditions are set, take a look to Figure 3.4, which uses
binomial coefficients to find the number of combinations of interest to
calculate the probability as stated in Eq. 3.4. This is an example of the
multivariate hypergeometric distribution. But do not let its complicated name
shock you, it is actually easy to use. First, start with the denominator, which
is the term under the division line that counts the number of combinations
possible after selecting k cards from an n-card deck. In this case, a starting
hand of 6 cards drawn from a deck of 40 cards, which counts to
40
C6=3838380. Second, the numerator term above the division line counts the
number of combinations possible with the cards that you want to draw. In this
case, each binomial coefficient represents a desired card, for example, 1 of 3
CD, 1 of 2 ZTM, and 1 of 1 LW. Here, 1 of each card to draw adds to a total
of 3 cards in hand, so you need to add 3 more cards to your hand to complete
a hand of 6. These 3 other cards can be anything remaining in the deck that is
not CD, ZTM or LW, which add to 34. Therefore, your 3 CD, 2 ZTM, and 1
LW in the deck plus the other 34 add to 40 cards in the deck in total. Notice
how the 4 binomial coefficient multiply each other according to the
multiplication rule to account for all the possible combinations to get 1 of
each desired card.
Figure 3.4. Example of the use of the multivariate hypergeometric distribution.

As a result, the probability to get 1 of 3 CD, 1 of 2 ZTM, and 1 of 1 LW


when drawing 6 cards from a 40-card deck is,

So, there are 35904 hand combinations with our combo pieces and a
probability of 0.0094 or 0.94% to get any of them. However, we have not
considered that LW is there to Special Summon Cyber-Stein (CS) from the
deck to allow the OTK. This means that our combo gets ruined if any of these
35904 combinations include CS. Fortunately, the multivariate hypergeometric
distribution also allows us to consider the cards that we do not want to draw.
This consideration can be included in the numerator as another binomial
coefficient, in this case, 1C0, or 0 CS to draw from 1 in deck. Notice how this
modifies the binomial coefficient to 33C3 since none of the remaining cards to
draw can be CS. Just remember, the binomial coefficients in the numerator
need to add to the cards in deck and to the cards in hand, in this case, 40 and
6 respectively.
See how the possibility of drawing CS actually decreases the probability
to get our combo to approximately 0.0085 or 0.85%, in other words, you can
expect it about 1 in every 118 duels, which is an extremely low probability
event in Yu-gi-oh! However, remember that at the moment we have only
considered hand combinations with only 1 of each combo piece, but there is
also a possibility to draw extra CD or ZTM without ruining our combo as
long as we get all the needed pieces. This increases the overall probability of
the OTK combo because we now consider additional combinations, for
example, those with 1, 2 or 3 CD, 1 or 2 ZTM, and 1 LW This is calculated in
Table 3.1.

Table 3.1. Probabilities for different combo hands.


Then, the overall combo probability is calculated by adding each hand
probability with the addition rule, therefore,

At the end, we still get a low combo probability of 0.98 %


approximately. A reason for this small value is that 3-card combinations are
usually difficult to get, especially when you rely completely on drawing them
rather than adding them to your hand with the help of other cards. Also, LW
in this example represents the bottleneck of the combo, since there is only a
single LW in the whole deck. On the other hand, the inclusion of cards such
as Mobius the Frost Monarch, Thestalos the Firestorm Monarch or even
Spell Cards like Premature Burial could help to produce variants of the same
combo and therefore, increase the overall probability. Anyway, popular
strategies back in 2006 already included most of these cards because they
were powerful and versatile in multiple situations. So, the added synergy
between them was an extra possibility to win and not the focus of the strategy
as a whole.

3.4 Permutations and combinations in R


Now is the time to use R to calculate some permutations and
combinations. To do this, let’s load a full decklist as the one shown in Table
3.2.
Table 3.2. Example decklist for the late 2006 format.

I loaded my decklist as a dataframe named Deck from a csv file using the
read.csv(file) function as described in the last chapter. See that I used “Cards”
as an identifier label. Notice that cards with multiple copies are added
multiple times as well. If you want, make sure to check the Appendix section
for a detailed description to load a decklist from a csv file.
Now, let’s calculate the number of permutations possible. To do this,
let’s start by asking how many cards are included in the deck with the
nrow(dataframe) function, which returns the number of rows in a dataframe.
Here, I saved the result of nrow(Deck) to a variable named Deck.size to use it
later.
Once the number of cards is identified, use the factorial(number)
function to calculate the number of permutations possible as shown in Eq.
3.1.

As mentioned before, the number of permutations for 40 cards is an


extremely large number. However, some cards in the deck are repeated,
therefore, the correct way to obtain all the permutations is with Eq. 4.2. This
means that we need to take a look at the deck and identify how many cards of
each are there. This is easily done with the table(vector) function, which
classifies the different elements of a vector. In this case, the vector is
Deck$Cards or just Deck because the dataframe contains a single column.
The next step is to calculate the factorial of each value obtained with the
table() function, and then multiply them for each other. This can be done
once again with the factorial() function nested inside the prod(vector)
function. Therefore, we can combine the 3 functions into a single line of code
as prod(factorial(table(Deck))), which is solved from the inside to the outside.
This means that table() classifies and count the cards in Deck first, then
factorial() calculates the factorial for each value classified, and finally, prod()
multiplies all the factorials evaluated.

The number of permutations with repetitions is obtained as shown below


in a single line of code. Alternatively, you can apply the previous functions in
series saving each result into a different variable to avoid the use of nested
function if you prefer.

Anyway, the number of permutations even when we consider the


repetition of cards is still a gigantic quantity. Fortunately, we are normally
not interested in the order that cards can take, so we can work with
combinations instead. Therefore, consider the case in which you want to draw
6 cards from a 40-card deck. Save the number of cards to draw into a variable
named Hand.size and calculate the number of combinations with the
choose(n, k) function, where n is the size of the deck, and k are the cards
drawn, for example, choose(40, 6).

This simple function already gives us the total number of 6-card


combinations without the need to evaluate any factorial. Now, we can
calculate the number of combinations for the combo described in Section
3.3. Just remember that we need to draw 1 CD, 1 ZTM, 1 LW, and 0 CS when
there are 3, 2, 1, 1 of each card respectively.

Finally, the combo probability is obtained as the ratio of the number of


combo combinations and the number of 6-card combinations in the 40-card
deck. However, remember that our desired combo can be completed with
multiple hands due to the copies of CD and ZTM included. Therefore, you
may need to evaluate some more combinations to find the overall probability.

To close this chapter, let’s take advantage of some other functions


available in R to automate the calculations. This time, consider that Yu-gi-oh!
decks can vary in size from 40 to 60 cards according to the rules. As a
consequence, the number of hand combinations can change according to the
cards in the deck, and to the cards drawn. This, of course, has an impact on
our combo probabilities. Therefore, let’s evaluate all the possible 5-card
combinations for decks of all possible sizes. This is easily done by creating a
vector with values from 40 to 60 as c(40:60). Then, all that is needed is to
evaluate the choose() function for all the values of the vector considering 5
drawn cards as shown below.

Or if you are like me who prefer visualizations, you can create a simple
plot of Combinations vs Size with the plot(x, y) function. Just type your
variables in the argument. For example, plot(Size, Combinations) results in
the graph shown in Figure 3.5.
Notice how the number of 5-card combinations increases from half a
million approximately for a deck with 40 cards to more than 5 million
combinations for a deck of the maximum size.

Figure 3.5. Number of 5-card combinations as a function of the size of the deck.

Alternatively, you can plot the proportion of combinations compared to


the 40-cards case. To do this, just divide all the elements of the Combinations
vector by its initial value, in other words, choose(40, 5) or 658008, as you
prefer. Notice that I nested the calculation inside the round(number, digits)
function to keep only 2 decimals.

This simple calculation allows us to visualize how many times larger the
number of 5-card combinations is for a deck from 40 to 60 cards compared to
those in a 40-card deck. You can also use the plot(Size, Ratio) function to
obtain the graph shown in Figure 3.6. Now is easier to visualize that the
number of combinations increases about 8 times as the deck increases in size
from 40 to 60 cards. As a consequence, it is less likely to get combo hands in
larger decks unless you find an alternative way to get the cards you want.
Some options could be to include more cards that let you search your combo
cards, or to include more cards to let you draw more cards.

Figure 3.6. Proportion of 5-card combinations as a function of the size of the deck. Reference is set to
40.

Amazing! You are now able to use the multivariate hypergeometric


distribution to calculate the probability of any combination of cards from a
deck. Dominion over this technique is surely going to have a tremendous
positive impact on your deck building skills as it did to mine. This alone will
give you a great advantage over most duelists, however, there is still more to
learn. Next chapter will present you a statistical approach to help you
evaluate the probability of combos from data. So get excited because the best
is yet to come!
4. Accelerate with the law of the large
numbers
"Clustering hopes will become a new shining star! Become the path its
light shines upon! Synchro Summon! Take flight, Stardust Dragon!"

Time to rev our programming skills up! This chapter will show you how
to look for a specific combination of cards in thousands of simulated test
hands in a matter of seconds. The fastest way to test your favorite deck!
H old on to your seat because now is the time to accelerate through the
history of Yu-gi-oh! Next stop in this road is 2007, a transition year that
popularized many game strategies but allowed none of them to become
dominant for long.
Let’s start with the Chimeratech OTK strategy, which tried to fill the gap
left by Cyber-Stein when it got banned on December 2006. This deck was
basically an enhancement of the old Machine-Beatdown strategies plus a 2-
card combo integrated by Future Fusion and Overload Fusion. The first of
these cards was there to send Cyber Dragon and as many Machine monsters
as possible from the deck to the Graveyard. The second used all those
monsters to conduct the Fusion Summon of Chimeratech Overdragon with
enough ATK to do the OTK. Then came the Gadgets, a team of low-level and
low-stats monsters assembled by Green Gadget, Red Gadget, and Yellow
Gadget. Their advantage, however, was their effect to add each other from
the deck to always have a monster in hand. This allowed to build decks with
few monsters and lots of Trap Cards to take control of the field. Furthermore,
Gadgets combined really well with Snipe Hunter, a monster that offered the
possibility to destroy any card on the field as long as you were willing to
discard 1 card, roll a 6-sided die, and get any result except 1 or 6. A nice
probability I would say. Other popular monster was the powerful and
versatile Card Trooper. This monster was capable to draw extra cards, load
the Graveyard with resources, gain ATK and even perform OTKs with help
of Machine Duplication and Limiter Removal. Then came a variety of
strategies taking advantage of cards such as Elemental HERO Stratos,
Destiny HERO – Malicious, Destiny HERO – Disk Commander, and Destiny
Hero – Diamond Dude. Monarchs received the support of Raiza the Storm
Monarch, which was more versatile and often more disruptive than the old
Zaborg the Thunder Monarch and Mobius the Frost Monarch. Ritual
Monsters also got some attention when Advanced Ritual Art was released.
This Ritual Spell Card opened up the possibility to conduct Ritual Summons
by sending Normal Monsters from the deck to the Graveyard instead of
Monsters in the hand. As a result, Ritual Monsters alleviated their usually
difficult summon condition. This created a hybrid OTK strategy assembled
by Demise, King of Armageddon and high ATK Insect-Type monsters such
as Neo Bug and Doom Dozer. Then, there was even an effective but short-
lived effect-damage strategy known as Chain Burn. And finally, 2007 closed
with the release of Light and Darkness Dragon, a powerful and oppressive
monster that provided recovery when destroyed. This last monster along with
the HERO and Monarch cards mentioned earlier gave birth to the strategy
known as Perfect Circle.
Overall, 2007 was a fast paced year in which duelists had to adapt to
often changing strategies, and 2008 was not different at all. Phantom of
Darkness, the first set of 2008, was like the new Invasion of Chaos for Dark-
attribute monsters. Many popular monsters in the game history returned as
dark-corrupted versions of themselves with more devastating effects and
easier to summon conditions. The most feared of them was Dark Armed
Dragon without a doubt, which found success in the competitive scene
thanks to the support of Dark Grepher, Armageddon Knight, and other cards.
Then came the Light of Destruction set to support Light-attribute monsters
with the introduction of the Lightsworn archetype. These newcomers focused
on fast Graveyard – filling strategies to summon the game-defining Judgment
Dragon. The same set also provided Gladiator Beast Gyzarus, a Fusion
Monster whose destructive effect and easy to summon requirement catapulted
the Gladiator Beast archetype to competitive levels. This deck focused on
tagging monsters between the field and the deck to summon the one required
for the occasion. As a result, Gladiator Beasts offered a versatile strategy with
a low number of monsters. This allowed players to save some space for traps
in their decks in a similar way than Gadgets did.
Most of the competitive strategies at this point in the history of the game
showed some degree of synergy. This made 2-card and even 3-card combos
more common than in previous years. This trend became more evident with
the introduction of Synchro and Tuner monsters at the end of summer 2008.
The former shared their space with Fusion Monsters in the now renamed
Extra Deck. However, the advantage of Synchros over Fusions was that they
did not require a Spell Card such as Polymerization to summon them.
Instead, they required players to send a Tuner Monster and 1 or more non-
Tuner Monster from the field to the Graveyard whose sum of Levels matched
the Level of the Synchro Monster to summon. This new Summon Mechanic
had an immediate impact on the game. Now, players had easy access to
powerful monsters resting in the Extra Deck until they were needed on the
field. As a consequence, the tempo of duels accelerated and the slower
Tribute Summon mechanic became less common because high Level
monsters were removed from the Main Deck unless they included really
advantageous effects. On the other hand, low Level monsters and the newly
introduced Tuner Monsters started to receive more attention to fulfill the
Synchro summoning requirement.
One could say that Synchro Monsters made deck building more difficult,
however, the extra effort involved was worth it in most strategies. As an
example, strategies based on Dark Armed Dragon quickly evolved to Tele-
DAD with the inclusion of Emergency Teleport to Special Summon the Level
2 Tuner, Krebons. This, in combination with the Level 6 Destiny HERO
Malicious allowed easy access to powerful Level 8 Synchro Monster such as
Red Dragon Archfiend, and Stardust Dragon. This last monster had an
impressive advantage against Gladiator Beasts. Therefore, the Tele-DAD
strategy soon moved to the undisputed top of the competitive game until the
release of a new banlist. After that, countless Synchro strategies joined the
game with the release of more Synchro and Tuner Monsters. Also, new
sealed products such as Hidden Arsenal offered a convenient way to bring
new archetypes to the game.
Particularly, one of the most popular Synchro strategies were the
Blackwing. These were a group of Dark Winged-Beasts Monsters with lots of
Special Summon effects, either for themselves or for their comrades. Also,
many of them had additional and versatile effects to help them overcome
even the most difficult situations. And if this wasn’t enough, the Black
Whirlwind Spell Card offered the possibility to search the most convenient
Blackwing monster according to the situation. All of these factors made
Blackwing a competitive, powerful, versatile, and consistent strategy. The
synergy of the cards in the deck was so impressive that even the use of
combinations and the multivariate hypergeometric distribution would be
insufficient to calculate the probability of some of their most complicated
events. Therefore, this chapter introduces the simulation of events to arm
yourself with an alternative strategy to evaluate probabilities. All you need to
implement simulations in R is to learn few more functions and understand the
law of the large numbers.

4.1 The law of the large numbers


Until now, we have worked with the theoretical probability, which we
defined as the chance or possibility of an event happening. However, there is
an important difference in how often an event occurs and how often an event
should occur. For example, in the last chapter we found a theoretical combo
probability of 0.0098 or 0.98%, which means that we are expected to get our
combo about once in every 100 starting hands. Nonetheless, we could do the
real experiment and find that we are lucky to get our combo in 5 of the 100
trials. This would suggest an experimental probability of 0.05 or 5%. This
doesn’t mean that the calculation of our theoretical probability is wrong, still,
the experiment is different than the theory. And maybe we repeat the
experiment just to find that we don’t get our combo at all, which would mean
an experimental probability of 0%, But do not worry, this is normal in the
study of probability and statistics due to the random occurrence of events.
However, as we increase the number of experiments, the experimental
probability gets closer to the theoretical probability. At some point, when the
number of experiments is large enough, the experimental probability would
be equal to the theoretical probability. This is the law of the large numbers.
Let’s consider the case of Snipe Hunter as an example of this law. This
monster allows us to discard 1 card to target 1 card on the field and roll a 6-
sided die. If the result of the die is not 1 nor 6, the target is destroyed.
Therefore, the theoretical probability to destroy a card is calculated as the
quotient of 4 desired outcomes and 6 total outcomes.

According to the theoretical probability, Snipe Hunter is expected to


succeed in 2 of every 3 trials. However, we can roll the die three times and
find that the results are 3, 4, and 2, in other words, 3 successes in 3 trials.
This would mean an experimental probability of 1 or 100%. However, this
result considers only 3 trials, but we can update it if we roll more dice and
include their outcomes to the previous ones. For example, rolling 3, 2, and 1
together with the previous 3, 4, and 2 results in 5 successful events of 6, from
which we obtain an experimental probability of 5/6 ≈ 0.83 or 83%. Similarly,
the experimental probability is updated as the number of rolls increases, as
shown in Table 4.1.
Table 4.1. Experimental probability for the successful event of destroying a card with Snipe Hunter.
The card is destroyed when other than 1 or 6 is rolled in a 6-sided die.

So, according to the law of the large numbers, the experimental


probability must equal the theoretical probability as the number of trials
increases. This is visualized in Figure 4.1 in which the experimental
probability is updated and plotted as the die is rolled 1000 times. It is
observed that both probabilities are approximately equal to 0.67 around the
40th roll. After that, the experiment slightly deviates from the theory but
returns to it once again close to the 90th and 250th rolls. Once the die is
rolled 1000 times, the final experimental probability obtained is
approximately 0.64, which is close the theoretical value.
Figure 4.1. Plot of experimental probability for the successful event of destroying a card with Snipe
Hunter as a function of the number of rolls.

As you can observe, there are sections of the plot in which experiment
and theory do not agree. Still, we can obtain a good approximation to the
theoretical probability if the experiment is simulated enough times. This is
possible thanks to the law of large numbers. Therefore, understanding this
law is extremely important for duelists like us because Yu-gi-oh! and card
games in general are full of uncertainty. Often we need to take a decision
between two or more options. Therefore, it is our responsibility to analyze
our available options and choose the one that can accomplish our desired goal
with the higher odds in our favor. However, keep in mind that even the best
analysis and the most logical decisions can disappoint us sometimes. When
this happens, we do not need to worry or feel bad about it. This is part of the
game and that is also a reason why we play it and feel passionate about it.
Instead, understand that this is just a failed trial in a massive experiment in
which the law of the large numbers is going to do its job in the long term.
Another valuable reason to use a statistical approach to evaluate a
probability is that there are some times in which calculations with the
multivariate hypergeometric distribution get more complex than we would
like. This is common in Yu-gi-oh! due to the immense variety of effects and
restrictions that cards can have. Fortunately, the law of the large numbers
allows us to approximate the theoretical probability from experimental data.
But do not worry, you do not need to roll 1000 dice or shuffle and draw 1000
hands because now you will learn how to easily do massive experiments in R.

4.2 Probabilities via simulations in R


Simulation of events require us to apply many new R functions and
combine them into a single code. However, moving straight to the finished
code can be confusing for duelists unexperienced with programming,
therefore, we are going to follow simple examples for each function needed
to finally combine them when each one of them is clear enough. This
approach will also give you the knowledge needed to create and modify your
own programs according to your needs, combos, and decks. As usual, start by
loading a complete decklist to R with the read.csv() function. The one shown
here is an example of the popular Blackwing strategy used in 2009 and 2010.
If you have doubts on how to load it, make sure to have a look to the
Appendix section.

Table 4.2. Main deck example of a Blackwing decklist.


Now draw 6 random cards from your deck with the sample() function.
Remember that this function requires a vector as an input, so you need to
introduce an argument such as Deck$Cards to make it work. In this example I
drew Royal Oppression, Blackwing – Vayu the Emblem of Honor, Blackwing
– Sirocco the Dawn, Black Whirlwind, Dark Armed Dragon, and Book of
Moon. Keep in mind that this is a random process, so I can almost guarantee
that my cards are different than yours, as in a real duel.

The next step is to write some vectors with combinations of cards you
are interested to draw in your starting hand. As an example, I wrote
Blackwing – Sirocco the Dawn (BSD) and Black Whirlwind (BW) as
Combo1, and Blackwing – Shura the Blue Flame (BSBF) and BW as
Combo2. These were usually nice cards a Blackwing player could start with,
but you can modify the vectors as you please.

Once you are ready with your combos, you can ask R if all the elements
of a particular combo are available in the hand of 6 cards you previously
drew using the all(condition) function and the %in% notation. Here, the
output of all(Combo1 %in% Hand) is TRUE because both BSD and BW are
found in the example hand. However, the output of all(Combo2 %in% Hand)
is FALSE because although BW is found in Hand, BSBF is not.
Now let’s learn about the If – Else statement. This instruction has the
form if(condition){code 1}else{code 2} and it allows us to execute one of
different pieces of code according to an established condition. In the example
below the condition is, all(Combo1 %in% Hand)==TRUE. This means that if
all the cards of Combo1 are available in Hand, then the If – Else statement
will execute the line of Code 1, otherwise, it will execute Code 2 when not all
the cards of Combo1 are available in Hand. Here, Code 1 also adds 1 to the
current value of the variable, Success, which is initially defined as 0. Then,
this value of Success + 1 is assigned once again to the variable Success to
replace the old value of 0 with a 1.

Alternatively, Code 2 is executed when the cards in our combo are not in
Hand. In Code 2, the variable Success is assigned once again with the current
value of Success. Since the initial value of Success was 0, then Success is
again 0.
Something to keep in mind with the If – Else statement and other
programming structures in general is that we need to respect the way in
which they are written. Make sure to type in a new line when needed as
shown in the examples. Also, pay attention to the double equal sign in the
condition line. Additionally, you may find convenient to type and run these
examples as a script in the upper left panel of RStudio. If you have doubts on
how to do that, please check the Appendix.
Now let’s use another structure to complete our simulation. This is, the
For loop, and it is written as for(variable in vector){code}. The purpose of
this structure is to repeat lines of code multiple times. Here, the variable can
take any name and it does not need to be predefined. Usually, programmers
use, i, for this purpose, but as you can see, I used the variable Trial.num.
Then comes the vector, which can be predefined if you want. In this example
I typed 1:Trials as the vector, where, Trials, was predefined as 3. This means
that the vector used contains the elements 1, 2, and 3. Finally, the code to
execute simulates the drawing of 6 cards from the deck and shows them with
the print() function, which is used to display results when you work with
scripts in RStudio. I also included print(“”) just to introduce an empty row
between each simulated hand. As you can see, the full code simulates the
drawing of 3 hands of 6 cards each. Once again, keep in mind that this is a
random process, therefore the cards drawn change every time you run the full
piece of code.
Feel free to play with the parameters of this structure. Increase the number
of trials, decrease the quantity of cards to draw, print extra messages. It is up
to you. Make sure both structures are clear to you, because the next step
combines every function in this section.
As you can see, the new code includes the Trials and Success variables at
the beginning. Then comes the For loop, which is executed 3 times as defined
in the variable Trials. However, this time the If – Else statement is placed
inside the For loop, right after the simulation and printing of the hand. This
allows our program to ask if our combination of cards is available in the
simulated hand. Here, remember that our combo was previously defined as a
vector named Combo1 with elements BSD and BW. Finally, the purpose of
the Success variable here is to keep track of how many of the 3 simulated
hands include Combo1. Notice that the Success variable was initially 0,
however, it updates according to the If – Else statement each time the For
loop is repeated.
In summary, the complete code simulates a random hand of 6 cards and
checks Combo1 is included in Hand. This process is repeated 3 times, and it
is observed that both BSD and BW are included in the first and second hands,
but not in the third one. As a consequence, the Success variable is updated
from 0 to 1 after the first iteration, then from 1 to 2 after the second iteration,
and finally from 2 to 2 once again after the third iteration.
Finally, the experimental probability to obtain at least 1 BSD and at least
1 BW when 6 cards are drawn from a 42-card deck with 3 copies of both
cards is obtained as the quotient of the final value of the Success variable
divided by the number of Trials implemented in the simulation. In this case,
that value is 2 / 3 ≈ 0.67 or 67%.

However, this number looks suspiciously optimistic considering the


knowledge and practice we have obtained in the previous chapters. In fact,
we can use binomial coefficients to find that the theoretical probability for
each hand with at least 1 BSD and at least 1 BW does not agree with our
experiment. This is shown in terms of percentage in Table 4.3, where we
consider that our 42-card deck includes a total of 3 BSD, 3 BW and 36 other
cards. Here, the probability for each of our possible combo hands is added
together to result in an overall combo probability of 0.1274 or 12.74%
approximately.
Table 4.3. Probabilities for different combo hands.

Now go back to the R script to calibrate the calculation of the


experimental probability. To do this, just repeat the simulation with different
values of the Trials variable as shown in Table 4.4. Here, you can see now
that the experimental probability gets closer to the theoretical value of 0.1274
as the number of Trials is increased.

Table 4.4. Experimental probability as a function of successes and trials.

Remember that this expected according to the law of the large numbers.
Also, notice that the previous simulation with 3 Trials and 2 successes seems
more like an unusual case. However, at this point you may be wondering how
many simulations are needed to estimate an experimental probability as close
as possible to the theoretical one. Usually, a large number such as 1000 or
10000 is enough for our needs. Still, we can take advantage of some R
functions to explore the answer, but first, we need to make some adjustments
to our code. Basically, we just need to add the term [Trial.num] with the
square brackets included next to our Successs variable. This produces a
vector where each element is every single output of the If – Else statement as
the For loop is cycled. As a result, we get a vector with 10 elements. One for
each trial. An advantage of this notation is that we can now find exactly
whether a trial results in a combo or not. Here, only the third and eight trials
include BSD and BW in Hand.

Then we can obtain a vector with the accumulated sum of successes to


keep track of the maximum value of the variable Success as a function of the
trial number.

Therefore, the updated value of experimental probability as a function of


the trial number is obtained by dividing each position of the accumulated
vector by its respective number of trial. Here, I rounded the value of
probability to two decimals with the round() function just for simplicity.

Finally, we can produce a simple plot of the updated value of


experimental probability as a function of trial number. In the example below I
include plots with simulations of 10 and 1000 trials. This approach is useful
to figure out whether the experimental probability has converged towards the
theoretical probability according to the law of the large numbers. In this
example, 2000 trials seem good enough to reach a probability of 0.1274, as
calculated with the binomial coefficients. Still, consider to do more trials
when possible.

And that’s it! Our program is able to find combo probabilities without
the need of binomial coefficients. Something extremely helpful for decks and
combos with multiple copies of a card. Now, applaud yourself for your
effort! There was certainly a large amount of information in this chapter but I
can promise you that it is worth it. Now you have a statistical technique to
evaluate probabilities. This is going to get even better by the end of the next
chapter. At that point, you will be ready to evaluate experimental
probabilities for some combos not considered in this section and also for
multiple combos at the same time.
5. Binomial eXperYmentZ
“Whoever can open this door will gain a great new power, but know that
with such a reward comes great risk. Have you the courage to unlock this
power?”

Find multiple combos in thousands of tests hands. Then, use the


binomial distribution to predict the consistency of your strategy through a
series of duels.
S ome duelists may remember the Synchro era as one of the most exciting in
the history of Yu-gi-oh! And there are definitely many reasons to suggest
that. One of those is that Synchro Monsters raised but also balanced the
power level of multiple strategies to allow them to take part in the
competitive game. Now that devastating monsters such as Trishula, Dragon
of the Ice Barrier were resting in the Extra Deck, it did not matter if your
favorite strategy was not compatible with Chaos monsters, Dark Armed
Dragon, Gladiator Beast Gyzarus or other boss monster. What duelists
looked for at this point of the game was a strategy to quickly summon a mix
of Tuner and non-Tuner Monsters to gain access to the Extra Deck.
Therefore, even cards that could special summon low ATK monsters had a
great impact on the game. Some examples include Rescue Cat and the X-
Saber archetype, Fishborg Blaster and Water Monsters, Rekindling and Fire
Monsters, Dandylion and other Plants, The Agent of Creation – Venus and
Fairies, Debris Dragon, Reborn Tengu, Doppelwarrior, and many more.
Additionally, cards such as T. G. Hyper Librarian and Card of Safe Return
motivated the players to focus on fast summoning strategies. This shift in the
game brought diversity to the tables as never seen before. Dark and Light
Monsters were not the only candidates to win a tournament anymore.
Duelists could choose and assemble strategies not only to play, but also to
express themselves in the duel. Also, new archetypes expanded the lore of
duel Monsters to make the game feel like a war for supremacy.
Eventually, fast summoning strategies became so common that duelists
adopted a combo mentality. What I mean by this is that players could
automatically identify a combination of cards in their starting hand and
immediately visualize an achievable goal such as a field full of powerful
monsters, or even a play to discard all the cards in the hand of the opponent.
This often required a good amount of hand testing and practice prior to the
real duel. However, this also caused duels to become more predictable. Now,
skilled players only needed to see the first card played by their opponents to
figure out their strategy. This was as valuable as knowing your own strategy.
However, it was a matter of time for things to change once again. On
August 2011, the Synchro era paused indefinitely and opened the Extra Deck
door for the Xyz Monsters. Their summon mechanic just needed to overlay
two or more monsters of the same Level to Xyz Summon an Xyz Monster of
equal Rank. This easier summon mechanic introduced some changes to the
basic rules of Yu-gi-oh! among which the two most notable were the debut of
Rank number and Xyz Materials. The first one of them was basically like the
well-known Monster Level but only for Xyz Monsters. Since they had a
Rank, they were not considered to have a Level. The second change was that
the monsters used to summon an Xyz Monster were not sent to the
Graveyard. Instead, they turned into Xyz Materials placed on the field but
under the Xyz Monster in some kind of limbo which was not the hand, the
field or the Graveyard. Then, these Xyz Materials could be detached from the
Xyz Monster to activate its effect. For this particular conditions, Xyz
Monsters were barely popular during their release. Their lack of Level made
them incompatible with successful Synchro strategies. Also, popular monster
effects activated in the Graveyard were now difficult to use because Xyz
Materials were somehow trapped below the Xyz Monsters. However, duelists
eventually adopted Xyz Monsters as a fundamental part of their deck because
the following banlists made sure to hurt the remaining Synchro strategies and
because of a lack of Tuners Monsters in the following sets. This opened up
the path for a new era of Yu-gi-oh! which was generally slower than the one
before.
The first successful Xyz strategy was the one named as Dino-Rabbit,
which used Rescue Rabbit to summon 2 Normal Monsters from the deck. In
this case, 2 Level 4 Dinosaur monsters to Xyz Summon Evolzar Laggia or
Evolzar Dolkka according to the needs to negate the summon or effect of
Monsters, respectively. Other than that, the deck included a large amount of
traps to slowly exhaust the opponent.
Then came 2012, which revolutionized the competitive game with its
first set, Oder of Chaos. Newcomers in this set were the Inzektorz, which
despite their low ATK were extremely effective to destroy cards on the field
and to generate card resources at the same time. This set also established the
Wind-Up archetype as one of the top contenders of that time. This was thanks
to the release of Wind-Up Rat and Wind-Up Carrier Zenmaity which
combined with the already available Wind-Up Hunter to hurt the hand of the
opponent and still defend the field with Wind-Up Zenmaines.
At this point, it was already clear that Xyz Monsters could not be ignored
anymore. Even previous strategies such as Gadgets, HERO and Lightsworn
benefited from the use of the new Extra Deck Monsters. Still, there was one
contender able to compete against Dino-Rabbit, Inzektor and Wind-Up
without the need of Xyz Monsters. This was the Chaos Dragon strategy,
which used a Lightsworn engine to quickly load the Graveyard with Dark and
Light monsters. This made easier to summon the mighty and resilient
Lightpulsar Dragon, whose 2500 ATK was above the oppressive Evolzar
Laggia and Evolzar Dolkka. It also had the effect to special summon high
Level Dark Dragons from the Graveyard when sent from the field to the
Graveyard. This made an excellent team with Red-Eyes Darkness Metal
Dragon to revive more Dragon monsters and offer an edge against Inzektor.
And if it was not enough, Lightpulsar Dragon also had an effect to Special
Summon itself from the Graveyard, which sometimes came useful against the
Wind-Up hand loop. These effects plus cards such as Future Fusion and
Five-Headed Dragon, Eclipse Wyvern and Dark Armed Dragon, and the once
again available Black Luster Soldier - Envoy of the Beginning made Chaos
Dragon a powerful and consistent strategy.
The end of 2012 was very different though. Chaos Dragon and Inzektor
took a step back in the competitive game due to a new banlist, whereas Dino-
Rabbit and Wind-Up managed to update their strategies to stay competitive.
The Mermail and Atlantean archetypes were also released back then to make
Water Attribute decks one of the fastest and most dangerous combo-based
decks of the Xyz era. On the other hand, the Brotherhood of the Fire Fist
archetype released at the beginning of 2013 offered a slower and more
control-oriented but still effective strategy. This quickly turned into an
intense but short-lived battle between Fire and Water decks that ended with
the release of much more powerful cards in the following set, Lord of the
Tachyon Galaxy. This set included Evilswarm Kerykeion, which turned the
Dark Attribute Evilswarm archetype into a viable strategy. There was also the
insane Spellbook of Judgment, which was capable to add lots of Spellbook
cards to the hand and make the Spellbook archetype a top contender. But
above everything were Redox, Dragon Ruler of Boulders, Tempest, Dragon
Ruler of Storms, Tidal, Dragon Ruler of Waterfalls, and Blaster, Dragon
Ruler of Infernos. Four Level 7 Dragon monsters of Earth, Wind, Water, and
Fire Attributes respectively. Each one of them offered great support to
strategies based on their respective Attribute, but players soon found that the
best option was to use them together with the 4 Level 3 younger versions of
the Dragon Rulers. This produced what some people think has been the most
powerful Yu-gi-oh! deck of all times.
This deck had high ATK Monsters that could be easily summoned from
the hand, deck or Graveyard. Each of the mature Dragon Rulers had a search
effect to make the whole strategy consistent and versatile, as well as a
singular effect useful to overcome difficult situations. Also, their Level 7
provided access to powerful and game defining Rank 7 Xyz Monsters such as
Mecha Phantom Beast Dracossack and Number 11: Big Eye. Other important
cards were Sacred Sword of Seven Stars, Super Rejuvenation, Gold
Sarcophagus, and Card Destruction to accelerate their plays and obtain more
resources. And if it wasn’t enough, the deck benefited from the still unusual
“Handtraps” of that time, which were Monsters such as Effect Veiler and
Maxx "C" capable to disrupt the opponent by discarding themselves from the
hand even during the turn of the opponent. All this made Dragon Ruler a fast,
powerful, consistent, resilient, and recursive strategy with practically no weak
points. Then, the banlist of September 2013 attempted to stop Dragon Ruler
by banning a numerous amount of cards such as the 4 younger dragons,
however, this was not enough. The four remaining Dragon Rulers lost some
speed and consistency, but the creativity of duelists managed to evolve them
into an unpredictable, more versatile and even more powerful strategy. This
was possible with the help of new Synchro Monsters and other compatible
Dragon strategies such as Dragunity and Blue-Eyes White Dragon. This
period of the game somehow returned the feeling of those exciting back and
forth unpredictable duels that had slowly faded away during the previous
years. On the other hand, it became more difficult to compete against the now
named Ravine Rulers with something different than Ravine Ruler. This was
the case until January 2014 when the mature Dragon Rulers were limited and
other key cards of the deck got banned. And although this did not make them
disappear from the competitive game, they started to share tables with new
Xyz oriented archetypes such as Geargia, Bujin, Constellar, Sylvan, Artifact
and other strategies.
Overall, the Xyz era showed more diversity than ever before with the
exception of the Dragon Ruler formats. On the other hand, the popularity and
availability of archetypes guided the players to plan their decks around
predictable strategies. And as expected, most duelists relied on practice and
experience to build their decks rather than on analysis or probabilities.
Therefore, in this chapter you will complete your training with simulations in
R to find the probability of any combo or play you want to implement. Then,
you will learn the binomial probability function to figure out how reliable a
strategy can be in a tournament.

5.1 The binomial and cumulative probability


At this point you already know how to evaluate the probability to draw
almost any combination of cards from a deck. However, the values you have
obtained apply only to Bernoulli trials, in other words, single random
experiments whose possible outcome is either success or failure. This means
that you can estimate how likely is to find a combo in a starting hand, but you
may need to refine your calculations to consider multiple trials or opening
hands, as it happens in a Yu-gi-oh! tournament. To do this, we are going to
use the binomial probability mass function (PMF) to evaluate a binomial
experiment, which is nothing more than a fixed number of Bernoulli trials.
The PMF is useful to find the binomial probability, P(k), of obtaining exactly
k successes in a binomial experiment with n number of trials as long as the
probability of success in the Bernoulli trial, p, is known, as shown in Eq. 5.1.

Notice how the term nCk in Eq. 5.1 refers to the number of combinations
of k successes in n trials. Also, since p is the probability of success in the
Bernoulli trial, then the term (1 – p) represents the complementary event, or
in this case, the probability of failure. Similarly, n – k is equal to the number
of failed events. But how does this relate to Yu-gi-oh! you may ask. Well,
let’s say that you know a combination of cards that makes you feel pretty
confident to win the duel as long as you manage to get them in your opening
hand. Won’t you like to have such hand in at least 2 of every 3 duels? For
that reason, you now need to know how likely is your strategy going to work
in a match rather than on a single duel. To explore this, let’s consider Figure
5.1, which shows all the possible ways in which you can win a match based
only on the probability to obtain a particular combo. Here, there are 3
possible scenarios to be declared the winner, which are: 1) succeed on duels 1
and 2; 2) succeed on duel 1, fail on duel 2, and succeed again on duel 3; and
finally 3) fail on duel 1 and succeed on duels 2 and 3.
Figure 5.1. Possible scenarios to win a match in which duels are won depending on the success of
obtaining a combo.

With this in mind, we can now use the multiplication rule to calculate the
probability of success for each scenario provided that the probability to
obtain a combo does not change from duel to duel as a consequence of side
decking, due to the actions of the opponent or due to something else. Here,
let’s assume that p = 0.6 or 60% to find our desired cards in the opening
hand. Therefore, the probability for each scenario is calculated as shown in
Table 5.1.

Table 5.1. Scenario probability calculated with the multiplication rule.

As a result, the probability to obtain a combo with a probability of p=0.6


in 2 out of 3 duels is calculated as the sum of probabilities.

Now, let’s attempt to obtain the same result using the PMF. Here, the
number of events is n=3, the number of successes is k=2, and the Bernoulli
probability is p=0.6.
It seems that the multiplication rule and the PMF do not agree. However,
what the PMF is actually calculating is a binomial probability in which
exactly 2 out of 3 starting hands contain a combo. As a consequence, the
PMF considers a case in which a 3rd duel is played and lost despite winning
the 1st and 2nd duels, as shown in Table 5.2. On the other hand, the value
obtained with the multiplication rule considers the case of a real match in
which, of course, there is no need to play a 3rd duel when the winner of the
match has already been decided in just two duels.

Table 5.2. Binomial probability for a binomial experiment with n=3, k=2, and p=0.6 calculated with the
multiplication rule.

If we now consider the scenarios shown in Table 5.2, the probability to


obtain a combo in 2 out of 3 duels now equals P(k) obtained with the PMF.
To address this discrepancy, consider what would happen if duelists were
forced to play the 3rd duel all of the time despite the result of the previous 2
duels. This would cause a total of 8 possible scenarios, in which a player
could win 0, 1, 2, or 3 duels in a match in different order. In other words, 8
permutations. Now, how would that affect the probability of our combo
during the match for each of the possible 8 scenarios if the combo probability
is still equal to 0.6? The answer is shown in Table 5.3. Notice that the total
probability for the 8 events is equal to 1, as expected, but also, see that the
addition of probabilities for the last 2 events ( ✔✔❌ , ✔✔✔ ) is 0.144 +
0.216 = 0.360, which is equal to the probability of the first scenario on Table
5.1. This value added to the probability of the other scenarios with two
successes is equal to 0.648, which equals the sum of probabilities of Table
5.1 too.

Table 5.3. Binomial probability for a binomial experiment with n=3, p=0.6 and k in the range from 0 to
3.

Therefore, this is a good time to introduce the cumulative probability,


which is the probability to find k in a range of values. In this case, the
question we should focus is, what is the probability to combo in at least 2 out
of 3 duels of a match when the combo probability is equal to p=0.6? This can
now be obtained with the PMF by calculating the cumulative probability
when k ≥ 2 as follows.

It may be somehow confusing to see the term P(k=3) in the calculation


above given that a Yu-gi-oh! match cannot have a player with 3 duels won.
Still, we need to consider this case because the PMF does not expect the
number of trials in a binomial experiment to change according to the results
obtained, as it does in a match. Therefore, we use the cumulative probability
to analyze this experiment. On the other hand, we use the binomial
probability to find the probability of an exact number of successes among a
number of trials.
Now have a look to Figure 5.2 which shows the probability P(k) as a
function of the number of successes k, for a binomial experiment with n=3
trials and a Bernoulli probability of p=0.6. Such visualization can be very
useful to quickly identify how many successes are needed to obtain the
maximum probability.
Figure 5.2. PMF and PDF of a binomial experiment with n=3 and p=0.6.

In this case, it is clear that a combo with p=0.6 is more likely to succeed
in 2 out of 3 duels rather than in 0, 1, or 3 out of 3 duels. In fact, it is more
likely to succeed in 1 out of 3 trials than on 3 out of 3, which means that we
may have some deck building work to do in order to improve the odds.
Finally, Figure 5.2 also includes a curve or probability density function
(PDF) for non-integer values of k. These non-integer values are not expected
in our binomial experiments, but they are useful to improve our visualization
of P as a function of k. More details about the PDF are available in more
advanced books on probability, statistics, and calculus.

5.2 Binomial and cumulative probability in R


This time, we are going to use a Tempest Dragunity decklist played in
2013 to explore the probability of starting the duel with a big play, which can
be achieved with multiple combinations of cards. If you are not familiar with
the deck, let me tell you that Dragunity was a Synchro based archetype
assembled by Dragon and Winged Beast monsters originally released in Duel
Terminal 3 and Hidden Arsenal 3 near the end of 2010. Its main attractive
was the possibility to summon high Level Synchro Monsters with a low card
investment, however, this strategy was too slow to be noticed in the
competitive game. On 2011, Dragunity received its key Synchro Monsters in
the Starstrike Blast set, whereas most of the other Dragunity cards became
easily available in the Dragunity Legion Structure Deck. This deck also
introduced new Dragunity Monsters and Dragon Ravine, a Field Spell that
increased the consistency of the deck, but not enough to compete with other
faster Synchro strategies. Then, the release of the Xyz Hieratic Dragon King
of Atum on 2012 allowed a fast and powerful 3-card combo. Unfortunately,
this combo had a chokepoint that decreased its consistency. This was, the
need to draw Dragunity Arma Mystletainn in the opening hand. However, the
release of Tempest, Dragon Ruler of Storms on 2013 offered multiple ways to
search it. This made Tempest Dragunity a fast, powerful, and highly
consistent strategy which I believe did not see enough success due to the
preference of duelists towards the Dragon Ruler strategy. Still, Tempest
Dragunity is a great example of a deck we can use to polish our R skills in
order to investigate the probability of combos and plays. Having said so, start
by loading the Tempest Dragunity decklist shown in Table 5.4 with the
read.csv() function.

Table 5.4. Main Deck example of a Tempest Dragunity decklist.


As mentioned earlier, Tempest Dragunity had a big initial play. This
required to Synchro Summon Dragunity Knight - Gae Dearg and another
Level 6 Dragon-Type Monster to the field to continue with the summon of
more powerful Monsters. Although this may sound somehow difficult, it was
rather easy due to the effects of cards such as Dragunity Dux, Dragunity
Phalanx, and Dragunity Arma Mystletainn, Dragon Ravine and Tempest,
Dragon Ruler of Storms. These last two cards were also searchable or had
synergy with Terraforming and Gold Sarcophagus. Furthermore, other cards
such as Monster Reborn, Foolish Burial, and Garuda the Wind Spirit were
sometimes helpful to achieve the same goal. This created a large amount of 3-
card and 4-card combinations capable to complete the big play. Many of this
combinations were difficult to have in mind before the duel, but they were
often recognized by skilled players while dueling. Therefore, in Table 5.5 I
show you some of these possible card combinations which we can use to
evaluate the probability of starting the duel with a big Tempest Dragunity
play. Some of these combinations required other random cards in hand to pay
the cost of Dragon Ravine, but that was rarely a problem at the beginning of
the duel. As you can see, these are too many combinations of cards to apply
the multivariate hypergeometric distribution or to conduct multiple
simulations for each single combo. Therefore, we are going to modify the
code written in Chapter 5 to test all 63 combinations at the same time in
10000 simulations. Also, we are going to improve the quality of the tests
performed.
Table 5.5. Possible card combinations for a big play.

Now, let’s input some vectors with a 3-card combo and a 6-card test
hand. The first one should include at least one repeated card, whereas the
second should include all cards in the first vector but without repetition, as
the example shown below.
Now, try to see if Test.combo is found in Test.hand with the all()
function as you did in the previous chapter. You may be surprised to get
TRUE as an answer despite Test.combo includes Dragon Ravine twice in the
vector whereas Test.hand includes it only once.

The reason why this happens is because the all() function does not check
for repeated values. This is inconvenient for us because Tempest Dragunity
used to create nice plays with some repeated cards unlike most decks.
Therefore, we really need to identify combinations of cards with repeated
cards. Fortunately, this is easily achievable with the vsetdiff(vector1, vector2)
function included in the vecsets package. However, that package is not
included among the default R functions, so you first need to write
install.packages(“vecsets”) in the R console. Then, type library(vecsets) in the
R console again to have access to the functions of the vecsets package. Keep
in mind that the installation of the package needs to be done only once, but
you need to call the library every time you open RStudio if you plan to use a
function included in the vecsets package. For more details, be sure to check
the Appendix section.
Now, you will have access to the vsetdiff() function once you have
successfully called the vecsets library. This function allows to find the
elements of a vector that are not in another vector, and the best of all is that it
considers the repeated elements. For example, the result of
vsetdiff(Test.combo, Test.hand) is 1 Dragon Ravine only because Dragunity
Phalanx in Test.combo is available in Test.hand, and because only 1 of the 2
Dragon Ravine in Test.combo is available in Test.hand. Therefore, only 1
Dragon Ravine remains.

We can take advantage of this operation to identify when all the elements
of a combo are in a random hand. Notice that the length of the vector
obtained with the vsetdiff() function is 0 when all the elements of the first
vector are available in the second vector. Otherwise, the result is greater than
0.

With this in mind, we just need to code an If - Else statement to identify


if a combination of cards in a random hand. But we are not going to stop
there. We are going to take this code one step further and program our own R
function to use it later in this project. To do this, start with a name to your
newborn function. Mine is, Find.combo. Then assign the name of the
function to the structure function(input){code} where input can have any
name to represent the data you plan to use as the argument of your function,
and code is the instruction to perform. Keep in mind that both parameters can
vary in length, name or other according to the needs. Here, the name of my
input is, Combo, and my code to execute is a simple If - Else statement as
shown below, in which the length of our vector obtained from the vsetdiff()
function is compared to 0. If the length is 0, then the function returns TRUE,
otherwise it returns FALSE. Something crucial here is to respect the position
of the parentheses and curly brackets used to define the If - Else statement as
well as the new function.

Once you have your own function, you can use it to quickly test combos
in a hand without typing too much code. Notice that our new function accepts
any vector as an input, however, the code we programmed strictly compares
the input with the vector named as Hand, which I redefined for each example
below. This will be extremely useful later.

Ok, now comes the painful part of the code. We need to introduce all of
the possible combos we have identified as individual vectors in order to test
them with the random hands we draw. It is not difficult, but it can be a long
typing task depending on the complexity of the deck to simulate. Here, the
picture below only shows 8 of 63 combos introduced. This task can be
somehow easier with some programming skills for some decks, but since the
number of decks played keeps growing and their strategies keep changing,
the best I can show you here is a generic solution that requires minimum
programming skills in exchange of some knowledge of the deck to simulate.
Here, my experience as a Tempest Dragunity duelist in 2013 allowed me to
identify the combos shown in Table 5.5 to produce a big play. I admit that I
most probably missed some combos that can achieve the same result, still I
guarantee that this simulation is going to provide us with an extremely useful
result. Also, keep in mind that Tempest Dragunity had an enormous number
of plays due to the synergy of its cards included.

The next step is to gather all of your combos into a single data structure
known as list, which is basically a container of data, or in this case, a vector
of vectors. To do this, just type all the combos inside the list(elements)
function.
One good reason to place all the combos inside a list is that now we can
apply a function to all vectors in a simply way. As an example, draw 6 new
random cards from your deck. Then, use sapply(list, function) to apply the
custom Find.combo() function to the 63 vectors contained in the list,
Combos. This way we can quickly see that combos 1, 8, and 21 are included
in our opening hand.

Since all 63 combos aim for the same goal, it may be a better idea to
identify if at least one of the results obtained is TRUE. This is easily done
with the any(vector) function.
Now, let’s put everything together and evaluate the experimental
probability of getting any of the 63 combos in 10000 simulated hands. This
requires to update the For loop used in Chapter 5 with the newly defined
Find.combo() function and the list of combos to test. Keep in mind that such
simulation may take few minutes to complete, so you may want to try a lower
number of trials. Additionally, you can plot the experimental probability as a
function of the trial number as done in Chapter 4.

Here, our big play is achieved in 5063 of the 10000 hands simulated,
which results in an experimental probability of 0.5063 or 50.63%. It was not
a bad probability in 2013, especially considering that Tempest Dragunity had
other minor but still effective and more common plays.
Now, it is time to use our knowledge about the binomial PMF to
anticipate the behavior of our strategy in a tournament. For this, let’s use our
experimental probability p = 0.5063. Also, let’s consider 4 different
tournaments of 5 rounds each. This means that we are expecting to play a
maximum of 15 duels per tournament. With this information in hand, we can
use the rbinom(a, b, p) function where a represents the number of
experiments, b the number of trials in each experiment, and p the probability
of success. Therefore, we use rbinom(4, 15, 0.5063) in this case. With this,
we can anticipate that it is possible to obtain our big play in 5, 10, 8, and 8 of
the 15 duels expected in each tournament.

Notice that the big play appears as expected in 2 tournaments and even
more often than expected in another one. However, keep in mind that there
may be some tournaments where things just do not go as we expect them. For
that reason, we must aim to increase p as much as possible, but also include
alternative plays as a plan B in case of disruptions cards or unlucky hands.
Last but not least, recognize that duels are often won not by doing everything
right, but by doing less mistakes than the opponent, therefore, it is extremely
important to learn to play bad hands as much as the good ones.
Now, let’s have a look to some other useful binomial calculations in R to
conclude this chapter. For this example, let’s consider a tournament of 8
rounds, so that adds up to a maximum of 24 duels. What is the probability of
opening a big play in 12 out of 24 duels given our play probability of 0.5063?
To answer this we use the dbinom(a, b, p) function, where a is the number of
successes, b the number of trials, and p the probability of success. This
results in the same value obtained with Eq. 5.1
This value may look small for you, but keep in mind that this is the
probability to obtain exactly 12 successes out of 24 when p=0.5063. To test
for multiple successes, just type a vector as the a parameter of dbinom().

Now plot it to visualize quickly visualize that it is more likely to succeed


somewhere in the range of 10 to 14 duels of the 24 expected to play. Also,
see that the maximum probability occurs when k=12.
Finally, the probability to succeed in 12 or more duels is obtained with
the addition rule for all the values of probability when k ≥ 12.

And that’s it! Put everything together and you get a complete code to
evaluate the probability to obtain multiple combinations of hands through a
simulation approach. Feel proud of yourself if you have reached this far. All
that is left now is to polish few details, but be sure that the knowledge
obtained here will put your deck building and hand testing skills far above the
average duelist.
6. Swing pendulum! Draw the
network diagram
“Ladies and gentlemen!”

In this chapter you will learn you how to create beautiful visualizations
to observe the connections existent between the cards of your deck in a new
way. Get creative because the fun has just begun!
T hethesummer of 2014 saw the arrival of some modifications to the rules of
game. The first one of them allowed both players to control a Field
Spell Card. Previously, no more than one Field Spell Card was allowed at
a time, and the activation of a second Field Spell automatically destroyed the
first one. This modification to the rule did not have a meaningful impact at
that time due to the seldom use of these type of Spells. On the other hand, the
second change had a serious and immediate effect to the game. Now, the first
turn player could not have a Draw Phase on the first turn anymore. This
decreased the probabilities to start with a long and powerful play that could
excessively complicate the participation and therefore the enjoyment of the
second-turn player. Basically, the first turn player received 5 cards to prepare
a good field, whereas the second turn player received 6 cards to attempt to
break the already established field of the opponent. However, these two
modifications were only preparations for the next evolution of duels, a whole
new era of Yu-gi-oh!
The new era, also known as the Pendulum era, introduced the Pendulum
Monsters, whose first members were, Timegazer Magician and Stargazer
Magician. Pendulum Monster cards had a design that shared the colors of
monsters cards in the upper half and Spell Cards in the bottom half. They also
had a dual role that allowed them to be used as any other monster but also as
a Continuous Spell Card when placed on one of the two new Pendulum Scale
zones added to the field. Furthermore, each Pendulum Monster included a
Pendulum Scale value. A duelist with two Pendulum Scales on the field had a
once-per-turn access to the controversial Pendulum Summon, which allowed
to Special Summon up to 5 monsters from the hand or face-up in the Extra
Deck to the field. Here, the face-up monsters in the Extra Deck were
Pendulum monsters sent from the field to the Extra Deck rather than from the
field to Graveyard according to their own new rules.
Not much later, the Duelist Alliance set introduced new Pendulum
Monsters. Sadly, for them, duelists ignored all the Pendulum Monsters in the
set except for Odd – Eyes Pendulum Dragon who was used competitively
some months later. However, this set is gladly remembered for radically
shifting the competitive game with the introduction of novel, powerful and
varied archetypes taking advantage of the previous summon mechanics.
These were, the Fusion-based Shadoll, the Xyz-oriented Satellarknight, and
the Synchro-based Yang Zing. All of them were also connected by a storyline
developed through the years to come in their respective Spell and Trap
Cards. Furthermore, the TCG version of Duelist Alliance also introduced the
Burning Abyss archetype which eventually adapted all the previous summon
mechanics mentioned except for Pendulum. It was clear that there was
something in Duelist Alliance for the enjoyment of every player. However,
competitively speaking, the Shadoll strategy was more effective than the
other 3. This was possible due to its faster playing style granted by its Spell
Cards, the powerful and oppressive effects of its Extra Deck monsters, the
versatility of effects of its Main Deck monsters, and the greater card
advantage offered as a whole. On the other extreme were the Yang Zing,
which could hardly keep the pace against the other contenders despite a
resilient defense, a disruptive Synchro Summon strategy during the turn of
the opponent, and the powerful effect of Baxia, Brightness of the Yang Zing.
Finally, the Satellarknight and Burning Abyss in the middle had their own
share of victories with easy to summon Monsters, card advantageous effects,
and versatile Trap Cards.
All four archetypes reinforced their strategies with the release of further
support, but also faced the challenge of Qliphort, the first competitive
Pendulum Monsters. This archetype took advantage of the latest summon
mechanic to consistently provide tributes for the Tribute Summon of
powerful Monsters. One reason why this was easily possible was due to the
versatility of Qliphort Scout, whose effect as a Pendulum Scale was capable
to add any Qli card from the deck to the hand every turn. Furthermore, the
deck was also compatible with floodgate Trap Cards, especially Skill Drain,
which slowed down the advance of most of the other popular strategies.
Few months later, more archetypes joined the battle with the release of
The Secret Forces, the first set of 2015. This set included the Yosenju and
Ritual Beast archetypes, but most notably, the Nekroz. These last were a
strategy assembled mostly by Ritual Monsters that rapidly positioned on top
of the game. These monsters had extremely powerful and oppressive effects
activated on the field as well as on the hand. Their searching capabilities were
exceptional too, which made Nekroz an extremely consistent strategy. And if
it was not enough, cards such as Shurit, Strategist of the Nekroz, Herald of
the Arc Light, and the Nekroz Ritual Spell Cards provided the card advantage
and multiple summon capabilities that Ritual strategies lacked in the past.
Their reign only came to an end with the release of the July 2015 banlist,
which allowed previous decks to compete once again with updated strategies.
At this point, it was clear that any strategy, even those with the most
complicated summon mechanics could be considerable contenders given the
correct support to generate field presence and card advantage. It did not
matter if the Main Deck monsters involved had low ATK or a lack of effects.
There were already a variety of powerful and generic Extra Deck Monsters
compatible with many strategies. This principle was mainly considered in the
design of new Pendulum strategies such as Igknight, Majespecter, and
Performage. These last, along other archetypes such as Masked HERO,
Kozmo and Infernoid established a new competitive game once most of the
late 2014 and early 2015 strategies were nearly banished by the November
2015 banlist.
The last days of 2015 saw the release of Pendulum Magician and Odd –
Eyes support. These combined very well with the Performage Pendulum
cards to conveniently Pendulum Summon high-level and powerful Monsters
such as Mist Valley Apex Avian, Odd–Eyes Pendulum Dragon, and
Majespecter Unicorn – Kirin. The large amount of resources generated by
these Pendulum Cards, the consistency of its plays, and the speed of its
strategy made Pendulum the dominant force of the competitive game. But its
dominance went even higher with the release of more Pendulum support in
Breakers of Shadows, the first set of 2016. Some notable cards included were
Performapal Monkeyboard, Performapal Pendulum Sorcerer, and Draco
Face–Off. This made Pendulum an unmatched force that required an
emergency banlist to allow a diverse format. This benefited reinvigorated
strategies such as Monarch and Blue–Eyes White Dragon in the following
months.
Then, the last span of the Pendulum era saw the introduction of many
new archetypes with a new lore that radically shifted the competitive game
once again. Many of them were completely ignored, for example, the
Chemicritter, Triamid, Aromaseraphy, and Crystron. Others, such as
Subterror and SPYRAL, found their place in the competitive game years
after. But the ones who found success during the second half of 2016 were
the Metalfoes, Paleozoic, and ABC. The first of these were Pendulum
Monsters with Scales of 1 and 8, card advantageous effects when used in the
Pendulum Zones, and no drawbacks as most of the Pendulum Monsters with
a high Scale value. These Monsters had no effect at all, but they had easy
access to powerful Metalfoes Fusion Monsters. Furthermore, they were easily
adaptable as a generic Pendulum engine for other decks, which allowed the
creation of hybrid strategies such as Metalfoes Yang Zing, Majespecter
Metalfoes, and Kozmo Metalfoes. On the other hand, the Paleozoic were a set
of Trap Cards with a variety of disruptive effects. But their most unique
characteristic was that they could be summoned from the Graveyard as
monsters. Once on the field, the were unaffected by monster effects. There
were also some Paleozoic Xyz Monsters easily summoned with the Paleozoic
Trap Cards, but the monster that made the whole strategy competitively
possible was Toadally Awesome. This last one was an Xyz Monster with an
extremely disruptive effect who offered support to the old Frog archetype.
This made possible the creation of the Paleofrog strategy. Finally, the ABC
machines offered a fast-paced, aggressive and disruptive although short-lived
strategy that hard core fans of the classic XYZ machines only dreamed about.
And then, 2017 changed the whole competitive game once again to make
almost every duelist forget how this Yu-gi-oh! era started. The culprits were
the Raging Tempest and Maximum Crisis sets that introduced the Zoodiac
and True Draco archetypes respectively. Also, the Dinosmasher’s Fury
Structure Deck that catapulted Dinosaur monsters to the top tables. Of these,
the Zoodiac strategy practically reinvented the Xyz mechanic by allowing to
Xyz Summon any Zoodiac Xyz Monster with a single Zoodiac material.
Therefore, this deck needed to summon just one Monster to go through the
effects of multiple Xyz Monsters in one turn. Furthermore, the non Xyz
Zoodiac monsters added an extra effect to the Xyz Monsters attached. And as
expected, there was a convenient effect for almost any situation. This made
Zoodiac a combo strategy that required few cards in the Main Deck to work.
And as seen in the past, this allowed players to fill the unused deck spaces
with plenty Trap Cards or even with key Cards of other archetypes to provide
hybrid strategies such as Zoo Lightsworn Zombie, Zoo Infernoid, and more.
On the other hand, the True Draco were high-Level Wyrm monsters that
redefined the Tribute Summon strategy. They were capable to tribute
Continuous Spell and Continuous Trap Cards too! Obviously, the archetype
had its own Spell and Trap cards specifically designed to keep the
consistency, speed, and recovery of the deck. They even had additional
disruptive effects when sent from the Spell and Trap Zone to the Graveyard.
Furthermore, the triumphant card of the True Draco archetype was the
overwhelming Master Peace, the True Dracoslaying King, a Level 8 Wyrm
with 2950 ATK and DEF unaffected by the type of cards used to Tribute
Summon it. Master Peace also had a highly destructive effect, and if this was
not enough, the Field Spell of the True Draco strategy just made it even more
powerful. This Field was Dragonic Diagram, and it offered 300 ATK and
DEF to True Draco and True King Monsters as well as protection from
destruction in battle once per turn. Also, Dragonic Diagram was capable to
search True Draco and True King Cards by destroying a Card in the hand or
field of the controller, which was not really a problem for True Draco
players. However, this last effect was also exploited by the Dinosaur duelists,
who often searched for True King Lithosagym, the Disaster to ignite combos
with Babycerasaurus to summon Souleating Oviraptor, an incredible
searcher of Dinosaurs. This gave Dinosaur players easy access to Synchro
Monsters such as Denglong, First of the Yang Zing through
Miscellaneousaurus and Jurrac Aeolo. This Synchro Monster had amazing
searching capabilities that offered impressive disruptions effects. This just
required the addition of few Yang Zing Cards to the deck.
Overall, the Pendulum era increased the speed and power of strategies
more than any other period in the history of Yu-gi-oh. The versatility of cards
increased, the summon of multiple monsters at the same time became
something trivial, and first turn combos to produce unbreakable fields
became the new objective. Finally, duelists learned to mix different
archetypes to produce hybrid strategies with a common engine. This last
point will be the focus of this chapter. Now, you will learn to visualize the
connections of the cards in your deck as never before!

6.1 Network diagrams


Network diagrams, also known as graphs, are useful plots to see the
connections existent between the elements of a group. A common example is
the subway map, which shows the connection between different points of a
city. However, network diagrams are also used as graphical and abstract
representation of many other situations and activities such as participation of
people in clubs, flow of traffic, states or conditions of any kind of sequential
activity, and more. Obviously, games can take some advantage of network
diagrams too. As an example, Figure 6.1 shows a network diagram of the
non-Extra Deck Yang Zing monsters released in Duelist Alliance. All of them
shared an effect that allowed them to Special Summon a different Yang Zing
monster from the deck when destroyed by battle. Here, each connection line
is called as edge, whereas each card is a node or vertex.
Figure 6.1. Network diagram for Yang Zing Monsters.

Edges on network diagrams can also have a direction to show whether a


connection goes in or out of a vertex. For example, Figure 6.2 shows a
diagram with the 9 non-Extra Deck Yang Zing monsters released. Here, each
of the 7 non-Pendulum Monsters have 8 edges in total. All edges go out
because they can summon any of the other Yang Zing Monster from the
deck, but only 6 of them go in because they can be summoned just by 6 of
their brothers. This is because the 2 Pendulum Monsters do not have a
Special Summon effect, which leaves them with 6 edges going in.
Figure 6.2. Directed diagram for the Special Summon effect of Yang Zing Monsters.

There are many more things to explore with network diagrams. In fact,
there is a whole mathematical theory behind them that would require entire
books to describe it. Here, we are going to use them to produce simple
visualizations of the interactions that exist in a deck of cards. The purpose of
this is to get a quick idea of what cards are central in a strategy and how
different engines can connect to each other.

6.2 Network diagrams in R


This time, we are going to use network diagrams to obtain a visualization
of the interactions existent in the Yang Zing Zefra deck used at the end of
2015 and beginning of 2016. Therefore, let’s start with some characteristics
of the deck.
The Yang Zing archetype is based on 9 Chinese mythological sons of a
Dragon King. They all have dragon-like bodies mixed with some animal
characteristics. Since there are 9 dragon sons, there are 9 Main Deck Yang
Zings monsters too. However, the names of the sons change according to the
source of the tale, which is convenient to print more Yang Zing monsters,
such as 4 other Synchro Monsters. 7 of the Main Deck monsters share an
effect that allow them to summon another Yang Zing monster from the deck
when they are destroyed by battle or card effect and sent to the Graveyard.
The remaining 2 are Pendulum Monsters whose names make them members
of two different archetypes at the same time, the Yang Zing and the Zefra.
The Zefra is a hybrid archetype assembled by Pendulum Monsters. There
are a total of 10 Zefra monsters divided into couples to include the name of 1
of 5 archetypes. These are the Yang Zing, Shadoll, Tellarknight, Nekroz, and
Ritual Beast. Additionally, there are 2 other unique Zefra monsters. The idea
behind these monsters is to provide support in the form of Pendulum Scales
to the 5 mentioned archetypes.
Additionally, the Yang Zing Zefra strategy of late 2015 and early 2016
included a minimal Odd-Eyes Pendulum Dragon engine to take advantage of
the Field Spell, Sky Iris. This Spell allows to destroy 1 of your own cards to
search 1 Odd-Eyes card from the deck. This was doubly convenient with
Yang Zing Zefra, since it was often used to destroy a Yang Zing monster to
avoid the card loss and to summon, Jiaotu, Darkness of the Yang Zing, the
main combo starter of the whole strategy. Then, Odd-Eyes Pendulum Dragon
was used to Pendulum Summon multiple copies of Zefraniu, Secret of the
Yang Zing as part of the combo or to search any other convenient Pendulum
Monster during the End Phase, for example, Archfiend Eccentrick.
Something interesting about this deck is that it used to consistently pull
5-card combos. This was possible due to its shared effects, high searching
capabilities, and versatile cards such as Terraforming. Also, because its basic
3-card combo did not require specific cards, but rather, any 2 Yang Zing
cards and an easily searchable, Jiaotu, Darkness of the Yang Zing.
Now, we are ready to work with our data. This time, we need 2 csv files.
One for the nodes or cards as shown in Table 6.1, and one for the edges or
interactions between cards as shown in Table 6.2. Notice that the table of
nodes includes 1 column for the nodes or cards, and 2 extra columns with the
quantity of cards and the type of card. The table of edges can also have extra
information, but here I show you only the minimal. This is, 1 column for the
initial node or searcher card, and another for the final node or search target.
Therefore, this table represents an interaction or connection between
searchers and targets. In this example, we are going to explore 2 kind of
interaction between the card, which are, cards that add certain cards from the
deck to the hand, and cards that summon Monsters from the deck to the field.
In this example, Chicken Game and Upstart Goblin are not in the table of
edges despite they allow the player to draw 1 card. This is because we cannot
know in advance the name of the card we are going to get. On the other hand,
Sky Iris shows a connection with the Yang Zing Monster despite its text does
not specifically mentions any Yang Zing at all. This is because this card can
trigger their effects to Special Summon Yang Zing monsters from the deck.
Anyway, there are no rules to define the edges. We simply investigate our
strategy in the way we interpret it, so feel free to modify the tables as you
please.

Table 6.1. Table of nodes. Type at least the name of the cards in a csv file.
Table 6.2. Table of edges. Type as 2 columns in a csv file.

Once the data is ready, we can load it with the well-known read.csv()
function. Keep in mind that we now require to load 2 files and save 2
dataframes.

To complete the next steps we need to execute the


install.packages(“igraph”) function in the R console. Then, we need to load
the igraph library as library(igraph). Remember that the installation of a
package is a onetime process, but you need to load a library every time you
start a new R session if you want to use it. Once igraph is loaded, you will
have access to many functions specifically designed to work with network
diagrams. The first one we need is, graph_from_data_frame(d, vertices,
directed), where d is the dataframe with the edges, vertices is the dataframe
with the nodes, and directed should be TRUE to visualize the direction of the
interactions, in other words, who searches whom. Therefore, use the
graph_from_data_frame() function with your dataframes and save the result
in an object. I chose YZZ.diagram. This object now contains all the data of
your csv files in a network structure that facilitates R to do some operations
with it. In our case, we are interested to visualize the network diagram, so we
use the plot() function with the network structure. Keep in mind that the plot
of a network structure is often plotted randomly, so you may get a different
plot every time you try to plot it.
Anyway, the plot does not look anything good at all. It needs some
customization as every network diagram does. To do this, just play with the
parameters of the plot() function that I indicate below. Most of them are self-
explanatory. Notice that I also modified the original csv files to include
shorter names for the nodes in order to improve the readability of the network
diagram.
You can also add the layout parameter inside the plot() function to
arrange the diagram in different ways. Here are some examples.
Figure 6.3. Network diagram layouts. a) layout=layout.fruchterman.reingold, b)
layout=layout.kamada.kawai, c) layout=layout.grid, d) layout=layout.circle.

Something I really enjoyed about this deck during my time as a Yang


Zing Zefra player was the versatility of its cards. I mean, it was already clear
that most of the Yang Zing monsters were capable to summon any other of
their brothers. It was also clear that Oracle of Zefra was there to search for
any of the 3 Zefra monsters included. Two of which were also Yang Zing
monsters, which was useful to either complete the Pendulum Scales or to
discard as a cost for the effect of Jiaotu, Darkness of the Yang Zing. Sky Iris
was versatile too to search for Odd – Eyes Pendulum Dragon and to summon
Jiaotu. But what I found most amazing was how Terraforming worked as a
gate to search for Sky Iris or Oracle of Zefra to gain access to the Odd-Eyes,
Zefra, and Yang Zing engines. Terraforming was also capable to find
Archfiend Eccentrick through Sky Iris and Odd – Eyes Pendulum Dragon. It
was even capable to indirectly find Yang Zing Path and Yang Zing Creation.
However, this was a little more complicated, since it required to search an
Oracle of Zefra to later search and Pendulum Summon a Zefraniu, Secret of
the Yang Zing. Alternatively, Terraforming could search Chicken Game to
draw an extra card at the cost of 1000 Life Points. Basically, Terraforming
was capable to search any card of the deck except Upstart Goblin, as you can
see in the diagram.
Anyway, let’s take our network diagram one step beyond. This time,
let’s make use of some of the additional data included in the nodes csv. To do
this, first take a look to the commands below. V(YZZ.diagram) refers to the
vertices of the YZZ.diagram network structure. Then, the code in square
brackets serves as an index to identify a particular set of nodes. In the first
case, we want to identify those nodes where the Type column in our nodes
csv is set to Monster. Finally, the $color part is an attribute that controls the
color of the nodes. Therefore, the line V(YZZ.diagram)
[V(YZZ.diagram)$Type == "Monster"]$color <– "tan1" assigns a tan color
to those nodes identified as Monster. Similarly, you can assign another color
to the nodes identified as Spell or Trap.

Now just type the color assignments previous to your favorite plot to
obtain a network diagram where you can easily identify the type of cards
included in the deck. You can even get more specific according to your
needs. Maybe you want to segregate Normal Monsters from Effect Monsters,
or paint the nodes of Pendulum Monsters according to their Scale value.
Maybe you want to add Extra Deck Monsters. It is up to you.
Here is my final piece of code. As you can see, I created a new object
named yzz.node.size to make the size of the nodes 5 times greater than the
quantity of each respective card. This helps to identify if our cards with more
connections are also the most played.
Awesome! Our simple network diagram is ready. There are still so many
things that we can learn about plots and the igraph package, but I am afraid
that you need a different book for that purpose. Right now, the main
takeaway of this kind of plots is to quickly visualize how the cards in our
deck interact with each other. If we have a card that is central to the different
engines in our deck, then maybe we would like to maximize it to have access
to our most convenient cards. If there is a card on the outskirt of the diagram
that is connected just to a few nodes or to none at all, then we must have a
really good reason to keep it in the deck. Otherwise it could be convenient to
think of a replacement. Finally, get ready because the next chapter will teach
you how to use the igraph package to input the combos of your deck in an
easier way to evaluate your probabilities. But that is not all, because you will
now consider some possible disruptions to your strategy. Until then, have
fun!
7. Link your skills to the top of the
duel
There are 3 reasons to read this chapter.
1. You will learn an extremely efficient way to input 2-card combos to
your programs.
2. You will learn to automatically test your strategy against the possible
disruptions of the opponent.
3. You will complete your quest.
T henextsummer of 2017 came to an end as well as the Pendulum era, but the
update to the game had some bold changes ready. First of all, the
Pendulum Scale zones merged with the Spell and Trap card zone.
Therefore, it was not possible to have 2 active scales along with 5 set traps
anymore. Then, 2 new shared Monster Zones appeared in the middle of both
of players’ field. These zones were specifically dedicated to monsters
summoned from the Extra Deck and each player was capable to control any
of the zones, but just one at a time. This immediately affected most combos
involving Fusion, Synchro, Xyz, and Pendulum Monsters because it became
much more difficult to summon multiple monsters from the Extra Deck.
However, this new game update offered its own way to deal with this
hardship. These were the Link Monsters, new blue-colored cards that found
their place in the Extra Deck. Their main difference with respect to Fusion,
Synchro and Xyz cards was that they did not have a Level nor a Rank, but a
Link Rate instead. To Link Summon a Link Monster, a player needed to send
monsters materials from the field to the Graveyard in an equal amount to the
Link Rate of the monster to summon. Alternatively, a player could use a Link
Monster as a material to count as a single monster or as a quantity of
monsters equal to its Link Rate. Of course any of these two conditions
needed to fulfill any other specific requirement stated in the Link Monster.
Furthermore, Link Monsters had up to 8 Link arrows distributed around the
monster image pointing either up, down, left, right, or to any of the 4 corners.
The number of these Link arrows was equal to the Link Rate and their
purpose was to point and unlock Monster Zones so they could be used to
summon more Extra Deck Monsters. Therefore, Link Monsters became
central to most strategies.
Another change introduced to the game with the new mechanics was the
possibility to hold up to 12 monsters on the field at the same time, 6 for each
player. There was even a way for a single player to control both Extra
Monster Zones to potentially summon up to 7 monsters, but I will not
describe the details here. Anyway, the new Link era was clearly destined to
increase the power ceiling of the game to new heights. This was evident due
to the introduction of more Monster Zones and to the simple summon
condition of Link Monsters. However, this needed some time to happen. The
scarcity of powerful Link Monsters at the beginning complicated the
competitiveness of Link archetypes, whereas the lack of Link Monster with
convenient Link arrows complicated the adaptation of previous Extra Deck
strategies. This gave a meaningful initial advantage to True Draco who was
not dependent of the Extra Deck, as well as Dinosaur to a lesser degree. But
few months later, the competitive game shifted in favor of the previously
available SPYRAL, who became a dominant force with the release of their
own Link Monster, SPYRAL Double Helix.
Then, the competitive game had a wild turn with the release of Extreme
Force, the first set of 2018. Notable cards in this set were the Mekk-Knight,
whose specialty was to break established boards taking advantage of the
placement of the cards on the field. Also, Underclock Taker as the first
generic Link 2 Monster, Isolde, Two Tales of the Noble Knights later used
with Gouki, and Saryuja Skull Dread, whose card advantageous effect
increased the consistency of combo decks such as World Chalice and many
more in the future to come. Still, no other single card in the set had the same
immediate impact than Heavymetalfoes Electrumite, a Link 2 Monster
especially designed to easily generate resources in Pendulum strategies. This
new monster worked together with Astrograph Sorcerer and Chronograph
Sorcerer, as well as few other Mythical Beast and Zefra cards to make
Pendulum the top contender of the season.
Few months later, the release of the set, Flames of Destruction changed
the game once again. The introduction of the Knightmare Link Monsters
offered generic Link support to most strategies, but no other archetype took
more advantage of them than Gouki. The Gouki excelled at generating hand
resources every time they moved from the Field to the Graveyard. This, in
combination with the original effect of Firewall Dragon, made possible to
consistently conduct an Extra Link to occupy both Extra Monster Zones. This
way, the Gouki Knightmare strategy managed to establish oppressive and
disruptive fields with protection integrated in a single turn.
Some decks in the past managed to consistently establish disruptive
fields in the first turn, however, this became the new normal during the Link
era for any strategy with the intention to compete. This was also the case for
other competitive archetypes such as Trickstar and their insane Trickstar
Reincarnation plus Droll & Lock Bird combo. Or, Altergeist and their
Altergeist Protocol followed by Altergeist Multifaker and Altergeist
Silquitous.
Then came the Sky Striker, Sky Striker Trickstar, and other hybrid
decks. These were more control oriented strategies that could easily switch
towards an OTK strategy. They were also capable to produce disruptive first
turn fields as was the common of the time. Particularly, this strategy had the
extremely versatile Sky Striker Mobilize - Engage! A card that could add any
Sky Striker card from the deck to the hand and often draw an extra card in the
process. And of course, there was a Sky Striker card for any occasion. They
were capable to destroy monsters, destroy Spell or Traps, negate monster
effects, Special Summon monsters, and more. Surprisingly, none of them had
the already standard limitation of modern archetypes to activate each of their
cards no more than once per turn. This made Sky Striker a top strategy for
more than a whole year. It was simply too good on its own, to good as an
engine in other decks, and too good to be stopped by the banlist.
Many months later, the Soul Fusion set released at the end of 2018
introduced amazing support for Thunder Dragon, a monster available since
2002. This new Thunder Dragon archetype focused on high level monsters
with effects activated in the hand and also when banished or sent from the
field to the Graveyard. Their Thunder Dragon Colossus was a powerful and
oppressive Fusion Monster that would not allow the opponent to add cards
from the deck to the hand. This caused difficulties for most strategies to
compete.
Other notable cards released in Soul Fusion were a second wave of
Danger! monsters as well as the initial Orcust monsters. The Danger! served
mainly as an engine to accelerate most other strategies, whereas the Orcust
had yet to wait some time to become one of the most powerful strategies of
the Link era. Meanwhile, the Guardragon Link monsters released in Savage
Strike at the beginning of 2019 offered a new engine adaptable to many
strategies in order to produce even more powerful first-turn fields. Soon after,
the Structure Deck Soulburner introduced the support that the Salamangreat
archetype needed to reach the top tables. And as expected, this strategy was
also capable to create powerful first-turn fields and still switch towards an
OTK when needed.
The Salamangreat, Orcust, Sky Striker, and Thunder Dragon continued
to lead the competitive game for the rest of 2019. Still, there were many other
competitive strategies capable to produce equally powerful boards. All this
was possible thanks to generic engines such as the Danger! and Guardragon,
the availability of counter trap cards in most archetypes, and the abundance
of disruptive monsters such as Borreload Savage Dragon, Dingirsu, the
Orcust of the Evening Star, Apollousa, Bow of the Goddess, and many more.
It was clear that the way to go in Yu-gi-oh! was to follow a combo to
produce “interruptions” to completely block the advance of the opponent.
This turned the game in favor of the first-turn player for a long time until the
second-turn player obtained enough cards to either break an established
board, or to prevent the creation of one. This second group contains what
players call handtraps. And although there is no strict definition of what a
handtrap is, duelists usually call handtrap any card with an effect activated in
the hand with the purpose to disrupt or negate an action of the opponent.
Usually, these are monsters used during the turn of the opponent, but some
can be activated at different times. Some classic examples include Kuriboh,
D.D. Crow, and Gorz the Emissary of Darkness, but probably most duelists
became familiar with the handtrap term when Effect Veiler and Maxx “C”
became trendy cards. Other important examples of handtrap monsters used
through the years include Droll & Lock Bird, Ghost Ogre & Snow Rabbit,
Ash Blossom & Joyous Spring, Fantastical Dragon Phantazmay, and Nibiru,
the Primal Being. Each of them with their own set of benefits and drawbacks.
There are also Trap handtraps, such as Infinite Impermanence, Red Reboot,
and Zefra War. Eventually, these cards became essential in most strategies
and Side Decks to have a chance to fight back. As a consequence, duelists
had no other choice but to build their decks considering the possibility of
being handtrapped. Either, by playing through the handtraps or by playing
cards such as Called by the Grave to protect against the handtraps.
With this in mind, your final mission in this adventure will be to test
your strategy against possible handtrap scenarios. This way you will have a
simulation that considers the obstacles expected by your opponent.

7.1 A complete and final code to test your strategy in R


Alright! We are close to complete our quest. To do it, we are going to
work with the Crusadia Guardragon strategy developed at the beginning of
2019, but first, let me tell you some details about the deck.
The Crusadia are a Link based archetype originally released in
Cybernetic Horizon on July 2018. Its purpose is to win the duel with a single
attack. To do this, Crusadia monsters share an effect that allow them to be
special summoned to a zone a Link Monster points to. This way, they can
easily summon Crusadia Equimax, a Link 3 monster who gains the original
ATK of the monsters it points to. Often, Crusadia Equimax is paired with
Crusadia Maximus, who allows a Crusadia Link Monster to double the Battle
Damage inflicted to a monster. Another common choice is the Field Spell
Crusadia Revival, which gives additional ATK to Crusadia Link Monsters
and allows one of them to attack all the monsters the opponent controls.
Finally, Crusadia Magius, Crusadia Regulex, and Crusadia Draco help with
the generation of resources that the archetype needs.
Often, Crusadia duelists build their deck around a unique Battle Phase,
therefore, they prefer to be the second turn player. With this in mind, they
usually use half of the deck to include the Crusadia engine, whereas the other
half is a mixture of cards to break an established board and to conduct a safe
and successful attack. Some popular choices include Kaiju Monsters to get
rid of disruptive monsters on the field, protective cards such as Called by the
Grave and Red Reboot, as well as other cards with miscellaneous effects such
as Black Garden. This mix often results in a powerful and consistent strategy,
but also a fragile one due its going-second nature. It is either win fast, or lose
fast.
On the other hand, the Crusadia Guardragon strategy developed at the
beginning of 2019 takes advantage of the Guardragon Link Monsters to allow
Crusadia players to start the duel. This strategy just needs a Crusadia monster
to Link summon Crusadia Magius and another card to Special Summon a
monster and trigger Crusadia Magius effect. This allows to add Crusadia
Draco from the deck to the hand and to summon Crusadia Spatha in the
process. Then comes what I consider one of the most beautiful interactions
ever seen in Yu-gi-oh! Crusadia Draco is used to summon Guardragon Elpy
under Crusadia Spatha. This triggers the effect of Crusadia Spatha to move
Guardragon Elpy to another Monster Zone in order to have both of them
pointing their Link Arrows to the same Zone. This allows Guardragon Elpy
to access a whole Dragon engine to generate more resources and often
conclude with an extremely disruptive field assembled by Gameciel, the Sea
Turtle Kaiju plus Kyoutou Waterfront, Crystal Wing Synchro Dragon,
Hieratic Seal of the Heavenly Spheres and more. This results in a strategy
with a highly consistent 2-card combo going first, but also capable to conduct
an OTK going second.
With all this in mind, let’s proceed to the evaluation of the Crusadia
Guardragon deck shown in Table 7.1. I warn you, there is a lot of coding
ahead, but not all of it is mandatory to complete the evaluation, so feel free to
implement what you find most convenient.
This time, we are also going to consider the possible disruptions of the
opponent. To do this, we need to introduce a deck for the opponent in order
to simulate the cards they could possibly draw. In this case, we do not need to
be too specific since we only care about the handtraps. Therefore, let’s
assume that most opponents play a 40-card deck with 6 handtraps in total. In
this example, these are 3 Ash Blossom & Joyous Spring and 3 Ghost Ogre &
Snow Rabbit as shown in Table 7.2. Both cards can only be used once per
turn, so the opponent can have a maximum of 2 disruptions per hand.
Anyway, feel free to select the handtraps of your preference according to the
strategies you face more often.

Table 7.1. Example of a Crusadia Guardragon Main Deck.

Table 7.2. Simplified decklist played by the opponent.

Remember that you can include both decklists in the same csv file as
described in Chapter 2, but there is no problem if you prefer to use separate
csv files. Then, we would normally move to code in R, but this time we are
going to prepare another csv file to facilitate the input of possible combos and
plays. This is going to require new instructions, but less code. Also, this
method is particularly good for 2-card combos, which is a standard of modern
Yu-gi-oh! decks. Therefore, start by preparing a spreadsheet with 1 of each
card in your deck and arrange them as shown in the adjacency matrix of
Figure 7.1. Each unique card should be from top to bottom on the left as well
as from left to right on the top in exactly the same order. Now, take a look to
the card in the first row, which is Crusadia Maximus in this example. Then,
go column by column in the same row and type 1 in each crossover where 2
cards interact together to produce a combo. Here, Crusadia Maximus does
combine with any other Crusadia monster, including a copy of himself. He
also interacts with Ranryu, Black Dragon Collapserpent, Monster Reborn,
World Legacy Succession, and Quick Launch. Therefore, Crusadia Maximus
can start our 2-card combo with a total of 10 unique cards. Of course, some
of these cards include multiple copies of them in the deck, but we do not need
to worry about that yet. Then, repeat the same process with the following
rows until you complete the whole spreadsheet. Another example is Crusadia
Draco, who shows the same interactions of Crusadia Maximus, except one
with itself and Black Dragon Collapserpent. On the other hand, Crusadia
Draco interacts with World Legacy Guardragon.
Feel free to add some format to the cells if that helps you to fill the data.
At the end, the summed values of the interactions of each card in a row
should be equal to the summed values of interactions for the same card in a
column. Keep in mind, that filling a spreadsheet like this requires your
expertise about the deck you attempt to evaluate. Here, I show you a Crusadia
Guardragon version that can start a play even without the need of a Crusadia
monster. An example of this is observed with the interaction of Ranryu and
Effect Veiler in Figure 7.1. Of course this requires few other cards in the
Main and Extra Decks, for example, as Ib the World Chalice Justiciar. I also
assume that Quick Launch always has a Rokket target available in the deck
just to facilitate the programming. This is often the case anyway, so it should
not compromise the final evaluation.
Figure 7.1. Adjacency matrix for 2-card combos.

Anyway, the adjacency matrix you need to save as a csv file needs to
look as the one shown in Figure 7.2 in order to introduce it to R. So, make
sure to delete the summed values and the list of cards on the left. There is no
need to flip the text on top if you do not want either.
Figure7.2. Adjacency matrix for 2-card combos as requested by R.

Okay! Let’s add some code now that the data is ready. First, let’s load
the libraries needed. You are already familiar with vecsets and igraph, but
this time you will also need stringr. Remember that you need to type
install.packages(“stringr”) in the console to install a new package. After that,
you just need to load its library when you need it.

Then, load your deck, the deck of the opponent, and the adjacency matrix
with the 2-card combos. Here, I wrote both decks in the same csv file as
described in section 2.3 to load as them as a single dataframe named Deck,
but you can load them as separate objects if you prefer.

Now we are ready to shuffle the cards, however, the adjacency matrix
with the 2-card combos needs some adjustments. This just requires to
introduce 2 lines of code to modify the adjacency matrix as shown in Figure
7.3. The first one passes the names of the columns as names of the rows,
whereas the second replaces the NA values with 0.
Figure 7.3. Original and modified adjacency matrix.

Now let’s take benefit of some of the functions in the igraph library. The
graph_from_adjacency_matrix(as.matrix(dataframe)) function builds a
network structure from the adjacency matrix provided in the object named
Combos. With this, you can use the plot() function and the customization
parameters described in Chapter 6 to quickly visualize a network diagram of
2-card combos. Here, the idea is to use our deck-building skills to create a
network where most cards are connected with each other.
Alternatively, you can move straight to the creation of a list of combos.
Just grab your network structure obtained from the adjacency matrix, get and
edgelist with the get.edgelist() function and transform it into a dataframe with
the as.data.frame() function. It is straightforward. Once this is ready, you will
have a dataframe with 2 columns and 72 rows. Each column is a card and
each row is 2-card combo. Here, I show you only the first 15 rows to point
that the dataframe includes permutations rather than combinations. As an
example, row 2 and row 11 include Crusadia Maximus and Crusadia Draco
but in different order. That is something we do not need to worry.
However, you probably observe that the names of the cards are now
modified. There is a period where there used to be a space. This is because
the edgelist is obtained from the names of the columns and rows in the
adjacency matrix, and R does not allow empty spaces as names. Fortunately,
the str_replace_all(string) function in the stringr library can easily replace a
string of characters for another one. Here, we replace the period, which needs
to be typed as “\\.” to a space, typed as “ ”.
Up to this point, I have been saving all data in the object names as,
Combos, so the output of each function replaces any previous information
available. I often do this when I do not plan to use certain data in further
sections of the code, but feel free to choose different names for your objects
if you prefer to store your data. Anyway, all that is left now is to test our
strategy as we did before. So, let’s reuse the custom Find.combo() function
described in Chapter 5.

Then, take the dataframe with combos and turn it into a list. However,
you first need to swap rows with columns because our combos are structured
row by row, whereas dataframes work with columns. To do this, just use the
t(dataframe) function with the Combos variable and then turn it into a list as
shown below. This list now includes the 72 basic combos of our strategy.

We could put this list into a for loop to evaluate the probability of Play1,
however, let’s define additional plays to test them all together. For example,
Play2 shown below takes our 72 2-card combos and adds Called by the Grave
as a third card with the rbind() function. Now we have 72 combos with 3
cards each, where all of them include a Called by the Grave. Then, repeat the
same steps to define Play3, but this time with 2 copies of Called by the
Grave.

Now is the time to test all plays. To do this, we need to define a large-
enough number of Trials. Then, let’s declare an initial value of 0 for the hand
to simulate. Also, let’s define an initial value of 0 to count each of the plays
to test. Here, I use the variables P1.Success, P2.Success, and P3.Success to
keep track of the times when each play is successful. Notice that here I keep
track of every single hand and result simulated with the Hands[Trial.num],
P1.Success[Trial.num], P2.Success[Trial.num], and P3.Success[Trial.num]
rather than just count the final result. This is because I later plan to put all the
results together in a single table. Also, see that I use the ifelse(condition, code
if positive, code if negative) function a simplified version of the If – Else
statement used before. In this case, when any(Result)==TRUE, in other
words, when a combo is in a simulated hand, the P1.Success[Trial.num]
variables stores a 1, otherwise, it stores a 0. The same is repeated for Play2
and Play3.

At this point, the simulation of our strategy is ready. Each individual


hand is stored, as well as the outcome of each play. Now we need to simulate
the strategy of our opponent. This also requires some consideration from our
part to rank the risk that each hand of the opponent represents. In this case,
we know that the opponent has 3 Ash Blossom & Joyous Spring and 3 Ghost
Ogre & Snow Rabbit. Both cards can only be used once per turn, so the
opponent can have a maximum of 2 disruptions per turn. Therefore, we can
assume 3 possible scenarios, which are, 1) no handtraps at all, 2) 1 or more
copies of a single handtrap, and 3) one or more copies of both handtraps.
Here, let’s assume that both handtraps are equally dangerous to us. With this
in mind, let’s shuffle the deck of the opponent and assign values to each
scenario.

In this case, we assign a value of 2 when both handtraps are in


Opp.Hand, a 1 when only one of either handtrap is in Opp.Hand, and 0 when
none of them are in Opp.Hand. Make sure to write the code in the same order
to get the correct values. Repeat the process with a For loop a number of
times equal to the Trial parameter and save each simulated hand in the
Opp.Hands[Trial.num] variable. Also, save each result in the
Opp.handtraps[Trial.num] variable.
As you have noticed, I have not printed any result yet. This is because I
want to take the opportunity to put every result into a single table for the final
calculations. To do this, create a vector with the numbers from 1 to the value
of Trials. Then, use the cbind() function to append this vector with the hands
and results simulated. Finally, convert the structure into a dataframe.

This last table let us see our simulated hand, the simulated hand of the
opponent, the outcome of our plays, and the number of disruptions in the
hand of the opponent. But there is still one key value missing in our table,
and that is, the final outcome of each trial. For example, we succeed when
P1.Success = 1 and Opp.handtraps = 0. However, we fail when P1.Success =
1 and Opp.handtraps = 1 unless we have a Called by the Grave ready in
hand, in other words, when P2.Success = 1. Therefore, we find that we have
the advantage over our opponent when P1.Sucess + P2.Success + P3.Success
– Opp.handtraps is greater than 0. So, we just need to add the
Full.sim$Balance column with the operation described.
Notice that I also included the Full.sim$Final.Outcome column to easily
show the final outcome as 1 for success or 0 for miss. Finally, we just need to
sum all the values in our columns of interest and divide them by the number
of Trials to obtain the experimental probability. These values are PP1 =
0.8922, PP2 = 0.2786, PP3 = 0.0222, and a PFO = 0.5162.

Or if you prefer, you can visualize the probability of the final outcome as
a function of the number of trial.
Okay! After this long code, let’s reflect about the meaning of these
results. First of all, see how this more contemporary strategy based on
multiple combinations of 2-cards achieves an impressive probability of
0.8922 on its basic play. However, this value drops considerably to 0.5162
when we consider some possible disruptions used by the opponent. Of course
this value can change as we adapt the number of handtraps proposed
according to cards trending in the competitive game. Also, here we assume
the worst possible scenario in which the opponent draws the right handtrap to
stop our strategy and also knows the exact moment when to use it. This is
probably true in the top competitive tables of a tournament, however, it is
also true that you may as well have the right card among the rest of your hand
to still succeed with your play or with an alternative play. It could either be a
card such as Called by the Grave specifically included to anticipate a
disruption, a copy of your combo cards, or something else. This may depend
on luck but also on your skill as a player. So if you really know your cards
and your strategy, that outcome probability of 0.5162 could actually increase
in your favor. Finally, remember that you can adapt this code according to
your needs. There are many more aspects of a strategy that you may want to
investigate via simulations, for example, what would be the final outcome
probability if it wasn’t by Called by the Grave? Or, how would the
calculations change if you modify some cards in the deck? It is up to you.
You already have the skills to find it! Here is the full and long but worth code
developed in this section.
8. The end of a journey and the
beginning of another
Congratulations! You have completed this quest to the realm of
Probability and Programming to excel at Yu-Gi-Oh! Now you can proudly
say that you have a general overview of the evolution of competitive Yu-gi-
oh! over almost 2 decades of duels. But do not get overconfident because this
is not the end of the journey. Instead, you are at the line that separates a
former duelist guided by experience, trial and error, and desire to grow, from
a future duelist armed with knowledge, an analytical mind, and the skills to
grow. Combine all these components and you will surely reach the top tables
more often even with some unexpected strategies. Remember that now you
understand the basic rules of probability to calculate the likelihood to get any
card from your deck. You also know the multivariate hypergeometric
distribution to calculate the probability to draw not one single card, but a
combination of cards too. And if for some reason the problem you want to
solve is too difficult, you can also trust the law of the large numbers and use
your newly acquired programming skills to simulate an experiment and
evaluate the experimental probability. Here, we implemented some lines of
code to evaluate the combo and play probability. We even modified that code
to consider a modern aspect of Yu-gi-oh! like handtraps. Similarly, you can
get as creative with R as you do when you build a deck. Add some more
lines, remove others, create your own functions, install packages, load
libraries, whatever you want or need to investigate a problem or to adapt to a
change in the game mechanics. Maybe you want to know if the benefit of Pot
of Desires is greater than its cost in your particular strategy. Or maybe you
want to know if a 40-card deck is always the best option. Or find a way to
“brick” less often. It is up to you. You have the skills, and you have the
knowledge. All I am left to say now is, thank you for joining me in this trip,
good luck and have fun!
Bonus chapter. The big battle of the
monsters
The Yu-Gi-Oh! Trading Card Game – Card Database available at
https://www.db.yugioh-card.com/yugiohdb/ is an official database offered by
Konami to let you to dive into all of the Yu-Gi-Oh! TCG cards. There, you
can easily segregate cards by name, text, type, Attribute, Level, Rank,
Pendulum Scales, Link Arrows and many other parameters to discover the
optimum cards for your strategy. The site also allows you to find decks,
create lists of cards, consult the current forbidden and limited list, and do
some other things to improve your competitive skills. However, it is also
natural to use such database for other recreational purposes. Personally, I can
tell you that I enjoy reviewing and classifying data to find answers to some
extravagant questions I can think about Yu-Gi-Oh! And, you know, I bet I am
not the only whose mind wanders thinking, who would win a hypothetical
war of Yu-Gi-Oh! Monsters? Dark or Light Attributes? Dragon or Spellcaster
types? Synchro or Xyz? Therefore, I want to take the opportunity to share
some of my fanciful questions with you. But not only that, I want to show
you what I think are the answers to those questions according to the data I
have observed. Here, it is important to specify that all the data shown in this
Bonus Chapter is collected from the Yu-Gi-Oh! Trading Card Game – Card
Database as of May 30th, 2021, so this includes a total of 10637 unique
cards. Also, all the questions here discussed are fictional, the answers are my
insights on data, and this whole chapter is for no other purpose than to have a
well-deserved fun time after your successful completion of this book. Have
fun!
1. Imagine a massive battle with all of the Yu-Gi-Oh! monsters on the
same battlefield. For some reason, the monsters decided to group as 6 big
armies according to their Attribute (Dark, Light, Water, Fire, Earth, and
Wind). The question is, which attribute would result victorious if the winner
is decided by the sum of ATK of all the monsters in an army? Also, which
army would be the first one to fall?
Take a minute to think your answer and go to the next page once you are
ready!
I bet the winner of this match is of not a surprise for most duelists.
Somehow, the designers of the cards or anyone in charge seem to have a
preference for Dark Attribute monsters. Or maybe this is a tradition started by
the legendary Yugi Mutou (or Pharaoh Atem himself) and his Dark Magician
since the release of the first anime show. Who knows. Anyway, with a total
of 2956680 ATK, the Dark monsters are the evident winners of this battle!
On the other hand, the Fire monsters are the first to fall with just 937000
ATK. Honestly, my lack of faith was on the Wind Attribute before this
analysis.

Figure 9.1. The big battle of the Yu-Gi-Oh! Attributes.


2. Maybe the Attributes are such a broad classification that the monsters
prefer to group as 23 armies according to their monster Type instead. Once
again, which Type would result victorious if the winner is decided by the sum
of ATK of all the monsters in an army? Also, which army would be the first
one to fall?
To answer this question, consider that most of the Monster Types have
been in the game since the release of Legend of Blue Eyes White Dragon on
2002. On the other hand, Psychic debuted in The Duelist Genesis on 2008,
Wyrm were introduced in Duelist Alliance on 2014, and Cyberse joined the
battle in Code of the Duelist on 2017. This may give you a hint to find the
first one to fall… or maybe not?
I knew Warriors would be top contenders, but honestly, I did not expect
them to defeat the mighty Dragons! They have a total of 1494760 and
1220700 ATK points respectively, which creates a significant difference. The
last position, or the first to fall in this battle are, the Sea Serpent Type
monsters with a total of 125350 ATK. This is even behind of the younger
Types in terms of total ATK points. However, I am more surprised to see
Cyberse doing relatively well in this war considering that they are the
youngest of all the monster Types in the game.

Figure 9.2. The big battle of the Yu-Gi-Oh! monster-Types.


3. Now, let’s consider the case of a big battle where the monsters are
divided according to their summon mechanic. Therefore, they divide into the
Ritual, Fusion, Synchro, Xyz, and Link armies. Which army has the highest
sum of ATK? Which one has the lowest?
Some things to consider here are that Fusion and Ritual Monsters have
been in the game since year 2002, whereas Synchro, Xyz, and Link Monsters
joined the battle on 2008, 2011, and 2017 respectively. So it is natural to
expect an unbalance here. Also, consider how often do you see a monster of
each particular Summon mechanic on the field.
Figure 9.3 clearly shows that Ritual Monsters have the lowest sum of
ATK. They have a total of 239350 ATK points, which is 3 to 4 times less
than the top contenders due to a lack of Ritual Monsters compared to the
other summon mechanics. This is most likely a consequence of the
complexity of the Ritual Summon mechanic. After all, why to use Ritual
Monsters when Extra Deck Monsters are easier to summon? And, why to
release new Ritual Monsters when duelists prefer to use Extra Deck
Monsters? On the other end, Xyz Monsters barely take the lead over Fusion
and Synchro with a total of 876460 ATK points.

Figure 9.3. The big battle of the Yu-Gi-Oh! Summon mechanics.


4. This time, the monsters organize according to their Level. This leaves
Xyz and Link Monsters outside the battle, but Fusion, Synchro, Xyz and
Ritual are still in. Which Level will be victorious and which one will be the
first to fall?
Keep in mind that the ATK of a monster normally increase as its Level
increases. This gives an advantage to high Level monsters. However, low
Level monsters are much more common in the game. They are easy to
summon and most of the times they are the materials or tributes that allow the
summon of high Level monsters.
And the clear winners are the Level 4 monsters with a total of 2700870
ATK points! That is double the ATK of the closest contender. Somehow,
Level 4 monsters seem to be the key cards in most strategies, whereas Level
8 monsters are the triumphant cards. On the other extreme are a special case
of just 2 Level 0 Synchro Monsters with 0 ATK points each. These are
followed by the also scarce Level 11 monsters. Something interesting is that
the number of monsters available for each Level is highly uneven. Maybe
you can use the Yu-Gi-Oh! Trading Card Game – Card Database to find the
total number of monsters by Level.

Figure 9.4. The big battle of the Yu-Gi-Oh! monster Levels.


5. Finally, let’s organize the Monsters by archetype to try to solve the
same questions. Which archetypes have the highest sum of ATK and which
one has the lowest?
This is more difficult to answer since there is no strict definition of what
an archetype is. This complicates the classification of monsters to analyze
this question. Also, not every monster belongs to an archetype, whereas some
of them belong to more than 1 at the same time. To complicate things further,
there are some cases of discrepancy between the OCG and TCG names of
monsters. Anyway, here I show the top 20 archetypes by total ATK points
using the names available on 475 Archetypes listed in
https://www.yugiohcardguide.com and https://yugipedia.com.
As you can see, the winners here would be the Number archetype with a
total of 273810 ATK points. This archetype already exceeds 100 members.
However, some may prefer not to consider Number as an archetype due to its
lack of Main Deck monsters or specific Spell and Trap cards. Cyber, and
Magician archetypes would also cause a polemic, since these are common
words used to name multiple monsters or to define other archetypes such as
Cyber Dragon or Cyberdark. Anyway, Figure 9,5 shows the top 20
archetypes by sum of ATK.

Figure 9.5. The big battle of the Yu-Gi-Oh! monster archetypes.

We could surely imagine more fictional scenarios, think other questions,


explore new data, and find some answers. I am sure we could get even more
creative as the game evolves and introduces new cards and new mechanics.
For the moment, I invite you to use the Yu-Gi-Oh! Trading Card Game –
Card Database available at https://www.db.yugioh-card.com/yugiohdb/ to
explore as you need.
Appendix
Installing R and RStudio
This book teaches you the basics of the R programming language to
simulate the shuffling and drawing of cards from a deck in order to easily
evaluate the probability of success of some complicated events. To do this,
you need to install R to do the coding, and also RStudio to make your
programming life a more enjoyable one.
To download R, just go to https://www.r-project.org/ and simply follow
the installation steps for your region and system. Then, visit
https://www.rstudio.com/products/rstudio/download/ and follow the
instructions to download the free version of RStudio Desktop for your
operating system. The installation steps for both programs are pretty straight
forward. The default settings are more than enough for us.
Although you need both, R and RStudio, you are only going to use
RStudio as your working environment.

Getting used to RStudio


Figure A.1 shows the main panels within RStudio as they appear when
you open it. Each panel has its own purpose and you will get more skilled
with the use of each one of them as you progress with the exercises in this
book. In short, you will use them for the following tasks.
1. Console
This will be your most used panel. You can use the console to input any
function and to quickly display its output. Just type a function and press
ENTER. Press Ctrl + L or click the broom icon to clear all the text in the
console if it becomes too cluttered.
2. Files and other tabs
These tabs allow you to visualize data and get more information.
Particularly, you may want to use the Plots tab to see your visualizations, and
the Help tab to obtain documentation and examples of the R functions and
packages.
3. Environment and other tabs
Environment is useful to keep track of your coded objects such as
variables, vectors, dataframes, and other. You can also click a specific object
to view its content in a new window. The History tab keeps track of the code
introduced.
4. Source
You can write an R script when the code gets too long or complicated to
introduce in the console. You can even write it and save it as file with a .r
extension (Make sure to type the .r extension when you save your script).
This is extremely convenient to reuse the same code with other sets of data.
Click the Source button to execute all the code written in the panel, or click
the Run button to execute selected code. Use the print() function on a an
object to display its content in the console. Other than that, use the File tab at
the top-left corner to access options such as the common New File, Open
File, or Save As.

Figure A.1. Typical RStudio screen.


Customize RStudio
Click the Tools tab on top of RStudio to discover and click the Global
Options. Then, click on Appearance and customize as you like. Enjoy!

Figure A.2. Global Options panel to customize the appearance of RStudio.


Input your first command in the console
Click anywhere on the empty space of the Console and type a simple
operation such as 1 + 1 and press ENTER. You will immediately get 2 as the
answer of 1 + 1. The [1] is there to point the first element of the answer. This
operation results in just one element, however, more complicated operations
and data structures may include more elements. Finally, notice that RStudio
allows you to type 1 + 1, or 1+1, or 1+ 1 and still get the same result.

Figure A.3. Simple command in the Console.

Write your first script


Click on the File tab, highlight New File, and chose R Script. Click
anywhere on the empty space of the Source panel and type some simple
operations. Make sure to save your file with a .r extension (make sure to type
the extension). Then, click on the Source button to execute all the code.
However, although all commands are executed, only those results inside the
print() function are displayed in the Console. Keep in mind that commands
are executed in series from top to bottom.
Figure A.4. Example of a simple R script.

Data types
R supports many different types of data which you can use according to
your needs. The most important in this book are Numeric, Strings, and
Logicals.
Numeric
These are basically numbers. They are subdivided into integers and
doubles for decimal numbers, but you do not really need to worry about that.
Just use your numeric data as you would use them in any calculator. Make
sure to follow the rules of algebra. Use parentheses when needed.
Strings
These are used when text is involved. These are easily recognized
because they have quotation marks around the text.

Keep in mind that there is a difference between a number, and a string


with a number. They are different types of data and you will get an error
message if you try to conduct an invalid operation.

Logicals
These are either TRUE or FALSE. You can use them with the & (and)
and | (or) symbols to identify when all events are true, or when at least one of
the events is true, respectively.
You can also compare other types of variable and obtain a logical output
according to the result. Often, you will need to find whenever two variables
are equal with the == operator.

Data structures
Sometimes, you will need to perform operations or apply functions to
multiple values. This is when more advanced data structures become useful.
The next, are the following data structures that you will use in this book.
Vectors
These are an arrangement of values. A vector can have any of the data
types mentioned, however, all the values must be of the same type.
Dataframes
A dataframe is assembled by vectors. It is extremely useful to work with
data. Here, each vector of the dataframe can be of different type.

You can also build a dataframe from already available vectors.

You can then show individual vectors of a dataframe by typing the name
of the dataframe, followed by the $ sign, and then the name of the vector or
column.

Lists
Lists are a larger data structure that can contain multiple data structures
inside. Detailed examples are explained in Chapter 5.

Load, shuffle, and draw some cards


The most convenient way to load your cards is from a csv (comma
separated values) file as shown in Figure A.5. This way you do not need to
write the whole deck for every script you make. Just type all of your cards as
a single column in your favorite spreadsheet software such as Microsoft
Excel, Google Spreadsheets, WPS Office Spreadsheet, or other. Use the first
row to type an identifier label.
Then, save your decklist as a csv file to use it in R. To do this, you first
need to specify R where to find your csv file by setting a Working Directory.
Just click the Session tab on top of RStudio, highlight Set Working Directory
and click on Choose Directory to open the folder with your csv file, as shown
in Figure A.6.

Figure A.5. Example of a decklist in a spreadsheet software. Just 21 cards shown here.
Figure A.6. Setting a working directory.

Setting a working directory makes easier to load the files you wish into
R. In this book, you will be loading and saving csv files with the read.csv()
function and the name of your file.

This saves the decklist into a dataframe. Now you can watch the content
of the decklists with the $ notation. Just type the name of the dataframe,
followed by the $ sign, and then the name of the identifier label.
If you want, you can also save multiple decklists in different columns of
the same csv file. Finally, use the sample(vector, number) function to indicate
the number of random cards to draw from a vector of cards.

The If – Else statement


The If – Else statement is a simple way to tell R what to do based on the
evaluation of certain condition.
This reads as, “if the condition is true, then execute code 1, else, execute
code 2”. You can also use the simplified ifelse() function, which is often used
to evaluate and assign values to vectors. Here, If the condition is evaluated as
TRUE, the ifelse() function results in output 1, otherwise, it results in output
2.

The For loop


The For loop follows the structure for(variable in vector){code}. It is
used to repeat a piece of code a certain number of times. You need to type it
as shown below.

Custom functions
There is a great variety of R functions available to you. They will
definitely make your programming life easier. However, it is impossible to
have a function for every single task a programmer needs. Fortunately, R
allows us to program our own functions to use them later without the need to
type long codes over and over again. Just follow the next structure to create
your own function.
Simple plots
R has wonderful packages to produce amazing visualizations. One
example is ggplot2. However, the use of ggplot2 requires some training that
is beyond the scope of this book. Fortunately, R is already loaded with basic
plotting capabilities that are more than enough for our needs. Here is the most
common example you will use in this book.

Install new packages and load libraries


R is an open source programming language. This allows programmers to
develop and share new R content, such as, new functions, documentations,
and more. This expands the original capabilities of R and facilitates your
programming life. Here, you will need to install few extra packages to
complete the exercises of this book. To do this, just use the install.packages()
function and type the name of the package you want.

Figure A.7. How to install a package.

You need to do the process to install a package only once, but you need
to load its respective library every time you open a new R session if you plan
to use it.
Acknowledgments
I want to start by acknowledging Konami and Kazuki Takahashi for
developing the Yu-Gi-Oh! Trading Card Game that I enjoy so much.
I would also like to thank the communities and tournament stores where
I have had the chance to play. I have made wonderful memories in places
such as Patriot Games, Retro Games, the Alliance Store, El Santuario, and
many more. Surely Yu-Gi-Oh! would not be the same without the effort of
Official Tournament Stores.
I am grateful for the support of Juan P. González, Víctor Pérez, Alfonso
Ozuna, and Ryan M. Nill for their ideas, opinions, and support while writing
this book.
Also, many thanks to the duelists, family, friends and rivals with whom I
have enjoyed exciting duels. These include, Ulises and Hector Lozada, Ryan
and Chris Nill, Dany Cortez, and a really long list of names.
Finally, special thanks to my mother, Yvett, who always supported me to
enjoy and improve in this game and everything else in my life.

About the author


Asiel Corpus, PhD
He is an engineer and scientist looking to expand the boundaries of
knowledge in the field of photovoltaics. However, he likes to enjoy his free
time with videogames, board games, and other forms of abstract
entertainment that involve data or numbers.

He had his first Yu-Gi-Oh! duel when his cousin showed him some cards
at the age of 16. At that moment, he fell in love with the art of the cards, the
logic of the rules, and the strategic and random nature of the game. Since
then, he has enjoyed Yu-Gi-Oh! duels in multiple places with a great
diversity of duelists. He wrote the book, “Probability and Programming to
excel at Yu-Gi-Oh!” as a result of the cancellation of Yu-Gi-Oh! events
during the COVID-19 pandemic.

You might also like