This story is part of ESPN The Magazine's June 22 eSports Issue. Subscribe today!

GEORGE YAO WALKED into the bathroom of his unfeasibly small $1,450-a-month San Francisco apartment and slid each of his five iPads into a zip-lock freezer bag. He was preparing, with some ceremony, to defend his world title. Three months earlier, in January 2013, Yao had reached the top of the global leaderboards for Clash of Clans, a medieval warfare-themed strategy game in which a player builds defenses, trains troops and attacks other players' fortifications. The achievement had cost him dearly. At the peak of his obsession, Yao would easily spend $400 a week in the game to help him climb the leaderboards, an unbudgeted outlay that prevented him from going out with his friends on the weekend (or renting an apartment in which he could fit much more than a couch). To maintain his position, which had made his online handle, Jorge Yao, familiar to millions of Clash players around the world, Yao was running five parallel game accounts, playing them off against each other simultaneously. His focus was so single-minded that he even took his iPads into the shower so he could monitor his games through the plastic bags.

Clash of Clans is made by the Finnish game studio Supercell. It launched in August 2012 and rapidly became one of the top five highest-grossing titles in Apple's App Store. In 2013, when Yao and his invitation-only clan, North44, were at their peak, Clash of Clans helped create $555 million of revenue for the company. The next year, Supercell's revenue tripled to $1.7 billion -- a seemingly inexplicable sum produced by a roster of games that, like Clash, are free to download and can be played without spending a dime. So how is Supercell generating all that money? By relying on players who don't simply want to enjoy the game but who want to win. Players who, like Yao, are willing to spend a great deal of cash.

"The game became my life," Yao tells me from his new home in London. "I played every single day in order to maintain my ranking. It became a daily routine, even on the weekends. I was exhausted." During a three-month period at the top of the game's leaderboard, when he came home from his job as a compliance analyst on IT projects, Yao estimates that he spent close to $3,000 buying "gems," units of virtual currency that can be used to speed up every aspect of the game, from the time it takes to build fortifications to the time it takes to train virtual troops. The habit left him close to broke. After Yao joined North44, one of the hundreds of thousands of groups of players who support one another and wage war on rival clans, a sympathetic team member became Yao's patron, funding his gem habit. Later, another wealthy clan mate who lived in the United Arab Emirates bought Yao three iPads to allow him to further maximize his time in the game. What had started as a diversion had mushroomed into an obsession. Yao's immersion was total. He'd twitch his way through the long nights on cans of Red Bull, his dedication on the virtual battlefield filling Supercell's coffers.

George Yao rose to unprecedented top dog status in Clash of Clans, but the game took over his life. Peter DaSilva/The New York Times/Redux

Yao's devotion to Clash was freely given but also, from Supercell's point of view, carefully planned, developed and nurtured. Clash is the most successful so-called "freemium" game, a relatively new breed of app that aims to lock players into a spending habit. The game's developer earns its money not at the point of sale, but at the point of absorption -- and during the past decade, the techniques for captivating players have vastly improved. Every time you play a game, its maker is, in all probability, recording everything you do and using that information to keep you playing longer and spending more.

These techniques are related to those seen in the gambling industry, where slot machines are designed to create a sense of total immersion in the game, so players continue to hit the button for as long as possible. That's particularly true for more repetitive freemium games, like Candy Crush, by the design studio King. "These games allow you to zone out," says Natasha Dow Schull, an MIT professor who has been researching the links between freemium video games and slots. "They all follow this high-hit-frequency/low-volatility model that puts you into a trance where your worries drop away. It's a mechanism for escape even more than it is a mechanism for excitement."

Schull, the author of "Addiction by Design," a study of digital slot machines in Las Vegas, argues that many slots players don't necessarily know that escape is what they're seeking until they get hooked by the flashing rhythms of the machines and find the allure of the trance irresistible. More than jackpots, they crave the feeling that the real world and all its problems are melting away. Schull believes that many play the repetitive freemium games to achieve a similar type of relief. The pull of games that involve strategy and world building, like Clash of Clans, she says, is less analogous to that of slot machines -- but their developers are no less devoted to leveraging every bit of data their players produce into profit. Whether King or Supercell, video game companies have built their entire business on one premise: lengthening our stay within their virtual worlds.

IN THE PAST FEW YEARS, video game studios have made both an art and a science of optimizing their designs. Employees with job titles like "data scientist" study whether a player is more likely to click on a button if it's square or round, or whether a particular advertisement is likely to break that trancelike state and cause someone to close the game. The tiniest improvement can have fortune-changing effects for a game studio. "If you can make a change to, say, a menu color that results in your 10 million players spending an average of just a penny more every month, it adds up fast," one analyst tells me.

