Complete Roguelike Tutorial, using Python3+libtcod, extras
This is part of a series of tutorials; the main page can be found here.
A neat Python shortcut for Notepad++
Although Notepad++ is light and has many nice features, it can be tricky to set up a shortcut to quickly run your game and see any errors or debug output. After reading the docs on Run commands, you might try to open a console (cmd) that doesn't close after the program runs so you can see debug output (/k), and using the path to the currently open file:
cmd /k "$(FULL_CURRENT_PATH)"
You then may puzzle over the following error (or similar), which doesn't seem connected to Notepad++ at all:
WindowsError: [Error 126] The specified module could not be found
The problem is this: Notepad++ and Python are smart enough to run the file, but not smart enough to initialize the "current directory" to the file's directory. So when trying to load libtcod, Python looks for it in all the usual places except where you put libtcod. (Computers can be so thick sometimes!) The fix is to previously "change directory" there, which can be done with a batch file.
Here's my setup. I want to launch the file in a console, so I can see any debug output, and I wanna keep it around in case of errors (to see the traceback) but close it automatically if the program runs fine -- accumulating lots of console windows when there are no errors is annoying. (To explicitly "pause" the console even when there are no errors call the built-in function raw_input from your program.) I simply created a windows batch file debug_py.bat with this:
@echo off cd %1 %2 if not errorlevel 1 goto quit echo. echo. pause :quit
Assuming parameter %1 is the file's directory, and %2 is the file name, this just changes to that dir and runs it, pausing the console if there's an error. The notepad++ shortcut that executes it with the correct parameters is this:
"C:\whatever\debug_py.bat" "$(CURRENT_DIRECTORY)" $(FILE_NAME)
Just change "C:\whatever\debug_py.bat" to the full path of the bat file you created. To create that shortcut in Notepad++ go to menu Run->Run..., paste that line into the textbox, then choose Save. No more problems, and the console closes automatically if there are no errors.
Old-school wall and floor tiles
Not a big fan of the new-school look of the map tiles in the tutorial? Perhaps you want your game to look more like one of the Major Roguelikes, with ' . ' characters for floor and ' # ' for wall tiles. No problem, just a couple of tweaks.
First, the most obvious one: in the render_all() function, replace the console_set_back calls, which only change the background color of a tile, with console_put_char_ex, which changes everything (here's the relevant page of the manual.). So a line like this:
Changes to something like this:
Which will change it to a white ' # ' character on a dark blue background. This is only an example; I'm sure you'd like to choose other colors!
If you change the floor characters too, it doesn't quite behave as expected, since the player erases the floor characters it steps on. To fix this you need to change the Object 's clear method, to this:
Assuming, of course, those are the colors and character you wanted for a lit ground tile!
Ok, so you're making a real-time game. You got through the section on combat, but the system described there is more or less turn-based. Don't despair! The only thing missing is a speed system.
Each object will have a wait value, which tells the number of frames it has to wait until it can take another action (move or attack). It's decreased by 1 every frame, and when it's 0, the object can move or hit again! Doing it will increase the wait value, so it has to wait again.
We'll start by defining a few speed constants, which are the values that wait is increased to when taking certain actions.
As you can see, we're making it a bit easier on the player, so he can maneuver around the monsters fast, but both attack at the same rate. These numbers are entirely tweakable of course!
The Object 's __init__ method must accept a move speed. Just add speed=DEFAULT_SPEED as a parameter; if unspecified, the default speed is used. The initialization code stores it, and sets wait to 0:
Whenever the object moves, it has to wait. At the end of the move method:
The Fighter class stores the attack speed, so it's very similar. Its __init__ method accepts the parameter attack_speed=DEFAULT_ATTACK_SPEED, and stores it with self.attack_speed = attack_speed. At the end of the attack method, the object has to wait until it can attack or move again:
Ok, but how do we enforce these wait periods? For the player, before testing for the movement keys (in handle_keys), add the wait logic right after the if game_state == 'playing' ... line:
So the movement/attack keys aren't used if the player has to wait. Next, the same behavior for the monsters! Replace the object.ai.take_turn() line with the block:
Also, there's a condition that only lets the monsters move/attack after the player moved or attacked. This is appropriate for a turn-based game, but for real-time, it has to be removed. A few lines above the code you just modified, replace the line if game_state == 'playing' and player_action != 'didnt-take-turn': with just if game_state == 'playing':.
And don't forget to switch to the non-blocking function in handle_keys():
There it is, a speed system for a real-time game! Don't forget to add speed=PLAYER_SPEED when creating the player, or any other speeds you want to modify. I left all the others as default.
Adding basic mouse support to the menu system is really easy. If you've completed Part 9: Spells and ranged combat, then you've already seen the code needed to check the mouse position and button presses. We're going to make a tiny change to code in Part 10: Main menu and saving, so keep that in mind if you haven't gotten that far yet.
Most of our changes will be to menu(). Let's start by adding the globals "key" and "mouse" to the top, so we can use these already defined references:
At this point, also move the following two lines from play_game() to the very end of the file, just before main_menu() is called. We'll need to initialize them now, since we're going to be using them in all menu code, including the main menu.
Next, we'll get the x- and y-offsets of the menu options. These will let us calculate coordinates for the mouse relative to the menu options, instead of the screen, making it simple to tell if the mouse is inside the menu and where:
Because the main loop is paused while a menu is open, if we try to check the mouse position now, we'll only get its position the last time it was updated, at the start of the main loop. The same issue arose in the target_tile() and target_monster() functions, with the same solution. We'll enclose the rest of the menu() function in a loop of its own, so that we can continuously update the mouse and check for input. Only when the player makes a selection will we break out of it and return to the game loop.
Notice that we changed from console_wait_for_keypress to sys_check_for_event. This lets us both update the mouse and avoid pausing execution. If you play the game now, you'll see that the inventory is unusable - it immediately closes itself. That's because we haven't added any checks yet, so the function immediately returns None before the player can react. Here is the updated menu() function:
The idea is to get the latest inputs from the mouse and keyboard, then check them against the menu contents. If the mouse is left-clicked, use the x- and y-offsets we calculated earlier to determine where in the menu the user clicked. The leftmost tile of the first option (not the header!) will be (0, 0), while the rightmost tile of the last option will be (width - 1, height - 1). Because the choices are numbered top to bottom starting from 0, and can only take up one line, menu_y will always equal the index of a valid choice if it lies inside the bounds of the menu. The rest is just checking for a few different ways to cancel and allowing the player to toggle fullscreen from inside a menu.
Creating a Binary
Source is great, but let's be honest, forcing your players to recreate your development environment isn't very polite. Let's do them the courtesy of packaging it all up in a nice and tidy executable.
Py2exe is a set of tools for creating stand-alone Windows programs from python scripts. Perfect, this is exactly what we want! Download py2exe (version 0.6.9) for your installed version of Python and install it. The project homepage has a nice tutorial which can help get you started, or you can use my script I've provided below.
If you are using my script, set the target_file to the name of the script that serves as the main point of entry for your game. Then just run the script! You should see a deal of console text about byte-compiling and copying, and if all goes well there should be two new directories. The dist folder is the one we care about, so go check it out.
Inside the dist folder there should be a shiny new executable file and a few other files. In my test I had: main.exe, SDL.dll, lib-tcod.dll, and w9xpopen.exe. Don't delete these, you need them! Run the executable to verify everything works fine and you are ready to package and distribute your game!
Cx_Freeze is a set of tools for creating Linux executables.
Py2app is a set of tools for creating Mac OSX applications.
The basic tutorial contains a simple pathfinding, but there's a lot of issues: for example the monsters cannot do a diagonal movement into a corridor, and they cannot navigate around other monsters.
Libtcod contains a pathfinding module that includes a simple A* pathfinding. The following function will fix all these issues.
First we will fix the AI class BasicMonster. We'll replace the movement function move_towards(player.x, player.y) with move_astar(player) that takes the player as the parameter into which to move.
The second thing is to create this function inside the Object class. The function creates a new path each turn that takes into account other monsters or unwalkable objects (these could be pillars, wells, altars)
Using Graphical Tiles
This tutorial shows how to use graphical tiles instead of ASCII or solid color graphics.
Here's a sample font file that's used in this tutorial. Save this file as TiledFont.png. The tiles are from Angband's free 16x16 tileset with the font from roarl's nethack font:
New tiles can be added to that file with an image editor that preserves the transparency.
There are some things that MUST be taken into account when using tiles with libtcod.
1. The tile size must be related to the font size. It cannot be smaller than the font size, but it can be larger. If it's larger, it's size must be related to the font size by a multiplier. If the font size is 16x16, you can use 16x16, 16x32, 32x32 etc. sized tiles. Larger tiles must be drawn in multiple chunks of 16x16 if the font size is 16x16.
2. If the tile is shown as a solid block instead of the tile, it's determined as a greyscale tile. Each tile must have at least one pixel that's RGB values are not the same. It's easiest to change one of the pixels for example from [132, 132, 132] to [132, 132, 133] RGB values. It doesn't look any different, but libtcod interpretes it differently.
3. The font file must have empty rows at the bottom. If the tiles won't appear, add empty rows to the file.
4. Tiles are not transparent in one sense, you cannot draw one tile on top of the other so that the bottom tile will be shown too. This results in items not showing floor below them. If you've got only one floor tile, you can actually draw the items to the floor tile so it won't look weird.
First we will load the font file by modifing the font row at the bottom:
Then we must load the custom rows from the font so the tiles can be used. Be sure also to call it from somewhere at the beginning:
Then we will add variables to the tiles at where the other constants are declared at the top of the file. Here's all the tiles needed for the tutorial:
Now we modify the render_all() function to render the map with the tiles. In the "console_put_char_ex" function the first color is how the tile will be tinted. The next color will tell how the transparent parts will be colored, black is good enough now. We tint the "seen, but not in the FOV" tiles as grey, others will be untinted with white:
Then we can modify the actual objects to use the tiles. Here's the "@" changed into player_tile. Remember to also make the color white so it will be untinted:
Now you can change the other objects also to use the graphical tiles' variables and then you can enjoy the results!
BSP Dungeon Generator
This tutorial explains how to use the Binary Space Partitioning module in libtcod. It's used for generating dungeons. The advantage in here is that the dungeons generated fill the map completely with rooms, instead of placing random rectangles and digging corridors between them.
BSP simplified is that a root node is divided into two nodes and then the two resulting nodes will be divided in two and repeated for the DEPTH amount. Then each of the nodes, so called leafs, will be transformed into rooms.
This tutorial is adapted to fit the main tutorial from the samples provided by libtcod.
First, add this in the top of the file. It will be used when determining the stairs room and the starting room
Next we create some constants for use within the dungeon generator.
DEPTH determines the amount of recursive rooms.
MIN_SIZE is the smallest room size.
FULL_ROOMS when False will create random sized rooms, when True it will create rooms that will be largest possible within the node area. It is recommended to use False to create more natural looking dungeons. Using True might be good when adding this into an existing area, for example creating a house indoor areas.
The following function is the main function that can be called instead of the basic tutorial's make_map() function.
It essentially creates a dungeon using the BSP module, picks one of the rooms for stairs, and one for the player start, and then for the rest of the rooms adds enemies and items.
This function is where the BSP stuff happens
All the corridor diggings are made within these for every direction
|FULL_ROOMS = True||FULL_ROOMS = False|