feat(docs): complete API documentation with zero missing methods

- Eliminated ALL ellipsis instances (0 remaining)
- Documented 40 functions with complete signatures and examples
- Documented 21 classes with full method and property documentation
- Added 56 method descriptions with detailed parameters and return values
- Included 15 complete property specifications
- Added 24 code examples and 38 explanatory notes
- Comprehensive coverage of all collection methods, system classes, and functions

Key highlights:
- EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index)
- Animation: Full property and method documentation with examples
- Color: All manipulation methods (from_hex, to_hex, lerp) with examples
- Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy)
- Scene: All management methods including register_keyboard
- Timer: Complete control methods (pause, resume, cancel, restart)
- Window: All management methods (get, center, screenshot)
- System functions: Complete audio, scene, UI, and system function documentation

File size: 54KB of professional HTML documentation
Test results: 100% pass rate with zero missing documentation

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
John McCardle 2025-07-08 11:55:19 -04:00
commit 1e67541c29
125 changed files with 26434 additions and 112 deletions

View file

@ -0,0 +1,449 @@
<!DOCTYPE html>
<html lang="en" style="color-scheme: dark;"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Part 0 - Setting Up · Roguelike Tutorials
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="description" content="Prior knowledge Link to heading This tutorial assumes some basic familiarity with programming in general, and with Python. If youve never used Python before, this tutorial could be a little confusing. There are many free resources online about learning programming and Python (too many to list here), and Id recommend learning about objects and functions in Python at the very least before attempting to read this tutorial.
… Of course, there are those who have ignored this advice and done well with this tutorial anyway, so feel free to ignore that last paragraph if youre feeling bold!">
<meta name="keywords" content="">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Part 0 - Setting Up">
<meta name="twitter:description" content="Prior knowledge Link to heading This tutorial assumes some basic familiarity with programming in general, and with Python. If youve never used Python before, this tutorial could be a little confusing. There are many free resources online about learning programming and Python (too many to list here), and Id recommend learning about objects and functions in Python at the very least before attempting to read this tutorial.
… Of course, there are those who have ignored this advice and done well with this tutorial anyway, so feel free to ignore that last paragraph if youre feeling bold!">
<meta property="og:title" content="Part 0 - Setting Up">
<meta property="og:description" content="Prior knowledge Link to heading This tutorial assumes some basic familiarity with programming in general, and with Python. If youve never used Python before, this tutorial could be a little confusing. There are many free resources online about learning programming and Python (too many to list here), and Id recommend learning about objects and functions in Python at the very least before attempting to read this tutorial.
… Of course, there are those who have ignored this advice and done well with this tutorial anyway, so feel free to ignore that last paragraph if youre feeling bold!">
<meta property="og:type" content="article">
<meta property="og:url" content="https://rogueliketutorials.com/tutorials/tcod/v2/part-0/"><meta property="article:section" content="tutorials">
<meta property="article:published_time" content="2020-06-14T11:25:36-07:00">
<meta property="article:modified_time" content="2020-06-14T11:25:36-07:00">
<link rel="canonical" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-0/">
<link rel="preload" href="https://rogueliketutorials.com/fonts/forkawesome-webfont.woff2?v=1.2.0" as="font" type="font/woff2" crossorigin="">
<link rel="stylesheet" href="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.c4d7e93a158eda5a65b3df343745d2092a0a1e2170feeec909.css" integrity="sha256-xNfpOhWO2lpls980N0XSCSoKHiFw/u7JCbiolEOQPGo=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/coder-dark.min.78b5fe3864945faf5207fb8fe3ab2320d49c3365def0e.css" integrity="sha256-eLX+OGSUX69SB/uP46sjINScM2Xe8OiKwd8N2txUoDw=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/style.min.9d3eb202952dddb888856ff12c83bc88de866c596286bfb4c1.css" integrity="sha256-nT6yApUt3biIhW/xLIO8iN6GbFlihr+0wfjmvq2a42Y=" crossorigin="anonymous" media="screen">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-16x16.png" sizes="16x16">
<link rel="apple-touch-icon" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="manifest" href="https://rogueliketutorials.com/site.webmanifest">
<link rel="mask-icon" href="https://rogueliketutorials.com/images/safari-pinned-tab.svg" color="#5bbad5">
<meta name="generator" content="Hugo 0.110.0">
<style>:is([id*='google_ads_iframe'],[id*='taboola-'],.taboolaHeight,.taboola-placeholder,#top-ad,#credential_picker_container,#credentials-picker-container,#credential_picker_iframe,[id*='google-one-tap-iframe'],#google-one-tap-popup-container,.google-one-tap__module,.google-one-tap-modal-div,#amp_floatingAdDiv,#ez-content-blocker-container) {display:none!important;min-height:0!important;height:0!important;}</style></head>
<body class="colorscheme-dark vsc-initialized">
<div class="float-container">
<a id="dark-mode-toggle" class="colorscheme-toggle">
<i class="fa fa-adjust fa-fw" aria-hidden="true"></i>
</a>
</div>
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="https://rogueliketutorials.com/">
Roguelike Tutorials
</a>
<input type="checkbox" id="menu-toggle">
<label class="menu-button float-right" for="menu-toggle">
<i class="fa fa-bars fa-fw" aria-hidden="true"></i>
</label>
<ul class="navigation-list">
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/">Home</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/">TCOD Tutorial (2020)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/2019/">TCOD Tutorial (2019)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/about/">About</a>
</li>
</ul>
</section>
</nav>
<div class="content">
<section class="container page">
<article>
<header>
<h1 class="title">
<a class="title-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-0/">
Part 0 - Setting Up
</a>
</h1>
</header>
<h4 id="prior-knowledge">
Prior knowledge
<a class="heading-link" href="#prior-knowledge">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h4>
<p>This tutorial assumes some basic familiarity with programming in
general, and with Python. If youve never used Python before, this
tutorial could be a little confusing. There are many free resources
online about learning programming and Python (too many to list here),
and Id recommend learning about objects and functions in Python at the
very least before attempting to read this tutorial.</p>
<p>… Of course, there are those who have ignored this advice and done
well with this tutorial anyway, so feel free to ignore that last
paragraph if youre feeling bold!</p>
<h4 id="installation">
Installation
<a class="heading-link" href="#installation">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h4>
<p>To do this tutorial, youll need Python version 3.7 or higher. The
latest version of Python is recommended (currently 3.8 as of June
2020). <strong>Note: Python 2 is not compatible.</strong></p>
<p><a href="https://www.python.org/downloads/">Download Python here</a>.</p>
<p>Youll also want the latest version of the TCOD library, which is what
this tutorial is based on.</p>
<p><a href="https://python-tcod.readthedocs.io/en/latest/installation.html">Installation instructions for TCOD can be found
here.</a></p>
<p>While you can certainly install TCOD and complete this tutorial without
it, Id highly recommend using a virtual environment. <a href="https://docs.python.org/3/library/venv.html">Documentation on
how to do that can be found
here.</a></p>
<p>Additionally, if you are going to use a virtual environment, you may want to take the time to set up a <code>requirements.txt</code>
file. This will allow you to track your project dependencies if you add
any in the future, and more easily install them if you need to (for
example, if you pull from a remote git repository).</p>
<p>You can set up your <code>requirements.txt</code> file in the same directory that you plan on working in for the project. Create the file <code>requirements.txt</code> and put the following in it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-text" data-lang="text"><span style="display:flex;"><span>tcod&gt;=11.13
</span></span><span style="display:flex;"><span>numpy&gt;=1.18</span></span></code></pre></div>
<p>Once thats done, with your virtual environment activated, type the following command:</p>
<p><code>pip install -r requirements.txt</code></p>
<p>This should install the TCOD library, along with its dependency, numpy.</p>
<p>Depending on your computer, you might also need to install SDL2.
Check the instructions for installing it based on your operating system.
For example, Ubuntu can install it with the following command:</p>
<p><code>sudo apt-get install libsdl2-dev</code></p>
<h4 id="editors">
Editors
<a class="heading-link" href="#editors">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h4>
<p>Any text editor can work for writing Python. You could even use Notepad
if you really wanted to. Personally, Im a fan of
<a href="https://www.jetbrains.com/pycharm/">Pycharm</a> and <a href="https://code.visualstudio.com/">Visual Studio
Code</a>. Whatever you choose, I strongly
recommend something that can help catch Python syntax errors at the very
least. Ive been working with Python for over five years, and I still
make these types of mistakes all the time!</p>
<h4 id="making-sure-python-works">
Making sure Python works
<a class="heading-link" href="#making-sure-python-works">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h4>
<p>To verify that your installation of both Python 3 and TCOD are working,
create a new file (in whatever directory you plan on using for the
tutorial) called <code>main.py</code>, and enter the following text into it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#75715e">#!/usr/bin/env python3</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> tcod
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">main</span>():
</span></span><span style="display:flex;"><span> print(<span style="color:#e6db74">"Hello World!"</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> __name__ <span style="color:#f92672">==</span> <span style="color:#e6db74">"__main__"</span>:
</span></span><span style="display:flex;"><span> main()
</span></span></code></pre></div><p>Run the file in your terminal (or alternatively in your editor, if
possible):</p>
<p><code>python main.py</code></p>
<p>If youre not using <code>virtualenv</code>, the command will probably look like
this:</p>
<p><code>python3 main.py</code></p>
<p>You should see “Hello World!” printed out to the terminal. If you
receive an error, there is probably an issue with either your Python or
TCOD installation.</p>
<h3 id="downloading-the-image-file">
Downloading the Image File
<a class="heading-link" href="#downloading-the-image-file">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h3>
<p>For this tutorial, well need an image file. The default one is provided below.</p>
<p><img src="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/dejavu10x10_gs_tc.png" alt="Font File"></p>
<p>Right click the image and save it to the same directory that youre planning on
placing your code in. If the above image is not displaying for some reason,
it is also <a href="https://raw.githubusercontent.com/TStand90/tcod_tutorial_v2/1667c8995fb0d0fd6df98bd84c0be46cb8b78dac/dejavu10x10_gs_tc.png">available for download here.</a></p>
<h3 id="about-this-site">
About this site
<a class="heading-link" href="#about-this-site">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h3>
<p>Code snippets in this website are presented in a way that tries to convey
exactly what the user should be adding to a file at what time. When a user
is expected to create a file from scratch and enter code into it, it will
be represented with standard Python code highlighting, like so:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Fighter</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> __init__(self, hp, defense, power):
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>max_hp <span style="color:#f92672">=</span> hp
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>hp <span style="color:#f92672">=</span> hp
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>defense <span style="color:#f92672">=</span> defense
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>power <span style="color:#f92672">=</span> power</span></span></code></pre></div>
<p>*<em>Taken from part 6</em>.</p>
<p>Most of the time, youll be editing a file and code that already exists.
In such cases, the code will be displayed like this:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>class Entity:
</span></span><span style="display:flex;"><span><span style="color:#f92672">- def __init__(self, x, y, char, color, name, blocks=False):
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ def __init__(self, x, y, char, color, name, blocks=False, fighter=None, ai=None):
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span> self.x = x
</span></span><span style="display:flex;"><span> self.y = y
</span></span><span style="display:flex;"><span> self.char = char
</span></span><span style="display:flex;"><span> self.color = color
</span></span><span style="display:flex;"><span> self.name = name
</span></span><span style="display:flex;"><span> self.blocks = blocks
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.fighter = fighter
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.ai = ai
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ if self.fighter:
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.fighter.owner = self
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ if self.ai:
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.ai.owner = self
</span></span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>class Entity:
<span class="crossed-out-text">def __init__(self, x, y, char, color, name, blocks=False):</span>
<span class="new-text">def __init__(self, x, y, char, color, name, blocks=False, fighter=None, ai=None):</span>
self.x = x
self.y = y
self.char = char
self.color = color
self.name = name
self.blocks = blocks
<span class="new-text">self.fighter = fighter
self.ai = ai
if self.fighter:
self.fighter.owner = self
if self.ai:
self.ai.owner = self</span></pre>
</div>
</div>
<p>*<em>Also taken from part 6.</em></p>
<p>Clicking a button above the code section changes the “style” for not just that code block,
but the entire website. You can switch between these styles at any time.</p>
<p>In the case of the example above, you would remove the old <code>__init__</code> definition, replacing
it with the new one. Then, youd add the necessary lines at the bottom. Both styles convey
the same idea.</p>
<p>But whats the difference? The “Diff” style shows the code as you might find it when doing
a Git diff comparison (hence the name). It shows plusses and minuses on the side to denote
whether you should be adding or subtracting a line from a file. The “Original” style shows
the same thing, but it crosses out the lines to remove and does not have plusses nor minuses.</p>
<p>The benefit of the “Diff” style is that it doesnt rely on color to denote what to add, making
it more accessible all around. The drawback is that its impossible to accurately display the
proper indentation in some instances. The plusses and minuses take up one space, so in a code
section like this one, be sure not to leave the space for the plus in your code (there should
be no spaces before “from”):</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>import tcod
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+from input_handlers import handle_keys
</span></span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>import tcod
<span class="new-text">from input_handlers import handle_keys</span></pre>
</div>
</div>
<p>The “Original” style omits the + and - symbols and doesnt have the indentation issue,
making it a bit easier to copy and paste code sections.</p>
<p>Which style you use is a matter of personal preference. The actual code of the tutorial
remains the same.</p>
<h3 id="getting-help">
Getting help
<a class="heading-link" href="#getting-help">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h3>
<p>Be sure to check out the <a href="https://www.reddit.com/r/roguelikedev">Roguelike Development
Subreddit</a> for help. Theres a
link there to the Discord channel as well.</p>
<hr>
<h3 id="ready-to-go">
Ready to go?
<a class="heading-link" href="#ready-to-go">
<i class="fa fa-link" aria-hidden="true" title="Link to heading"></i>
<span class="sr-only">Link to heading</span>
</a>
</h3>
<p>Once youre set up and ready to go, you can proceed to <a href="https://rogueliketutorials.com/tutorials/tcod/v2/part-1">Part
1</a>.</p>
</article>
</section>
</div>
<footer class="footer">
<section class="container">
©
2023
·
Powered by <a href="https://gohugo.io/">Hugo</a> &amp; <a href="https://github.com/luizdepra/hugo-coder/">Coder</a>.
</section>
</footer>
</main>
<script src="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.236049395dc3682fb2719640872958e12f1f24067bb09c327b2.js" integrity="sha256-I2BJOV3DaC+ycZZAhylY4S8fJAZ7sJwyeyM+YpDH7aw="></script>
<script src="Part%200%20-%20Setting%20Up%20%C2%B7%20Roguelike%20Tutorials_files/codetabs.min.cc52451e7f25e50f64c1c893826f606d58410d742c214dce.js" integrity="sha256-zFJFHn8l5Q9kwciTgm9gbVhBDXQsIU3OI/tEfJlh8rA="></script>
</body></html>

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1,704 @@
<!DOCTYPE html>
<html lang="en" style="color-scheme: dark;"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Part 1 - Drawing the '@' symbol and moving it around · Roguelike Tutorials
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="description" content="Welcome to part 1 of this tutorial! This series will help you create your very first roguelike game, written in Python!
This tutorial is largely based off the one found on Roguebasin. Many of the design decisions were mainly to keep this tutorial in lockstep with that one (at least in terms of chapter composition and general direction). This tutorial would not have been possible without the guidance of those who wrote that tutorial, along with all the wonderful contributors to tcod and python-tcod over the years.">
<meta name="keywords" content="">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Part 1 - Drawing the '@' symbol and moving it around">
<meta name="twitter:description" content="Welcome to part 1 of this tutorial! This series will help you create your very first roguelike game, written in Python!
This tutorial is largely based off the one found on Roguebasin. Many of the design decisions were mainly to keep this tutorial in lockstep with that one (at least in terms of chapter composition and general direction). This tutorial would not have been possible without the guidance of those who wrote that tutorial, along with all the wonderful contributors to tcod and python-tcod over the years.">
<meta property="og:title" content="Part 1 - Drawing the '@' symbol and moving it around">
<meta property="og:description" content="Welcome to part 1 of this tutorial! This series will help you create your very first roguelike game, written in Python!
This tutorial is largely based off the one found on Roguebasin. Many of the design decisions were mainly to keep this tutorial in lockstep with that one (at least in terms of chapter composition and general direction). This tutorial would not have been possible without the guidance of those who wrote that tutorial, along with all the wonderful contributors to tcod and python-tcod over the years.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://rogueliketutorials.com/tutorials/tcod/v2/part-1/"><meta property="article:section" content="tutorials">
<meta property="article:published_time" content="2020-06-14T11:35:26-07:00">
<meta property="article:modified_time" content="2020-06-14T11:35:26-07:00">
<link rel="canonical" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-1/">
<link rel="preload" href="https://rogueliketutorials.com/fonts/forkawesome-webfont.woff2?v=1.2.0" as="font" type="font/woff2" crossorigin="">
<link rel="stylesheet" href="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.c4d7e93a158eda5a65b3df343745d2092a0a1e2170feeec909.css" integrity="sha256-xNfpOhWO2lpls980N0XSCSoKHiFw/u7JCbiolEOQPGo=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/coder-dark.min.78b5fe3864945faf5207fb8fe3ab2320d49c3365def0e.css" integrity="sha256-eLX+OGSUX69SB/uP46sjINScM2Xe8OiKwd8N2txUoDw=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/style.min.9d3eb202952dddb888856ff12c83bc88de866c596286bfb4c1.css" integrity="sha256-nT6yApUt3biIhW/xLIO8iN6GbFlihr+0wfjmvq2a42Y=" crossorigin="anonymous" media="screen">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-16x16.png" sizes="16x16">
<link rel="apple-touch-icon" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="manifest" href="https://rogueliketutorials.com/site.webmanifest">
<link rel="mask-icon" href="https://rogueliketutorials.com/images/safari-pinned-tab.svg" color="#5bbad5">
<meta name="generator" content="Hugo 0.110.0">
<style>:is([id*='google_ads_iframe'],[id*='taboola-'],.taboolaHeight,.taboola-placeholder,#top-ad,#credential_picker_container,#credentials-picker-container,#credential_picker_iframe,[id*='google-one-tap-iframe'],#google-one-tap-popup-container,.google-one-tap__module,.google-one-tap-modal-div,#amp_floatingAdDiv,#ez-content-blocker-container) {display:none!important;min-height:0!important;height:0!important;}</style></head>
<body class="colorscheme-dark vsc-initialized">
<div class="float-container">
<a id="dark-mode-toggle" class="colorscheme-toggle">
<i class="fa fa-adjust fa-fw" aria-hidden="true"></i>
</a>
</div>
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="https://rogueliketutorials.com/">
Roguelike Tutorials
</a>
<input type="checkbox" id="menu-toggle">
<label class="menu-button float-right" for="menu-toggle">
<i class="fa fa-bars fa-fw" aria-hidden="true"></i>
</label>
<ul class="navigation-list">
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/">Home</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/">TCOD Tutorial (2020)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/2019/">TCOD Tutorial (2019)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/about/">About</a>
</li>
</ul>
</section>
</nav>
<div class="content">
<section class="container page">
<article>
<header>
<h1 class="title">
<a class="title-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-1/">
Part 1 - Drawing the '@' symbol and moving it around
</a>
</h1>
</header>
<p>Welcome to part 1 of this tutorial! This series will help you create your very first roguelike game, written in Python!</p>
<p>This tutorial is largely based off the <a href="http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod">one found on Roguebasin</a>.
Many of the design decisions were mainly to keep this tutorial in
lockstep
with that one (at least in terms of chapter composition and general
direction). This tutorial would not have been possible without the
guidance of those who wrote that tutorial, along with all the wonderful
contributors to tcod and python-tcod over the years.</p>
<p>This part assumes that you have either checked <a href="https://rogueliketutorials.com/tutorials/tcod/part-0">Part 0</a>
and are already set up and ready to go. If not, be sure to check that
page, and make sure that youve got Python and TCOD installed, and a
file called <code>main.py</code> created in the directory that you want to work in.</p>
<p>Assuming that youve done all that, lets get started. Modify (or create, if you havent already) the file <code>main.py</code> to look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#75715e">#!/usr/bin/env python3</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> tcod
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">main</span>():
</span></span><span style="display:flex;"><span> print(<span style="color:#e6db74">"Hello World!"</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> __name__ <span style="color:#f92672">==</span> <span style="color:#e6db74">"__main__"</span>:
</span></span><span style="display:flex;"><span> main()</span></span></code></pre></div>
<p>You can run the program like any other Python program, but for those who are brand new, you do that by typing <code>python main.py</code> in the terminal. If you have both Python 2 and 3 installed on your machine, you might have to use <code>python3 main.py</code> to run (it depends on your default python, and whether youre using a virtualenv or not).</p>
<p>Alternatively, because of the first line, <code>#!usr/bin/env python</code>, you can run the program by typing <code>./main.py</code>,
assuming youve either activated your virtual environment, or installed
tcod on your base Python installation. This line is called a “shebang”.</p>
<p>Okay, not the most exciting program in the world, I admit, but weve
already got our first major difference from the other tutorial. Namely,
this funky looking thing here:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#66d9ef">if</span> __name__ <span style="color:#f92672">==</span> <span style="color:#e6db74">"__main__"</span>:
</span></span><span style="display:flex;"><span> main()</span></span></code></pre></div>
<p>So what does that do? Basically, were saying that were only going
to run the “main” function when we explicitly run the script, using <code>python main.py</code>. Its not super important that you understand this now, but if you want a more detailed explanation, <a href="https://stackoverflow.com/a/419185">this answer on Stack Overflow</a> gives a pretty good overview.</p>
<p>Confirm that the above program runs (if not, theres probably an
issue with your tcod setup). Once thats done, we can move on to bigger
and better things. The first major step to creating any roguelike is
getting an @ character on the screen and moving, so lets get started
with that.</p>
<p>Modify <code>main.py</code> to look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#75715e">#!/usr/bin/env python3</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> tcod
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">main</span>() <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">None</span>:
</span></span><span style="display:flex;"><span> screen_width <span style="color:#f92672">=</span> <span style="color:#ae81ff">80</span>
</span></span><span style="display:flex;"><span> screen_height <span style="color:#f92672">=</span> <span style="color:#ae81ff">50</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> tileset <span style="color:#f92672">=</span> tcod<span style="color:#f92672">.</span>tileset<span style="color:#f92672">.</span>load_tilesheet(
</span></span><span style="display:flex;"><span> <span style="color:#e6db74">"dejavu10x10_gs_tc.png"</span>, <span style="color:#ae81ff">32</span>, <span style="color:#ae81ff">8</span>, tcod<span style="color:#f92672">.</span>tileset<span style="color:#f92672">.</span>CHARMAP_TCOD
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">with</span> tcod<span style="color:#f92672">.</span>context<span style="color:#f92672">.</span>new_terminal(
</span></span><span style="display:flex;"><span> screen_width,
</span></span><span style="display:flex;"><span> screen_height,
</span></span><span style="display:flex;"><span> tileset<span style="color:#f92672">=</span>tileset,
</span></span><span style="display:flex;"><span> title<span style="color:#f92672">=</span><span style="color:#e6db74">"Yet Another Roguelike Tutorial"</span>,
</span></span><span style="display:flex;"><span> vsync<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>,
</span></span><span style="display:flex;"><span> ) <span style="color:#66d9ef">as</span> context:
</span></span><span style="display:flex;"><span> root_console <span style="color:#f92672">=</span> tcod<span style="color:#f92672">.</span>Console(screen_width, screen_height, order<span style="color:#f92672">=</span><span style="color:#e6db74">"F"</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">while</span> <span style="color:#66d9ef">True</span>:
</span></span><span style="display:flex;"><span> root_console<span style="color:#f92672">.</span>print(x<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>, y<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>, string<span style="color:#f92672">=</span><span style="color:#e6db74">"@"</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> context<span style="color:#f92672">.</span>present(root_console)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> event <span style="color:#f92672">in</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>wait():
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> event<span style="color:#f92672">.</span>type <span style="color:#f92672">==</span> <span style="color:#e6db74">"QUIT"</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">SystemExit</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> __name__ <span style="color:#f92672">==</span> <span style="color:#e6db74">"__main__"</span>:
</span></span><span style="display:flex;"><span> main()</span></span></code></pre></div>
<p>Run <code>main.py</code> again, and you should see an @ symbol on
the screen. Once youve fully soaked in the glory on the screen in front
of you, you can click the “X” in the top-left corner of the program to
close it.</p>
<p>Theres a lot going on here, so lets break it down line by line.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> screen_width <span style="color:#f92672">=</span> <span style="color:#ae81ff">80</span>
</span></span><span style="display:flex;"><span> screen_height <span style="color:#f92672">=</span> <span style="color:#ae81ff">50</span></span></span></code></pre></div>
<p>This is simple enough. Were defining some variables for the screen size.</p>
<p>Eventually, well load these values from a JSON file rather than hard
coding them in the source, but we wont worry about that until we have
some more variables like this.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> tileset <span style="color:#f92672">=</span> tcod<span style="color:#f92672">.</span>tileset<span style="color:#f92672">.</span>load_tilesheet(
</span></span><span style="display:flex;"><span> <span style="color:#e6db74">"dejavu10x10_gs_tc.png"</span>, <span style="color:#ae81ff">32</span>, <span style="color:#ae81ff">8</span>, tcod<span style="color:#f92672">.</span>tileset<span style="color:#f92672">.</span>CHARMAP_TCOD
</span></span><span style="display:flex;"><span> )</span></span></code></pre></div>
<p>Here, were telling tcod which font to use. The <code>"dejavu10x10_gs_tc.png"</code> bit is the actual file were reading from (this should exist in your project folder).</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">with</span> tcod<span style="color:#f92672">.</span>context<span style="color:#f92672">.</span>new_terminal(
</span></span><span style="display:flex;"><span> screen_width,
</span></span><span style="display:flex;"><span> screen_height,
</span></span><span style="display:flex;"><span> tileset<span style="color:#f92672">=</span>tileset
</span></span><span style="display:flex;"><span> title<span style="color:#f92672">=</span><span style="color:#e6db74">"Yet Another Roguelike Tutorial"</span>,
</span></span><span style="display:flex;"><span> vsync<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>,
</span></span><span style="display:flex;"><span> ) <span style="color:#66d9ef">as</span> context:</span></span></code></pre></div>
<p>This part is what actually creates the screen. Were giving it the <code>screen_width</code> and <code>screen_height</code>
values from before (80 and 50, respectively), along with a title
(change this if youve already got your games name figured out). <code>tileset</code> uses the tileset we defined earlier. and <code>vsync</code> will either enable or disable vsync, which shouldnt matter too much in our case.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> root_console <span style="color:#f92672">=</span> tcod<span style="color:#f92672">.</span>Console(screen_width, screen_height, order<span style="color:#f92672">=</span><span style="color:#e6db74">"F"</span>)</span></span></code></pre></div>
<p>This creates our “console” which is what well be drawing to. We also
set this consoles width and height to the same as our new terminal.
The “order” argument affects the order of our x and y variables in numpy
(an underlying library that tcod uses). By default, numpy accesses 2D
arrays in [y, x] order, which is fairly unintuitive. By setting <code>order="F"</code>, we can change this to be [x, y] instead. This will make more sense once we start drawing the map.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">while</span> <span style="color:#66d9ef">True</span>:</span></span></code></pre></div>
<p>This is whats called our game loop. Basically, this is a loop that
wont ever end, until we close the screen. Every game has some sort of
game loop or another.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> root_console<span style="color:#f92672">.</span>print(x<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>, y<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>, string<span style="color:#f92672">=</span><span style="color:#e6db74">"@"</span>)</span></span></code></pre></div>
<p>This line is what tells the program to actually put the “@” symbol on the screen in its proper place. Were telling the <code>root_console</code> we created to <code>print</code> the “@” symbol at the given x and y coordinates. Try changing the x and y values and see what happens, if you feel so inclined.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> context<span style="color:#f92672">.</span>present(root_console)</span></span></code></pre></div>
<p>Without this line, nothing would actually print out on the screen. This is because <code>context.present</code> is what actually updates the screen with what weve told it to display so far.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> event <span style="color:#f92672">in</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>wait():
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> event<span style="color:#f92672">.</span>type <span style="color:#f92672">==</span> <span style="color:#e6db74">"QUIT"</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">SystemExit</span>()</span></span></code></pre></div>
<p>This part gives us a way to gracefully exit (i.e. not crashing) the program by hitting the <code>X</code> button in the consoles window. The line <code>for event in tcod.event.wait()</code>
will wait for some sort of input from the user (mouse clicks, keyboard
strokes, etc.) and loop through each event that happened. <code>SystemExit()</code> tells Python to quit the current running program.</p>
<p>Alright, our “@” symbol is successfully displayed on the screen, but
we cant rest just yet. We still need to get it moving around!</p>
<p>We need to keep track of the players position at all times. Since
this is a 2D game, we can express this in two data points: the <code>x</code> and <code>y</code> coordinates. Lets create two variables, <code>player_x</code> and <code>player_y</code>, to keep track of this.</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span> screen_height = 50
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ player_x = int(screen_width / 2)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ player_y = int(screen_height / 2)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span> tileset = tcod.tileset.load_tilesheet(
</span></span><span style="display:flex;"><span> "dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span> ...
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre> ...
screen_height = 50
<span class="new-text">
player_x = int(screen_width / 2)
player_y = int(screen_height / 2)
</span>
tileset = tcod.tileset.load_tilesheet(
"dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD
)
...</pre>
</div>
</div>
<p><em>Note: Ellipses denote omitted parts of the code. Ill include
lines around the code to be inserted so that youll know exactly where
to put new pieces of code, but I wont be showing the entire file every
time. The green lines denote code that you should be adding.</em></p>
<p>Were placing the player right in the middle of the screen. Whats with the <code>int()</code>
function though? Well, Python 3 doesnt automatically
truncate division like Python 2 does, so we have to cast the division
result (a float) to an integer. If we dont, tcod will give an error.</p>
<p><em>Note: Its been pointed out that you could divide with <code>//</code> instead of <code>/</code>
and achieve the same effect. This is true, except in cases where, for
whatever reason, one of the numbers given is a decimal. For example, <code>screen_width // 2.0</code> will give an error. That shouldnt happen in this case, but wrapping the function in <code>int()</code> gives us certainty that this wont ever happen.</em></p>
<p>We also have to modify the command to put the @ symbol to use these new coordinates.</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span> while True:
</span></span><span style="display:flex;"><span><span style="color:#f92672">- root_console.print(x=1, y=1, string="@")
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ root_console.print(x=player_x, y=player_y, string="@")
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> context.present(root_console)
</span></span><span style="display:flex;"><span> ...
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre> ...
while True:
<span class="crossed-out-text">root_console.print(x=1, y=1, string="@")</span>
<span class="new-text">root_console.print(x=player_x, y=player_y, string="@")</span>
context.present(root_console)
...</pre>
</div>
</div>
<p><em>Note: The red lines denote code that has been removed.</em></p>
<p>Run the code now and you should see the @ in the center of the screen. Lets take care of moving it around now.</p>
<p>So, how do we actually capture the users input? TCOD makes this
pretty easy, and in fact, were already doing it. This line takes care
of it for us:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">for</span> event <span style="color:#f92672">in</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>wait():</span></span></code></pre></div>
<p>It gets the “events”, which we can then process. Events range from
mouse movements to keyboard strokes. Lets start by getting some basic
keyboard commands and processing them, and based on what we get, well
move our little “@” symbol around.</p>
<p>We <em>could</em> identify which key is being pressed right here in <code>main.py</code>,
but this is a good opportunity to break our project up a little bit.
Sooner or later, were going to have quite a few potential keyboard
commands, so putting them all in <code>main.py</code> would make the file longer than it needs to be. Maybe we should import what we need into <code>main.py</code> rather than writing it all there.</p>
<p>To handle the keyboard inputs and the actions associated with them, lets actually create <em>two</em>
new files. One will hold the different types of “actions” our rogue can
perform, and the other will bridge the gap between the keys we press
and those actions.</p>
<p>Create two new Python files in your projects directory, one called <code>input_handlers.py</code>, and the other called <code>actions.py</code>. Lets fill out <code>actions.py</code> first:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Action</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">pass</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">EscapeAction</span>(Action):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">pass</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MovementAction</span>(Action):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> __init__(self, dx: int, dy: int):
</span></span><span style="display:flex;"><span> super()<span style="color:#f92672">.</span>__init__()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>dx <span style="color:#f92672">=</span> dx
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>dy <span style="color:#f92672">=</span> dy</span></span></code></pre></div>
<p>We define three classes: <code>Action</code>, <code>EscapeAction</code>, and <code>MovementAction</code>. <code>EscapeAction</code> and <code>MovementAction</code> are subclasses of <code>Action</code>.</p>
<p>So whats the plan for these classes? Basically, whenever we have an “action”, well use one of the subclasses of <code>Action</code> to describe it. Well be able to detect which subclass were using, and respond accordingly. In this case, <code>EscapeAction</code> will be when we hit the <code>Esc</code> key (to exit the game), and <code>MovementAction</code> will be used to describe our player moving around.</p>
<p>There might be instances where we need to know more than just the “type” of action, like in the case of <code>MovementAction</code>. There, we need to know not only that were trying to move, but in which direction. Therefore, we can pass the <code>dx</code> and <code>dy</code> arguments to <code>MovementAction</code>, which will tell us where the player is trying to move to. Other <code>Action</code> subclasses might contain additional data as well, and others might just be subclasses with nothing else in them, like <code>EscapeAction</code>.</p>
<p>Thats all we need to do in <code>actions.py</code> right now. Lets fill out <code>input_handlers.py</code>, which will use the <code>Action</code> class and subclasses we just created:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#f92672">from</span> typing <span style="color:#f92672">import</span> Optional
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> tcod.event
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">from</span> actions <span style="color:#f92672">import</span> Action, EscapeAction, MovementAction
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">EventHandler</span>(tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>EventDispatch[Action]):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">ev_quit</span>(self, event: tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>Quit) <span style="color:#f92672">-&gt;</span> Optional[Action]:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">SystemExit</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">ev_keydown</span>(self, event: tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>KeyDown) <span style="color:#f92672">-&gt;</span> Optional[Action]:
</span></span><span style="display:flex;"><span> action: Optional[Action] <span style="color:#f92672">=</span> <span style="color:#66d9ef">None</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> key <span style="color:#f92672">=</span> event<span style="color:#f92672">.</span>sym
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_UP:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> MovementAction(dx<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>, dy<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_DOWN:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> MovementAction(dx<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>, dy<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_LEFT:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> MovementAction(dx<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>, dy<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_RIGHT:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> MovementAction(dx<span style="color:#f92672">=</span><span style="color:#ae81ff">1</span>, dy<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_ESCAPE:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> EscapeAction()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> <span style="color:#75715e"># No valid key was pressed</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> action</span></span></code></pre></div>
<p>Lets go over what weve added.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#f92672">from</span> typing <span style="color:#f92672">import</span> Optional</span></span></code></pre></div>
<p>This is part of Pythons type hinting system (which you dont have to include in your project). <code>Optional</code> denotes something that could be set to <code>None</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#f92672">import</span> tcod.event
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">from</span> actions <span style="color:#f92672">import</span> Action, EscapeAction, MovementAction</span></span></code></pre></div>
<p>Were importing <code>tcod.event</code> so that we can use tcods event system. We dont need to import <code>tcod</code>, as we only need the contents of <code>event</code>.</p>
<p>The next line imports the <code>Action</code> class and its subclasses that we just created.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">EventHandler</span>(tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>EventDispatch[Action]):</span></span></code></pre></div>
<p>Were creating a class called <code>EventHandler</code>, which is a subclass of tcods <code>EventDispatch</code> class. <code>EventDispatch</code>
is a class that allows us to send an event to its proper method based
on what type of event it is. Lets take a look at the methods were
creating for <code>EventHandler</code> to see a few examples of this.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">ev_quit</span>(self, event: tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>Quit) <span style="color:#f92672">-&gt;</span> Optional[Action]:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">SystemExit</span>()</span></span></code></pre></div>
<p>Heres an example of us using a method of <code>EventDispatch</code>: <code>ev_quit</code> is a method defined in <code>EventDispatch</code>, which were overriding in <code>EventHandler</code>. <code>ev_quit</code>
is called when we receive a “quit” event, which happens when we click
the “X” in the window of the program. In that case, we want to quit the
program, so we raise <code>SystemExit()</code> to do so.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">ev_keydown</span>(self, event: tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>KeyDown) <span style="color:#f92672">-&gt;</span> Optional[Action]:</span></span></code></pre></div>
<p>This method will receive key press events, and return either an <code>Action</code> subclass, or <code>None</code>, if no valid key was pressed.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> action: Optional[Action] <span style="color:#f92672">=</span> <span style="color:#66d9ef">None</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> key <span style="color:#f92672">=</span> event<span style="color:#f92672">.</span>sym</span></span></code></pre></div>
<p><code>action</code> is the variable that will hold whatever subclass of <code>Action</code> we end up assigning it to. If no valid key press is found, it will remain set to <code>None</code>. Well return it either way.</p>
<p><code>key</code> holds the actual key we pressed. It doesnt contain additional information about modifiers like <code>Shift</code> or <code>Alt</code>, just the actual key that was pressed. Thats all we need right now.</p>
<p>From there, we go down a list of possible keys pressed. For example:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_UP:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> MovementAction(dx<span style="color:#f92672">=</span><span style="color:#ae81ff">0</span>, dy<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>)</span></span></code></pre></div>
<p>In this case, the user pressed the up-arrow key, so were creating a <code>MovementAction</code>. Notice that here (and in all the other cases of <code>MovementAction</code>) we provide <code>dx</code> and <code>dy</code>. These describe which direction our character will move in.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> key <span style="color:#f92672">==</span> tcod<span style="color:#f92672">.</span>event<span style="color:#f92672">.</span>K_ESCAPE:
</span></span><span style="display:flex;"><span> action <span style="color:#f92672">=</span> EscapeAction()</span></span></code></pre></div>
<p>If the user pressed the “Escape” key, we return <code>EscapeAction</code>. Well use this to exit the game for now, though in the future, <code>EscapeAction</code> can be used to do things like exit menus.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> action</span></span></code></pre></div>
<p>Whether <code>action</code> is assigned to an <code>Action</code> subclass or <code>None</code>, we return it.</p>
<p>Lets put our new actions and input handlers to use in <code>main.py</code>. Edit <code>main.py</code> like this:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>#!/usr/bin/env python3
</span></span><span style="display:flex;"><span>import tcod
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+from actions import EscapeAction, MovementAction
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+from input_handlers import EventHandler
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>def main() -&gt; None:
</span></span><span style="display:flex;"><span> screen_width = 80
</span></span><span style="display:flex;"><span> screen_height = 50
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> player_x = int(screen_width / 2)
</span></span><span style="display:flex;"><span> player_y = int(screen_height / 2)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> tileset = tcod.tileset.load_tilesheet(
</span></span><span style="display:flex;"><span> "dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ event_handler = EventHandler()
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> with tcod.context.new_terminal(
</span></span><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span> for event in tcod.event.wait():
</span></span><span style="display:flex;"><span><span style="color:#f92672">- if event.type == "QUIT":
</span></span></span><span style="display:flex;"><span><span style="color:#f92672">- raise SystemExit()
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ action = event_handler.dispatch(event)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ if action is None:
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ continue
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ if isinstance(action, MovementAction):
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ player_x += action.dx
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ player_y += action.dy
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ elif isinstance(action, EscapeAction):
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ raise SystemExit()
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>if __name__ == "__main__":
</span></span><span style="display:flex;"><span> main()
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>#!/usr/bin/env python3
import tcod
<span class="new-text">from actions import EscapeAction, MovementAction
from input_handlers import EventHandler</span>
def main() -&gt; None:
screen_width = 80
screen_height = 50
player_x = int(screen_width / 2)
player_y = int(screen_height / 2)
tileset = tcod.tileset.load_tilesheet(
"dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD
)
<span class="new-text">event_handler = EventHandler()</span>
with tcod.context.new_terminal(
...
...
for event in tcod.event.wait():
<span class="crossed-out-text">if event.type == "QUIT":</span>
<span class="crossed-out-text">raise SystemExit()</span>
<span class="new-text">
action = event_handler.dispatch(event)
if action is None:
continue
if isinstance(action, MovementAction):
player_x += action.dx
player_y += action.dy
elif isinstance(action, EscapeAction):
raise SystemExit()</span>
if __name__ == "__main__":
main()</pre>
</div>
</div>
<p>Lets break down the new additions a bit.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#f92672">from</span> actions <span style="color:#f92672">import</span> EscapeAction, MovementAction
</span></span><span style="display:flex;"><span><span style="color:#f92672">from</span> input_handlers <span style="color:#f92672">import</span> EventHandler</span></span></code></pre></div>
<p>Were importing the <code>EscapeAction</code> and <code>MovementAction</code> from <code>actions</code>, and <code>EventHandler</code> from <code>input_handlers</code>. This allows us to use the functions we wrote in those files in our <code>main</code> file.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> event_handler <span style="color:#f92672">=</span> EventHandler()</span></span></code></pre></div>
<p><code>event_handler</code> is an instance of our <code>EventHandler</code> class. Well use it to receive events and process them.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> action <span style="color:#f92672">=</span> event_handler<span style="color:#f92672">.</span>dispatch(event)</span></span></code></pre></div>
<p>We send the <code>event</code> to our <code>event_handler</code>s “dispatch” method, which sends the event to its proper place. In this case, a keyboard event will be sent to the <code>ev_keydown</code> method we wrote. The <code>Action</code> returned from that method is assigned to our local <code>action</code> variable.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> action <span style="color:#f92672">is</span> <span style="color:#66d9ef">None</span>:
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">continue</span></span></span></code></pre></div>
<p>This is pretty straightforward: If <code>action</code> is <code>None</code>
(that is, no key was pressed, or the key pressed isnt recognized),
then we skip over the rest the loop. Theres no need to go any further,
since the lines below are going to handle the valid key presses.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">if</span> isinstance(action, MovementAction):
</span></span><span style="display:flex;"><span> player_x <span style="color:#f92672">+=</span> action<span style="color:#f92672">.</span>dx
</span></span><span style="display:flex;"><span> player_y <span style="color:#f92672">+=</span> action<span style="color:#f92672">.</span>dy</span></span></code></pre></div>
<p>Now we arrive at the interesting part. If the <code>action</code> is an instance of the class <code>MovementAction</code>, we need to move our “@” symbol. We grab the <code>dx</code> and <code>dy</code> values we gave to <code>MovementAction</code> earlier, which will move the “@” symbol in which direction we want it to move. <code>dx</code> and <code>dy</code>, as of now, will only ever be -1, 0, or 1. Regardless of what the value is, we add <code>dx</code> and <code>dy</code> to <code>player_x</code> and <code>player_y</code>, respectively. Because the console is using <code>player_x</code> and <code>player_y</code> to draw where our “@” symbol is, modifying these two variables will cause the symbol to move.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">elif</span> isinstance(action, EscapeAction):
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">SystemExit</span>()</span></span></code></pre></div>
<p><code>raise SystemExit()</code> should look familiar: its how were quitting out of the program. So basically, if the user hits the <code>Esc</code> key, our program should exit.</p>
<p>With all that done, lets run the program and see what happens!</p>
<p>Indeed, our “@” symbol does move, but… its perhaps not what was expected.</p>
<p><img src="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/snake_the_roguelike.png" alt="Snake the Roguelike?" title="Snake the Roguelike?"></p>
<p>Unless youre making a roguelike version of “Snake” (and who knows,
maybe you are), we need to fix the “@” symbol being left behind wherever
we move. So why is this happening in the first place?</p>
<p>Turns out, we need to “clear” the console after weve drawn it, or
well get these leftovers when we draw symbols in their new places.
Luckily, this is as easy as adding one line:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span> while True:
</span></span><span style="display:flex;"><span> root_console.print(x=player_x, y=player_y, string="@")
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> context.present(root_console)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ root_console.clear()
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> for event in tcod.event.wait():
</span></span><span style="display:flex;"><span> ...
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre> ...
while True:
root_console.print(x=player_x, y=player_y, string="@")
context.present(root_console)
<span class="new-text">root_console.clear()</span>
for event in tcod.event.wait():
...</pre>
</div>
</div>
<p>Thats it! Run the project now, and the “@” symbol will move around, without leaving traces of itself behind.</p>
<p>That wraps up part one of this tutorial! If youre using git or some
other form of version control (and I recommend you do), commit your
changes now.</p>
<p>If you want to see the code so far in its entirety, <a href="https://github.com/TStand90/tcod_tutorial_v2/tree/2020/part-1">click
here</a>.</p>
<p><a href="https://rogueliketutorials.com/tutorials/tcod/v2/part-2">Click here to move on to the next part of this
tutorial.</a></p>
</article>
</section>
</div>
<footer class="footer">
<section class="container">
©
2023
·
Powered by <a href="https://gohugo.io/">Hugo</a> &amp; <a href="https://github.com/luizdepra/hugo-coder/">Coder</a>.
</section>
</footer>
</main>
<script src="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.236049395dc3682fb2719640872958e12f1f24067bb09c327b2.js" integrity="sha256-I2BJOV3DaC+ycZZAhylY4S8fJAZ7sJwyeyM+YpDH7aw="></script>
<script src="Part%201%20-%20Drawing%20the%20'@'%20symbol%20and%20moving%20it%20around%20%C2%B7%20Roguelike%20Tutorials_files/codetabs.min.cc52451e7f25e50f64c1c893826f606d58410d742c214dce.js" integrity="sha256-zFJFHn8l5Q9kwciTgm9gbVhBDXQsIU3OI/tEfJlh8rA="></script>
</body></html>

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1,292 @@
<!DOCTYPE html>
<html lang="en" style="color-scheme: dark;"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Extra - A more "Traditional" Look · Roguelike Tutorials
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="description" content="Prerequisites: Completion of part 4
The tutorial itself goes in a much different visual direction than most roguelikes. If you like this look, great! If you want to make your game look a bit more like other roguelikes you might be more familiar with, this section is for you.
Most roguelikes define the floor tiles as a period (.) and the wall tiles as a pound sign (#). This is simple enough to implement, by adjusting our tile types like this:">
<meta name="keywords" content="">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Extra - A more &quot;Traditional&quot; Look">
<meta name="twitter:description" content="Prerequisites: Completion of part 4
The tutorial itself goes in a much different visual direction than most roguelikes. If you like this look, great! If you want to make your game look a bit more like other roguelikes you might be more familiar with, this section is for you.
Most roguelikes define the floor tiles as a period (.) and the wall tiles as a pound sign (#). This is simple enough to implement, by adjusting our tile types like this:">
<meta property="og:title" content="Extra - A more &quot;Traditional&quot; Look">
<meta property="og:description" content="Prerequisites: Completion of part 4
The tutorial itself goes in a much different visual direction than most roguelikes. If you like this look, great! If you want to make your game look a bit more like other roguelikes you might be more familiar with, this section is for you.
Most roguelikes define the floor tiles as a period (.) and the wall tiles as a pound sign (#). This is simple enough to implement, by adjusting our tile types like this:">
<meta property="og:type" content="article">
<meta property="og:url" content="https://rogueliketutorials.com/tutorials/tcod/v2/extras/traditional-look/"><meta property="article:section" content="tutorials">
<meta property="article:published_time" content="2020-09-18T16:39:01-07:00">
<meta property="article:modified_time" content="2020-09-18T16:39:01-07:00">
<link rel="canonical" href="https://rogueliketutorials.com/tutorials/tcod/v2/extras/traditional-look/">
<link rel="preload" href="https://rogueliketutorials.com/fonts/forkawesome-webfont.woff2?v=1.2.0" as="font" type="font/woff2" crossorigin="">
<link rel="stylesheet" href="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.c4d7e93a158eda5a65b3df343745d2092a0a1e2170feeec909.css" integrity="sha256-xNfpOhWO2lpls980N0XSCSoKHiFw/u7JCbiolEOQPGo=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/coder-dark.min.78b5fe3864945faf5207fb8fe3ab2320d49c3365def0e.css" integrity="sha256-eLX+OGSUX69SB/uP46sjINScM2Xe8OiKwd8N2txUoDw=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/style.min.9d3eb202952dddb888856ff12c83bc88de866c596286bfb4c1.css" integrity="sha256-nT6yApUt3biIhW/xLIO8iN6GbFlihr+0wfjmvq2a42Y=" crossorigin="anonymous" media="screen">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-16x16.png" sizes="16x16">
<link rel="apple-touch-icon" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="manifest" href="https://rogueliketutorials.com/site.webmanifest">
<link rel="mask-icon" href="https://rogueliketutorials.com/images/safari-pinned-tab.svg" color="#5bbad5">
<meta name="generator" content="Hugo 0.110.0">
<style>:is([id*='google_ads_iframe'],[id*='taboola-'],.taboolaHeight,.taboola-placeholder,#top-ad,#credential_picker_container,#credentials-picker-container,#credential_picker_iframe,[id*='google-one-tap-iframe'],#google-one-tap-popup-container,.google-one-tap__module,.google-one-tap-modal-div,#amp_floatingAdDiv,#ez-content-blocker-container) {display:none!important;min-height:0!important;height:0!important;}</style></head>
<body class="colorscheme-dark vsc-initialized">
<div class="float-container">
<a id="dark-mode-toggle" class="colorscheme-toggle">
<i class="fa fa-adjust fa-fw" aria-hidden="true"></i>
</a>
</div>
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="https://rogueliketutorials.com/">
Roguelike Tutorials
</a>
<input type="checkbox" id="menu-toggle">
<label class="menu-button float-right" for="menu-toggle">
<i class="fa fa-bars fa-fw" aria-hidden="true"></i>
</label>
<ul class="navigation-list">
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/">Home</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/">TCOD Tutorial (2020)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/2019/">TCOD Tutorial (2019)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/about/">About</a>
</li>
</ul>
</section>
</nav>
<div class="content">
<section class="container page">
<article>
<header>
<h1 class="title">
<a class="title-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/extras/traditional-look/">
Extra - A more "Traditional" Look
</a>
</h1>
</header>
<p><em>Prerequisites: Completion of <a href="https://rogueliketutorials.com/tutorials/tcod/v2/part-4/">part 4</a></em></p>
<p>The tutorial itself goes in a much different visual direction than
most roguelikes. If you like this look, great! If you want to make your
game look a bit more like other roguelikes you might be more familiar
with, this section is for you.</p>
<p>Most roguelikes define the floor tiles as a period (<code>.</code>) and the wall tiles as a pound sign (<code>#</code>). This is simple enough to implement, by adjusting our tile types like this:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>floor = new_tile(
</span></span><span style="display:flex;"><span> walkable=True,
</span></span><span style="display:flex;"><span> transparent=True,
</span></span><span style="display:flex;"><span><span style="color:#f92672">- dark=(ord(" "), (255, 255, 255), (50, 50, 150)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672">- light=(ord(" "), (255, 255, 255), (200, 180, 50)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ dark=(ord("."), (100, 100, 100), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light=(ord("."), (200, 200, 200), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>)
</span></span><span style="display:flex;"><span>wall = new_tile(
</span></span><span style="display:flex;"><span> walkable=False,
</span></span><span style="display:flex;"><span> transparent=False,
</span></span><span style="display:flex;"><span><span style="color:#f92672">- dark=(ord(" "), (255, 255, 255), (0, 0, 100)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672">- light=(ord(" "), (255, 255, 255), (130, 110, 50)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ dark=(ord("#"), (100, 100, 100), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light=(ord("#"), (200, 200, 200), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>)
</span></span><span style="display:flex;"><span>down_stairs = new_tile(
</span></span><span style="display:flex;"><span> walkable=True,
</span></span><span style="display:flex;"><span> transparent=True,
</span></span><span style="display:flex;"><span><span style="color:#f92672">- dark=(ord("&gt;"), (0, 0, 100), (50, 50, 150)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672">- light=(ord("&gt;"), (255, 255, 255), (200, 180, 50)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ dark=(ord("&gt;"), (100, 100, 100), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light=(ord("&gt;"), (200, 200, 200), (0, 0, 0)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>)
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>floor = new_tile(
walkable=True,
transparent=True,
<span class="crossed-out-text">dark=(ord(" "), (255, 255, 255), (50, 50, 150)),</span>
<span class="crossed-out-text">light=(ord(" "), (255, 255, 255), (200, 180, 50)),</span>
<span class="new-text">dark=(ord("."), (100, 100, 100), (0, 0, 0)),</span>
<span class="new-text">light=(ord("."), (200, 200, 200), (0, 0, 0)),</span>
)
wall = new_tile(
walkable=False,
transparent=False,
<span class="crossed-out-text">dark=(ord(" "), (255, 255, 255), (0, 0, 100)),</span>
<span class="crossed-out-text">light=(ord(" "), (255, 255, 255), (130, 110, 50)),</span>
<span class="new-text">dark=(ord("#"), (100, 100, 100), (0, 0, 0)),</span>
<span class="new-text">light=(ord("#"), (200, 200, 200), (0, 0, 0)),</span>
)
down_stairs = new_tile(
walkable=True,
transparent=True,
<span class="crossed-out-text">dark=(ord("&gt;"), (0, 0, 100), (50, 50, 150)),</span>
<span class="crossed-out-text">light=(ord("&gt;"), (255, 255, 255), (200, 180, 50)),</span>
<span class="new-text">dark=(ord("&gt;"), (100, 100, 100), (0, 0, 0)),</span>
<span class="new-text">light=(ord("&gt;"), (200, 200, 200), (0, 0, 0)),</span>
)</pre>
</div>
</div>
<p><em>Note: If you havent completed <a href="https://rogueliketutorials.com/tutorials/tcod/v2/part-11/">part 11</a> yet, just ignore the <code>down_stairs</code> tile type.</em></p>
<p>The tile types are now represented by <code>.</code> and <code>#</code>, and the colors are a lighter gray if the tile is in the field of view, and a darker gray if its outside of it.</p>
<p>After these changes, the game will look like this:</p>
<p><img src="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/traditional-look.png" alt="Traditional Look"></p>
<p><em>Note: Screenshot taken from a version of the game after part 13</em></p>
<p>You should experiment with different looks for your game, based on
what you think is visually appealing. Adjust colors, change symbols, and
modify the UI to your hearts content!</p>
</article>
</section>
</div>
<footer class="footer">
<section class="container">
©
2023
·
Powered by <a href="https://gohugo.io/">Hugo</a> &amp; <a href="https://github.com/luizdepra/hugo-coder/">Coder</a>.
</section>
</footer>
</main>
<script src="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.236049395dc3682fb2719640872958e12f1f24067bb09c327b2.js" integrity="sha256-I2BJOV3DaC+ycZZAhylY4S8fJAZ7sJwyeyM+YpDH7aw="></script>
<script src="Part%2014%20-%20Extra%20-%20A%20more%20_Traditional_%20Look%20%C2%B7%20Roguelike%20Tutorials_files/codetabs.min.cc52451e7f25e50f64c1c893826f606d58410d742c214dce.js" integrity="sha256-zFJFHn8l5Q9kwciTgm9gbVhBDXQsIU3OI/tEfJlh8rA="></script>
</body></html>

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1,627 @@
<!DOCTYPE html>
<html lang="en" style="color-scheme: dark;"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Part 4 - Field of View · Roguelike Tutorials
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="description" content="We have a dungeon now, and we can move about it freely. But are we really exploring the dungeon if we can just see it all from the beginning?
Most roguelikes (not all!) only let you see within a certain range of your character, and ours will be no different. We need to implement a way to calculate the “Field of View” for our adventurer, and fortunately, tcod makes that easy!">
<meta name="keywords" content="">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Part 4 - Field of View">
<meta name="twitter:description" content="We have a dungeon now, and we can move about it freely. But are we really exploring the dungeon if we can just see it all from the beginning?
Most roguelikes (not all!) only let you see within a certain range of your character, and ours will be no different. We need to implement a way to calculate the “Field of View” for our adventurer, and fortunately, tcod makes that easy!">
<meta property="og:title" content="Part 4 - Field of View">
<meta property="og:description" content="We have a dungeon now, and we can move about it freely. But are we really exploring the dungeon if we can just see it all from the beginning?
Most roguelikes (not all!) only let you see within a certain range of your character, and ours will be no different. We need to implement a way to calculate the “Field of View” for our adventurer, and fortunately, tcod makes that easy!">
<meta property="og:type" content="article">
<meta property="og:url" content="https://rogueliketutorials.com/tutorials/tcod/v2/part-4/"><meta property="article:section" content="tutorials">
<meta property="article:published_time" content="2020-06-29T00:00:00+00:00">
<meta property="article:modified_time" content="2020-06-29T00:00:00+00:00">
<link rel="canonical" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-4/">
<link rel="preload" href="https://rogueliketutorials.com/fonts/forkawesome-webfont.woff2?v=1.2.0" as="font" type="font/woff2" crossorigin="">
<link rel="stylesheet" href="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.c4d7e93a158eda5a65b3df343745d2092a0a1e2170feeec909.css" integrity="sha256-xNfpOhWO2lpls980N0XSCSoKHiFw/u7JCbiolEOQPGo=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/coder-dark.min.78b5fe3864945faf5207fb8fe3ab2320d49c3365def0e.css" integrity="sha256-eLX+OGSUX69SB/uP46sjINScM2Xe8OiKwd8N2txUoDw=" crossorigin="anonymous" media="screen">
<link rel="stylesheet" href="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/style.min.9d3eb202952dddb888856ff12c83bc88de866c596286bfb4c1.css" integrity="sha256-nT6yApUt3biIhW/xLIO8iN6GbFlihr+0wfjmvq2a42Y=" crossorigin="anonymous" media="screen">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="https://rogueliketutorials.com/images/favicon-16x16.png" sizes="16x16">
<link rel="apple-touch-icon" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://rogueliketutorials.com/images/apple-touch-icon.png">
<link rel="manifest" href="https://rogueliketutorials.com/site.webmanifest">
<link rel="mask-icon" href="https://rogueliketutorials.com/images/safari-pinned-tab.svg" color="#5bbad5">
<meta name="generator" content="Hugo 0.110.0">
<style>:is([id*='google_ads_iframe'],[id*='taboola-'],.taboolaHeight,.taboola-placeholder,#top-ad,#credential_picker_container,#credentials-picker-container,#credential_picker_iframe,[id*='google-one-tap-iframe'],#google-one-tap-popup-container,.google-one-tap__module,.google-one-tap-modal-div,#amp_floatingAdDiv,#ez-content-blocker-container) {display:none!important;min-height:0!important;height:0!important;}</style></head>
<body class="colorscheme-dark vsc-initialized">
<div class="float-container">
<a id="dark-mode-toggle" class="colorscheme-toggle">
<i class="fa fa-adjust fa-fw" aria-hidden="true"></i>
</a>
</div>
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="https://rogueliketutorials.com/">
Roguelike Tutorials
</a>
<input type="checkbox" id="menu-toggle">
<label class="menu-button float-right" for="menu-toggle">
<i class="fa fa-bars fa-fw" aria-hidden="true"></i>
</label>
<ul class="navigation-list">
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/">Home</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/">TCOD Tutorial (2020)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/tutorials/tcod/2019/">TCOD Tutorial (2019)</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="https://rogueliketutorials.com/about/">About</a>
</li>
</ul>
</section>
</nav>
<div class="content">
<section class="container page">
<article>
<header>
<h1 class="title">
<a class="title-link" href="https://rogueliketutorials.com/tutorials/tcod/v2/part-4/">
Part 4 - Field of View
</a>
</h1>
</header>
<p>We have a dungeon now, and we can move about it freely. But are we
really <em>exploring</em> the dungeon if we can just see it all from the
beginning?</p>
<p>Most roguelikes (not all!) only let you see within a certain range of
your character, and ours will be no different. We need to implement a way
to calculate the “Field of View” for our adventurer, and fortunately,
tcod makes that easy!</p>
<p>When walking around the dungeon, there will essentially be three “states” a tile can be in, relating to our field of view.</p>
<ol>
<li>Visible</li>
<li>Not visible</li>
<li>Not visible, but previously seen</li>
</ol>
<p>What this means is that we should draw the “visible” tiles as well as
the “not visible, but previously seen” ones to the screen, but
differentiate them somehow. The “not visible” tiles can simply be drawn
as an empty tile, with the color black, gray, or whatever you want to
use.</p>
<p>In order to differentiate between these tiles, well need two new
Numpy arrays: One to keep track of the tiles that are currently visible,
and another to keep track of all the tiles that our character has seen
before. Add the two arrays to <code>GameMap</code> like this:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>class GameMap:
</span></span><span style="display:flex;"><span> def __init__(self, width: int, height: int):
</span></span><span style="display:flex;"><span> self.width, self.height = width, height
</span></span><span style="display:flex;"><span> self.tiles = np.full((width, height), fill_value=tile_types.wall, order="F")
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.visible = np.full((width, height), fill_value=False, order="F") # Tiles the player can currently see
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.explored = np.full((width, height), fill_value=False, order="F") # Tiles the player has seen before
</span></span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>class GameMap:
def __init__(self, width: int, height: int):
self.width, self.height = width, height
self.tiles = np.full((width, height), fill_value=tile_types.wall, order="F")
<span class="new-text">self.visible = np.full((width, height), fill_value=False, order="F") # Tiles the player can currently see
self.explored = np.full((width, height), fill_value=False, order="F") # Tiles the player has seen before</span></pre>
</div>
</div>
<p>We create two arrays, <code>visible</code> and <code>explored</code>, and fill them with the value <code>False</code>. In a moment, well create a function that will update these arrays based on whats in the field of view.</p>
<p>Lets turn our attention back to the tile types. Remember when we
specified the “walkable”, “transparent”, and “dark” attributes? We
called it “dark” because its what the tile will look like when its not
in the field of view, but what about when it <em>is</em>?</p>
<p>For that, well want a new <code>graphic_dt</code> in the <code>tile_dt</code> type, called <code>light</code>. We can add that by modifying <code>tile_types.py</code> like this:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>tile_dt = np.dtype(
</span></span><span style="display:flex;"><span> [
</span></span><span style="display:flex;"><span> ("walkable", np.bool), # True if this tile can be walked over.
</span></span><span style="display:flex;"><span> ("transparent", np.bool), # True if this tile doesn't block FOV.
</span></span><span style="display:flex;"><span> ("dark", graphic_dt), # Graphics for when this tile is not in FOV.
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ ("light", graphic_dt), # Graphics for when the tile is in FOV.
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span> ]
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>def new_tile(
</span></span><span style="display:flex;"><span> *, # Enforce the use of keywords, so that parameter order doesn't matter.
</span></span><span style="display:flex;"><span> walkable: int,
</span></span><span style="display:flex;"><span> transparent: int,
</span></span><span style="display:flex;"><span> dark: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>) -&gt; np.ndarray:
</span></span><span style="display:flex;"><span> """Helper function for defining individual tile types """
</span></span><span style="display:flex;"><span><span style="color:#f92672">- return np.array((walkable, transparent, dark), dtype=tile_dt)
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ return np.array((walkable, transparent, dark, light), dtype=tile_dt)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+# SHROUD represents unexplored, unseen tiles
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+SHROUD = np.array((ord(" "), (255, 255, 255), (0, 0, 0)), dtype=graphic_dt)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span>floor = new_tile(
</span></span><span style="display:flex;"><span><span style="color:#f92672">- walkable=True, transparent=True, dark=(ord(" "), (255, 255, 255), (50, 50, 150)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ walkable=True,
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ transparent=True,
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ dark=(ord(" "), (255, 255, 255), (50, 50, 150)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light=(ord(" "), (255, 255, 255), (200, 180, 50)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>)
</span></span><span style="display:flex;"><span>wall = new_tile(
</span></span><span style="display:flex;"><span><span style="color:#f92672">- walkable=False, transparent=False, dark=(ord(" "), (255, 255, 255), (0, 0, 100)),
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ walkable=False,
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ transparent=False,
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ dark=(ord(" "), (255, 255, 255), (0, 0, 100)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ light=(ord(" "), (255, 255, 255), (130, 110, 50)),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>)
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>tile_dt = np.dtype(
[
("walkable", np.bool), # True if this tile can be walked over.
("transparent", np.bool), # True if this tile doesn't block FOV.
("dark", graphic_dt), # Graphics for when this tile is not in FOV.
<span class="new-text">("light", graphic_dt), # Graphics for when the tile is in FOV.</span>
]
)
def new_tile(
*, # Enforce the use of keywords, so that parameter order doesn't matter.
walkable: int,
transparent: int,
dark: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
<span class="new-text">light: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],</span>
) -&gt; np.ndarray:
"""Helper function for defining individual tile types """
<span class="crossed-out-text">return np.array((walkable, transparent, dark), dtype=tile_dt)</span>
<span class="new-text">return np.array((walkable, transparent, dark, light), dtype=tile_dt)</span>
<span class="new-text"># SHROUD represents unexplored, unseen tiles
SHROUD = np.array((ord(" "), (255, 255, 255), (0, 0, 0)), dtype=graphic_dt)</span>
floor = new_tile(
<span class="crossed-out-text">walkable=True, transparent=True, dark=(ord(" "), (255, 255, 255), (50, 50, 150)),</span>
<span class="new-text">walkable=True,
transparent=True,
dark=(ord(" "), (255, 255, 255), (50, 50, 150)),
light=(ord(" "), (255, 255, 255), (200, 180, 50)),</span>
)
wall = new_tile(
<span class="crossed-out-text">walkable=False, transparent=False, dark=(ord(" "), (255, 255, 255), (0, 0, 100)),</span>
<span class="new-text">walkable=False,
transparent=False,
dark=(ord(" "), (255, 255, 255), (0, 0, 100)),
light=(ord(" "), (255, 255, 255), (130, 110, 50)),</span>
)</pre>
</div>
</div>
<p>Lets go through the new additions.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span>tile_dt <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>dtype(
</span></span><span style="display:flex;"><span> [
</span></span><span style="display:flex;"><span> (<span style="color:#e6db74">"walkable"</span>, np<span style="color:#f92672">.</span>bool), <span style="color:#75715e"># True if this tile can be walked over.</span>
</span></span><span style="display:flex;"><span> (<span style="color:#e6db74">"transparent"</span>, np<span style="color:#f92672">.</span>bool), <span style="color:#75715e"># True if this tile doesn't block FOV.</span>
</span></span><span style="display:flex;"><span> (<span style="color:#e6db74">"dark"</span>, graphic_dt), <span style="color:#75715e"># Graphics for when this tile is not in FOV.</span>
</span></span><span style="display:flex;"><span> (<span style="color:#e6db74">"light"</span>, graphic_dt), <span style="color:#75715e"># Graphics for when the tile is in FOV.</span>
</span></span><span style="display:flex;"><span> ]
</span></span><span style="display:flex;"><span>)
</span></span></code></pre></div><p>Were adding a new <code>graphic_dt</code> to the <code>tile_dt</code> that we use to define our tiles. <code>light</code> will hold the information about what our tile looks like when its in the field of view.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">new_tile</span>(
</span></span><span style="display:flex;"><span> <span style="color:#f92672">*</span>, <span style="color:#75715e"># Enforce the use of keywords, so that parameter order doesn't matter.</span>
</span></span><span style="display:flex;"><span> walkable: int,
</span></span><span style="display:flex;"><span> transparent: int,
</span></span><span style="display:flex;"><span> dark: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
</span></span><span style="display:flex;"><span> light: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]],
</span></span><span style="display:flex;"><span>) <span style="color:#f92672">-&gt;</span> np<span style="color:#f92672">.</span>ndarray:
</span></span><span style="display:flex;"><span> <span style="color:#e6db74">"""Helper function for defining individual tile types """</span>
</span></span><span style="display:flex;"><span> <span style="color:#66d9ef">return</span> np<span style="color:#f92672">.</span>array((walkable, transparent, dark, light), dtype<span style="color:#f92672">=</span>tile_dt)
</span></span></code></pre></div><p>Weve modified the <code>new_tile</code> function to account for the new <code>light</code> attribute. <code>light</code> works the same as <code>dark</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span><span style="color:#75715e"># SHROUD represents unexplored, unseen tiles</span>
</span></span><span style="display:flex;"><span>SHROUD <span style="color:#f92672">=</span> np<span style="color:#f92672">.</span>array((ord(<span style="color:#e6db74">" "</span>), (<span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>), (<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">0</span>)), dtype<span style="color:#f92672">=</span>graphic_dt)
</span></span></code></pre></div><p><code>SHROUD</code> is what well use for when a tile is neither in view nor has been “explored”. Its set to just draw a black tile.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span>floor <span style="color:#f92672">=</span> new_tile(
</span></span><span style="display:flex;"><span> walkable<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>,
</span></span><span style="display:flex;"><span> transparent<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>,
</span></span><span style="display:flex;"><span> dark<span style="color:#f92672">=</span>(ord(<span style="color:#e6db74">" "</span>), (<span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>), (<span style="color:#ae81ff">50</span>, <span style="color:#ae81ff">50</span>, <span style="color:#ae81ff">150</span>)),
</span></span><span style="display:flex;"><span> light<span style="color:#f92672">=</span>(ord(<span style="color:#e6db74">" "</span>), (<span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>), (<span style="color:#ae81ff">200</span>, <span style="color:#ae81ff">180</span>, <span style="color:#ae81ff">50</span>)),
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>wall <span style="color:#f92672">=</span> new_tile(
</span></span><span style="display:flex;"><span> walkable<span style="color:#f92672">=</span><span style="color:#66d9ef">False</span>,
</span></span><span style="display:flex;"><span> transparent<span style="color:#f92672">=</span><span style="color:#66d9ef">False</span>,
</span></span><span style="display:flex;"><span> dark<span style="color:#f92672">=</span>(ord(<span style="color:#e6db74">" "</span>), (<span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>), (<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">100</span>)),
</span></span><span style="display:flex;"><span> light<span style="color:#f92672">=</span>(ord(<span style="color:#e6db74">" "</span>), (<span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>, <span style="color:#ae81ff">255</span>), (<span style="color:#ae81ff">130</span>, <span style="color:#ae81ff">110</span>, <span style="color:#ae81ff">50</span>)),
</span></span><span style="display:flex;"><span>)
</span></span></code></pre></div><p>Finally, we add <code>light</code> to both the <code>floor</code> and <code>wall</code>
tiles. We also modify the functions to fit a bit better on the screen,
adding new lines after each argument. This is just for the sake of
readability.</p>
<p><code>light</code> in both cases is set to a brighter color, so that
when we draw the field of view to the screen, the player can easily
differentiate between whats in view and whats not. As usual, feel free
to play with the color schemes to match whatever you might have in
mind.</p>
<p>With all that in place, we need to modify the way <code>GameMap</code> draws itself to the screen.</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>class GameMap:
</span></span><span style="display:flex;"><span> ...
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> def render(self, console: Console) -&gt; None:
</span></span><span style="display:flex;"><span><span style="color:#f92672">- console.tiles_rgb[0:self.width, 0:self.height] = self.tiles["dark"]
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ """
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ Renders the map.
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ If a tile is in the "visible" array, then draw it with the "light" colors.
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ If it isn't, but it's in the "explored" array, then draw it with the "dark" colors.
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ Otherwise, the default is "SHROUD".
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ """
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ console.tiles_rgb[0:self.width, 0:self.height] = np.select(
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ condlist=[self.visible, self.explored],
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ choicelist=[self.tiles["light"], self.tiles["dark"]],
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ default=tile_types.SHROUD
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ )
</span></span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>class GameMap:
...
def render(self, console: Console) -&gt; None:
<span class="crossed-out-text">console.tiles_rgb[0:self.width, 0:self.height] = self.tiles["dark"]</span>
<span class="new-text">"""
Renders the map.
If a tile is in the "visible" array, then draw it with the "light" colors.
If it isn't, but it's in the "explored" array, then draw it with the "dark" colors.
Otherwise, the default is "SHROUD".
"""
console.tiles_rgb[0:self.width, 0:self.height] = np.select(
condlist=[self.visible, self.explored],
choicelist=[self.tiles["light"], self.tiles["dark"]],
default=tile_types.SHROUD
)</span></pre>
</div>
</div>
<p>The first part of the statement, <code>console.tiles_rgb[0:self.width, 0:self.height]</code>, hasnt changed. But instead of just setting it to <code>self.tiles["dark"]</code>, were using <code>np.select</code>.</p>
<p><code>np.select</code> allows us to conditionally draw the tiles we want, based on whats specified in <code>condlist</code>. Since were passing <code>[self.visible, self.explored]</code>, it will check if the tile being drawn is either visible, then explored. If its visible, it uses the first value in <code>choicelist</code>, in this case, <code>self.tiles["light"]</code>. If its not visible, but explored, then we draw <code>self.tiles["dark"]</code>. If neither is true, we use the <code>default</code> argument, which is just the <code>SHROUD</code> we defined earlier.</p>
<p>If you run the project now, none of the tiles will be drawn to the screen. This is because we need a way to actually modify the <code>visible</code> and <code>explored</code> tiles. Lets modify <code>Engine</code> to do just that:</p>
<div>
<button class="btn btn-primary data-toggle-tab active" data-toggle-tab="diff">
Diff
</button>
<button class="btn btn-secondary data-toggle-tab" data-toggle-tab="original">
Original
</button>
<div class="data-pane active" data-pane="diff">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-diff" data-lang="diff"><span style="display:flex;"><span>...
</span></span><span style="display:flex;"><span>from tcod.context import Context
</span></span><span style="display:flex;"><span>from tcod.console import Console
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+from tcod.map import compute_fov
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span>from entity import Entity
</span></span><span style="display:flex;"><span>...
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>class Engine:
</span></span><span style="display:flex;"><span> def __init__(self, entities: Set[Entity], event_handler: EventHandler, game_map: GameMap, player: Entity):
</span></span><span style="display:flex;"><span> self.entities = entities
</span></span><span style="display:flex;"><span> self.event_handler = event_handler
</span></span><span style="display:flex;"><span> self.game_map = game_map
</span></span><span style="display:flex;"><span> self.player = player
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.update_fov()
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> def handle_events(self, events: Iterable[Any]) -&gt; None:
</span></span><span style="display:flex;"><span> for event in events:
</span></span><span style="display:flex;"><span> action = self.event_handler.dispatch(event)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> if action is None:
</span></span><span style="display:flex;"><span> continue
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> action.perform(self, self.player)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.update_fov() # Update the FOV before the players next action.
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ def update_fov(self) -&gt; None:
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ """Recompute the visible area based on the players point of view."""
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.game_map.visible[:] = compute_fov(
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.game_map.tiles["transparent"],
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ (self.player.x, self.player.y),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ radius=8,
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ )
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ # If a tile is "visible" it should be added to "explored".
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ self.game_map.explored |= self.game_map.visible
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> def render(self, console: Console, context: Context) -&gt; None:
</span></span><span style="display:flex;"><span> self.game_map.render(console)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> for entity in self.entities:
</span></span><span style="display:flex;"><span><span style="color:#f92672">- console.print(entity.x, entity.y, entity.char, fg=entity.color)
</span></span></span><span style="display:flex;"><span><span style="color:#f92672"></span><span style="color:#a6e22e">+ # Only print entities that are in the FOV
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ if self.game_map.visible[entity.x, entity.y]:
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">+ console.print(entity.x, entity.y, entity.char, fg=entity.color)
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e"></span>
</span></span><span style="display:flex;"><span> context.present(console)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span> console.clear()
</span></span></code></pre></div>
</div>
<div class="data-pane" data-pane="original">
<pre>...
from tcod.context import Context
from tcod.console import Console
<span class="new-text">from tcod.map import compute_fov</span>
from entity import Entity
...
class Engine:
def __init__(self, entities: Set[Entity], event_handler: EventHandler, game_map: GameMap, player: Entity):
self.entities = entities
self.event_handler = event_handler
self.game_map = game_map
self.player = player
<span class="new-text">self.update_fov()</span>
def handle_events(self, events: Iterable[Any]) -&gt; None:
for event in events:
action = self.event_handler.dispatch(event)
if action is None:
continue
action.perform(self, self.player)
<span class="new-text">self.update_fov() # Update the FOV before the players next action.</span>
<span class="new-text">def update_fov(self) -&gt; None:
"""Recompute the visible area based on the players point of view."""
self.game_map.visible[:] = compute_fov(
self.game_map.tiles["transparent"],
(self.player.x, self.player.y),
radius=8,
)
# If a tile is "visible" it should be added to "explored".
self.game_map.explored |= self.game_map.visible</span>
def render(self, console: Console, context: Context) -&gt; None:
self.game_map.render(console)
for entity in self.entities:
<span class="crossed-out-text">console.print(entity.x, entity.y, entity.char, fg=entity.color)</span>
<span class="new-text"># Only print entities that are in the FOV
if self.game_map.visible[entity.x, entity.y]:
console.print(entity.x, entity.y, entity.char, fg=entity.color)</span>
context.present(console)
console.clear()</pre>
</div>
</div>
<p>The most important part of our additions is the <code>update_fov</code> function.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-py3" data-lang="py3"><span style="display:flex;"><span> <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">update_fov</span>(self) <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">None</span>:
</span></span><span style="display:flex;"><span> <span style="color:#e6db74">"""Recompute the visible area based on the players point of view."""</span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>game_map<span style="color:#f92672">.</span>visible[:] <span style="color:#f92672">=</span> compute_fov(
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>game_map<span style="color:#f92672">.</span>tiles[<span style="color:#e6db74">"transparent"</span>],
</span></span><span style="display:flex;"><span> (self<span style="color:#f92672">.</span>player<span style="color:#f92672">.</span>x, self<span style="color:#f92672">.</span>player<span style="color:#f92672">.</span>y),
</span></span><span style="display:flex;"><span> radius<span style="color:#f92672">=</span><span style="color:#ae81ff">8</span>,
</span></span><span style="display:flex;"><span> )
</span></span><span style="display:flex;"><span> <span style="color:#75715e"># If a tile is "visible" it should be added to "explored".</span>
</span></span><span style="display:flex;"><span> self<span style="color:#f92672">.</span>game_map<span style="color:#f92672">.</span>explored <span style="color:#f92672">|=</span> self<span style="color:#f92672">.</span>game_map<span style="color:#f92672">.</span>visible
</span></span></code></pre></div><p>Were setting the <code>game_map</code>s <code>visible</code> tiles to equal the result of the <code>compute_fov</code>. Were giving <code>compute_fov</code> three arguments, which it uses to compute our field of view.</p>
<ul>
<li><code>transparency</code>: This is the first argument, which were passing <code>self.game_map.tiles["transparent"]</code>. <code>transparency</code>
takes a 2D numpy array, and considers any non-zero values to be
transparent. This is the array it uses to calculate the field of view.</li>
<li><code>pov</code>: The origin point for the field of view, which is a 2D index. We use the players x and y position here.</li>
<li><code>radius</code>: How far the FOV extends.</li>
</ul>
<p>Theres more that this function can do, including not lighting up
walls, and using different algorithms to calculate the FOV. If youre
interested, you can find the documentation <a href="https://python-tcod.readthedocs.io/en/latest/tcod/map.html#tcod.map.compute_fov">here</a>.</p>
<p>The line <code>self.game_map.explored |= self.game_map.visible</code> sets the <code>explored</code> array to include everything in the <code>visible</code> array, plus whatever it already had. This means that any tile the player can see, the player has also “explored.”</p>
<p>Thats all we need to do to update our field of view. Notice that we call the function when we initialize the <code>Engine</code>
class, so that the field of view is created before the player can move,
and after handling an action, so that whenever the player does move,
the field of view will be updated.</p>
<p>Lastly, we modify the part that draws the entities, so that only entities in the field of view are drawn.</p>
<p>Run the project now, and youll see something like this:</p>
<p><img src="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/part-4-fov.png" alt="Part 4 - FOV" title="Field of View"></p>
<p>Its hard to believe, but thats all we need to do for a functioning field of view!</p>
<p>This chapter was a shorter one, but weve accomplished quite a lot.
Our dungeon feels a lot more mysterious, and in coming chapters, it will
get a lot more dangerous.</p>
<p>If you want to see the code so far in its entirety, <a href="https://github.com/TStand90/tcod_tutorial_v2/tree/2020/part-4">click
here</a>.</p>
<p><a href="https://rogueliketutorials.com/tutorials/tcod/v2/part-5">Click here to move on to the next part of this
tutorial.</a></p>
</article>
</section>
</div>
<footer class="footer">
<section class="container">
©
2023
·
Powered by <a href="https://gohugo.io/">Hugo</a> &amp; <a href="https://github.com/luizdepra/hugo-coder/">Coder</a>.
</section>
</footer>
</main>
<script src="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/coder.min.236049395dc3682fb2719640872958e12f1f24067bb09c327b2.js" integrity="sha256-I2BJOV3DaC+ycZZAhylY4S8fJAZ7sJwyeyM+YpDH7aw="></script>
<script src="Part%204%20-%20Field%20of%20View%20%C2%B7%20Roguelike%20Tutorials_files/codetabs.min.cc52451e7f25e50f64c1c893826f606d58410d742c214dce.js" integrity="sha256-zFJFHn8l5Q9kwciTgm9gbVhBDXQsIU3OI/tEfJlh8rA="></script>
</body></html>

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

View file

@ -0,0 +1 @@
pre{border:1px solid #000;padding:15px;background-color:#272822;color:#f8f8f2;background-color:#272822}.language-diff,.language-py3{background-color:#272822!important}body.colorscheme-dart code{background-color:#272822!important}.crossed-out-text{color:#f92672;text-decoration:line-through}.new-text{color:#a6e22e}.data-pane{display:none}.data-pane.active{display:inline}

View file

@ -0,0 +1 @@
const body=document.body,darkModeToggle=document.getElementById("dark-mode-toggle"),darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");localStorage.getItem("colorscheme")?setTheme(localStorage.getItem("colorscheme")):setTheme(body.classList.contains("colorscheme-light")||body.classList.contains("colorscheme-dark")?body.classList.contains("colorscheme-dark")?"dark":"light":darkModeMediaQuery.matches?"dark":"light"),darkModeToggle&&darkModeToggle.addEventListener("click",()=>{let e=body.classList.contains("colorscheme-dark")?"light":"dark";setTheme(e),rememberTheme(e)}),darkModeMediaQuery.addListener(e=>{setTheme(e.matches?"dark":"light")}),document.addEventListener("DOMContentLoaded",function(){let e=document.querySelector(".preload-transitions");e.classList.remove("preload-transitions")});function setTheme(e){body.classList.remove("colorscheme-auto");let n=e==="dark"?"light":"dark";body.classList.remove("colorscheme-"+n),body.classList.add("colorscheme-"+e),document.documentElement.style["color-scheme"]=e;function t(e){return new Promise(t=>{if(document.querySelector(e))return t(document.querySelector(e));const n=new MutationObserver(s=>{document.querySelector(e)&&(t(document.querySelector(e)),n.disconnect())});n.observe(document.body,{childList:!0,subtree:!0})})}if(e==="dark"){const e={type:"set-theme",theme:"github-dark"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}else{const e={type:"set-theme",theme:"github-light"};t(".utterances-frame").then(t=>{t.contentWindow.postMessage(e,"https://utteranc.es")})}}function rememberTheme(e){localStorage.setItem("colorscheme",e)}

View file

@ -0,0 +1 @@
var allTabs=document.querySelectorAll("[data-toggle-tab]"),allPanes=document.querySelectorAll("[data-pane]");function toggleTabs(e){if(e.target){e.preventDefault();var n,s,o=e.currentTarget,t=o.getAttribute("data-toggle-tab")}else t=e;window.localStorage&&window.localStorage.setItem("configLangPref",t),n=document.querySelectorAll("[data-toggle-tab='"+t+"']"),s=document.querySelectorAll("[data-pane='"+t+"']");for(let e=0;e<allTabs.length;e++)allTabs[e].classList.remove("active"),allPanes[e].classList.remove("active");for(let e=0;e<n.length;e++)n[e].classList.add("active"),s[e].classList.add("active")}for(let e=0;e<allTabs.length;e++)allTabs[e].addEventListener("click",toggleTabs);window.localStorage.getItem("configLangPref")&&toggleTabs(window.localStorage.getItem("configLangPref"))

Some files were not shown because too many files have changed in this diff Show more