These techniques are familiar in the gambling industry. For some time now, Schull says, slot machine manufacturers have hired mathematical engineers to make "personalized volatility algorithms." Drawing on data from the gambler's playing history (as tracked by ubiquitous casino loyalty cards), these algorithms tailor the rhythms of a machine's payout to suit the current player's mentality, whether it's a person who prefers to take high-risk gambles or someone who makes only safe bets for modest gains.

In the video game industry, many larger developers make extensive use of psychologists and professional economists to improve the game -- and its bottom line -- in subtle ways. Riot Games, creator of League of Legends, arguably the most popular freemium eSport in the world, employs a team of data scientists to study the 5 terabytes of data generated by the 2 million players who log in each day. They use the information to ensure the game is fairly balanced and that one particular character isn't too powerful.

"It's been a fundamental shift in our understanding," says Seth Killian, a designer who worked on Street Fighter IV, the competitive fighting game that has sold more than 8 million copies since its original launch in 2008. "A game's menus, virtual stores and so on used to be viewed as an afterthought, but the scope of free-to-play games has shown that what goes on around the game can be just as important to your financial success as what's happening during a match."

The formulas are heavily guarded. In early 2009, an employee of Zynga, creator of FarmVille, downloaded 70 files from his computer to a USB storage device two weeks before leaving to join rival social game publisher Playdom (now owned by ESPN's parent company, Disney). The files included a document known as The Playbook, which Zynga claimed is a "recipe book" that contains its "secret sauce" for designing profitable Facebook games. Unbeknownst to the employee and three of his colleagues, who had also downloaded the file before they left to work for Playdom, Zynga hired a forensics team to go through their computers after they left. "Most of us had emailed or copied the files, which is technically illegal, but which is pretty normal for the game industry," says one of the employees, who asked to not be named.

Zynga sued Playdom and the four employees for theft of this document, which, Zynga claimed in its lawsuit, was "the result of years of testing, development, trial and error, analyzing customer behavior, ... optimization ... and collective know-how." In the right hands the information could be used, the company argued, to make hugely profitable games. The suit was settled for undisclosed terms one year later, but not before one of the defendants was held in contempt of court for deleting the file from his computer in a cover-up attempt, receiving a $4,000 fine and a 10-day prison sentence (the sentence was suspended).

Zynga isn't the only company intent on protecting its design secrets. Twice a month, Riot Games, the League of Legends maker, hires an actor to visit its studio in southern California and roam its halls, chatting with staff while pretending to be a new employee. The company, founded in 2006 by two USC graduates, is expanding so quickly that there are often fresh faces among its more than 1,000 employees. But new hires, like every other staff member, must wear an identification badge at all times. The actor, meanwhile, does not wear one. Any Riot employee who finds and reports the imposter wins a prize. Beneath the playfulness is a serious aim: to train employees to be observant about who should and shouldn't be walking the developer's corridors. When you're custodian of the most widely played video game on the planet, you must protect your design secrets with Sauron-like vigilance.

AS GEORGE YAO'S experience with Clash of Clans lengthened, he began to perceive the tricks the game employed to draw him in and lure him to spend. He noticed how, when he reached the top of the leaderboards, he'd spend less on the game ("I dropped from $400 a week to around $250") because there were fewer players at his level for the game to match him against in battles. He also observed that he spent less money in those weeks when Supercell did not update the game with new features.

In the final months of his obsession, Clash of Clans became what Yao described as almost "a second job." He estimates that he would play 70 to 80 hours a week and says that he lost 20 pounds during his reign because he often simply forgot to eat. For Yao, who still holds the record for longest run atop the Clash leaderboard, it was a lifestyle he could not sustain. "I played every single day in order to maintain my ranking, and after six months I felt there was not much left I could accomplish in the game itself," he says. "I wanted to quit on top rather than fizzle out slowly." On June 17, 2013, Yao took to Facebook to announce to his 20,000 followers that he was quitting the game. He'd escaped. "It was such a relief," he says quietly.

No sooner than Yao posted his message on Facebook, he heard from a surge of game studios wanting to know about what he'd learned in his year on the freemium front line. First, rival game publishers made consultancy offers, hoping to learn Clash of Clans' secrets. Then came a formal job offer. Yao was bored with his life in the finance industry, so at the same time he quit the game, he also quit his profession. He moved to London to join Space Ape Games, where he now works as manager of live operations across a number of the studio's freemium titles. Samurai Siege, the first game Yao worked on, is a "carbon copy" of Clash of Clans, he says.

Yao's work mainly involves tweaking in-game tournaments to increase participation: for example, ensuring that the prizes being offered are worthwhile enough for the top-tier players to compete for but "not too hardcore that lower-tier players don't have a shot at winning them." He is, however, coy about how the company uses data to make the game more profitable.

Freemium game companies in Asia appear more willing to talk. Barcode Footballer was the top-grossing freemium game in Japan last summer. "There are many times that we have changed the game based on player data," says Keisuke Osone, who heads the team of data analysts at the game's developer, CYBIRD, in the Shibuya area of Tokyo. This can involve changing the location of menu options on the screen, or even adapting the game to when players have the most money jangling around their pockets. "People tend to time their spending in the game around the day their salary is paid, so we tend to run special offers and promote the most desirable in-game items around that time," Osone says. "In Japan payday is usually on the 25th of each month, so we generally run campaigns on that date." The team also tweaks its digital storefront to make the most of the fact that "people like to buy things on the first day of every month" because, Osone says, they have just been billed for the previous month's purchases by the mobile phone operator.

"Every decision my team makes is catalyzed by data," says Eric Seufert, vice president of user acquisition and engagement at Rovio, the Swedish developer of the mobile game phenomenon Angry Birds. Often, the game will run two similar versions of the same ad to see which garners more clicks. This, Seufert explains, does not necessarily lead the company to run the more popular ad. It might garner more clicks from certain players, but at the same time, it might drive away others who are bigger spenders. Another ad may attract fewer hits but also prove less bothersome to the more desirable players. Seufert, who previously worked for the freemium communication service Skype, says that getting those decisions right is a matter of life or death for a game world. If too many players decide to quit or move to a rival game, the virtual world dies, potentially taking its developer down with it.

Survival is often based on finding the highest spending players, known as whales (a term that originated in the gambling industry), and keeping them invested. Will Luton, author of "Free-to-Play: Making Money From Games You Give Away" -- and a player who spends about $2,000 a year in Magic, The Gathering Online -- estimates that only 2 to 5 percent of a freemium game's audience will spend any money in the game. Of these paying players, he says, a tiny percentage of big spenders typically provide up to 50 percent of the revenue. Confoundingly, other reports, like a study from the market research company NPD in 2012, claim that 40 percent of those who have played a freemium game have made in-app payments. Since only a handful of companies release their figures, definitive data on this issue are hard to come by. It's safe to say, though, that the makers of freemium games want as large a user base as possible, filled with plenty of whales and small fish alike.

Sometimes, the whales are smaller (physically, at least) than you might expect. Last October the Belgian news site Nieuwsblad reported that a teenage boy had spent no less than $46,000 on in-game purchases in Game of War: Fire Age, using his grandfather's credit card. He later claimed that he did not realize he was spending real money. Stories of children ringing up preposterous bills are so widespread that in 2014 the Federal Trade Commission issued a successful complaint against Apple, arguing that the company did not adequately inform account holders that entering their password would open a 15-minute window during which children could incur unlimited charges in a freemium game. Apple agreed to provide full refunds to consumers, paying a minimum of $32.5 million, to settle the complaint. Google also made a $19 million settlement with the FTC, while Amazon has vowed to fight similar charges. What will remain even after all the FTC's business is settled: the uneasy fact that psychologists and economists are working to draw players, including children, into that slot-machine-like spending trance. (In 2012, Zynga formalized the relationship between the two industries when it announced a partnership with bwin.party, an online poker and casino games provider.)

Of course, there is plenty that's positive about a game like Clash of Clans: it teaches planning and strategy, encourages care and dedication and, as seen in Yao's case, can foster new friendships. But for the player who succumbs to the algorithm, it can become not only a financial burden but an emotional and psychological drain. In 2013, a few months after he quit Clash, Yao told The New York Times that he couldn't stand the sight of the game.

Yet today, just as he once labored to upgrade his troops in Clash, he works to turn casual players into legions of George Yaos -- players who give their all to the game, perhaps even beyond the limits of what they can afford, as they seek to find the flow state in which, as MIT's Schull puts it, the world's problems disappear. It can become a dispiriting cycle: Players pick up the game to escape the pressures of the world but, in time, the game can mimic those same pressures and become its own kind of stress and labor -- one that can, in some cases, even invade the shower. Does Yao ever struggle with the idea that he is working to draw others into a pattern of play from which he was relieved to escape?

"I do consider that," he says. "Some players don't know any better. They can be competing for something and they don't like what they're doing, but they do it anyway."