Skip to content
Image with logo, providing a link to the home page
  • United Stated of America flag, representing the option for the English language.
  • Bandeira do Brasil, simbolizando a opção pelo idioma Português do Brasil.

Ideas, Rules, Simulation: Introduction: Window and Hello World

Source code and windows with drawing areas created in this topic for JavaScript with HTML Canvas, GDScript with Godot Engine, Python with PyGame, and Lua with LÖVE. The image also provides a link to this website: <www.francogarcia.com>, as well as the account francogarciacom, used for the Twitter and Instagram of the author.

Image credits: Image created by the author using the program Inkscape; icons by Font Awesome.

Requirements

The material for Ideas, Rules, Simulations promotes project based learning (interactive simulations and digital games) using multimedia resources. As such, it is complimentary to the material of Learn Programming, which introduces fundamentals and basic programming techniques for programming, with examples for JavaScript, Python, Lua and GDScript (for Godot Engine).

For Ideas, Rules, Simulations you will need a configured development environment for one of the previous languages:

JavaScript (for browsers) and GDScript provide built-in support for multimedia content.

I am also considering improving the online programming editors provided in this website, to support an interactive course. Currently, the page with tools provide options for:

The editors support images in the browser. However, Python and Lua use the JavaScript syntax for the canvas. If I create an abstraction and add support for audio, they could become valid tools (at least for the first activities).

However, it is worth configuring an Integrated Development Environment (IDE), or a combination of text editor with interpreter as soon as possible, to enable you to program using your machine with greater efficiency. Online environments are practical, though local environments are potentially more complete, efficient, faster and customizable. If you want to become a professional, you will need a configured development environment. The sooner you do it, the better.

Version in Video

This entry has video versions on the author's YouTube channel:

However, this text version is more complete.

Programming Simulations and Digital Games

Programming is not knowing how to use a programming language. In fact, in Learn Programming it was argued that programming is solving problems. Hence the importance of computational thinking.

If one thinks about a system or algorithm as a black box, systems:

  1. Receive an input or a stimulus;
  2. Process an input to calculate a result;
  3. Provide an output as a result.

A simulation is an imitation of a process or a system, potentially build by subsystems -- or a system of systems. As usual, consulting the definition can be useful.

Simulations use models to represent characteristics or behaviors. Programmatically, this is performed using abstractions for data decomposition (for instance, using records) and functional decomposition (for instance, using subroutines such as functions, procedures and methods). In systems, this means using arithmetic operations and boolean operations to process the memory. Such processing typically requires selections or choices, as well as repetitions and iterations.

In other words, the links in the previous paragraph describe many of the main resources applied to program. Hence the complexity.

In fact, the creation of a minimally complex simulation uses virtually all the basic programming concepts:

  1. Entry point;
  2. Output;
  3. Data types;
  4. Variables and constants;
  5. Input;
  6. Arithmetic;
  7. Comparisons;
  8. Logic operations;
  9. Conditional structures;
  10. Subroutines (functions and procedures);
  11. Repetition structures (or loops);
  12. Collections;
  13. Records (structs);
  14. Libraries;
  15. Tests and debugging.

To save data, one still uses files (or high-level implementations based on files, such as databases; at some point, there will exist a file). Therefore, we are back to the contents of Learn Programming. Fundamentals are the basis of every system -- as well as any knowledge.

Ideas, Rules, Simulation

Simulations can be inherently complex. Nevertheless, there exist simple simulations. Perhaps that they are not too interesting, though they can serve as a first step for a journey. A journey which continuity can allow creating increasingly complex (and interesting) simulations.

Ideas, Rules, Simulation promotes a project-based approach to learn programming. The series explores smaller projects with smaller scopes, with new concepts and complexity introduced over time. In other words, a continuous and incremental learning, on which your own programming and problem-solving skills will improve every project.

As it happened in Learn Programming, each new introduced concept and resource can be reused in the future. Thus, you will understand how to reduce the complexity of a system to for its simple parts. Systems to subsystems, subsystems to data and functional decomposition, each decomposition to the source code of a program. You will understand how design patterns are created: by the repetition and reuse of successful solutions from previous works in future projects. Patterns have been previously commented in Records and in Libraries. By understanding how they originate, you will be able to modify existing patterns to your needs, as well as create your own.

Once again, smaller projects allows doing that gradually, iteratively, and continuously, with gentler learning curves.

From Entry Point and Program Structure, programming activities can start from a Hello, world! (typically written as Hello, my name is Franco! in this blog's entries). For multimedia simulations, the process will be similar. From a Hello, world! to the first images, from the first images to real-time interactive systems. We will create a window, draw pixels, then more complex geometric forms (such as lines and polygons), then image, animations, sounds...

As the concepts and fundamentals, you will transform ideas in simulations. Ideas, problems, algorithms, systems: ideas, rules, simulation. In short, this is the essence to create computational simulations: the creation of rules that transform your ideas in computer programs.

The projects will have a beginning -- for instance, a Hello, world!. On the other hand, unlike Learn Programming, there is not a predefined end. In the future, we will be able to explore concepts and resources such as rendering, Artificial Intelligence, distributed systems.

Part of the journey consists of helping you to become independent and able to create your own projects. Therefore, depending on how the series evolves, you may level up from a beginner, to adequate, competent, proficient, professional... After mastering the fundamentals, the only limits will be your imagination, problem-solving skills, the available hardware, and what is computationally possible. After all, every computer program starts, though not every program ends.

The most important, though, it that you understand and perceive the progress, as well as become able to use the knowledge to create your own systems. Thus, sooner or later, you will be able to make magic with computers, using Computation as it is: science for you, magic to other people.

The First Step: Hello, World! in Console (Terminal)

As it has been commented in Learn Programming: Entry point, it is traditional to write "Hello, world!" as the first program when learning a new language.

# NOTE Modify if you use other type of Node as the scene's root.
extends Node

func _ready():
    print("Hello, my name is Franco!")
console.log("Hello, my name is Franco!")
print("Hello, my name is Franco!")
print("Hello, my name is Franco!")

This series assumes that you know how to create a project and run code in the chosen language. If you need help, you can watch the videos on the author's YouTube channel:

For GDScript, there is also a written version illustrating how to create a project for Godot Engine. For the other languages, you can refer to the section Requirements at the beginning of this page.

To start, create a file or project in your favorite text editor or IDE. Next, run the project.

For JavaScript, you can use the embedded console in your browser (shortcut: F12).

If everything is correct, the message should appear on the console (terminal) of your command line interpreter or IDE.

Say goodbye to the console. The console has fulfilled its part of outputting data for Ideas, Rules, Simulation. Hereafter, console output will be complimentary, as a resource for logging or debugging.

It is time to start a graphical environment.

The Second Step: A Graphical Window

If you are using GDScript, Godot Engine has already created a window for you. In other words, you completed two steps in a single one.

The other languages require additional setup to create a graphical window.

HTML Canvas for JavaScript

JavaScript, in particular, will require an auxiliary HTML file. The file can be named index.html (or other name that you prefer). The code assumes that the name of the JavaScript will be script.js. If you choose another name, remember to modify it in the created HTML file. Likewise, the value provided as the id for the tag canvas is important. If you change the value to something like drawing-area, remember to modify the code in the JavaScript that you will create soon.

<!DOCTYPE html>
<html lang="pt-BR">
  <head>
    <meta charset="utf-8">
    <title>My First Program with Graphics</title>
    <meta name="author" content="Franco Eusébio Garcia">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <div style="text-align: center;">
      <canvas id="canvas"
              width="1"
              height="1"
      >
          Accessibility: alternative text for graphical content.
      </canvas>
    </div>

    <!-- NOTE Updated with the name of the JavaScript file. -->
    <script src="./script.js"></script>
  </body>
</html>

You will be able to use this same HTML file for many other projects.

After creating this HTML file and the JavaScript file from the next section, you must open the HTML in the browser of your preference to run the project.

For accessibility, you can change the text between the canvas tags to describe what will be represented. This is an important feature for people who use technologies such as screen readers to understand the contents. For this topic, you would modify the content for something like "The canvas displays the message 'Hello, my name is Franco!'.". Later, you can update it with the second message.

Unfortunately, the initial content of this series will not be universally accessible, because the introduction of additional programming resources are still required to do it. Each step as its time.

Considering this addendum, HTML is not a language of interest at this time. That honor belongs to the GDScript, JavaScript, Python and Lua programming languages.

GDScript, JavaScript, Python and Lua

In all languages, the goal will be creating a drawing window or area. At this moment, it can have a width of 320 pixels (px) and a height of 240 px. Thus:

  • In GDScript, the only requirement is changing the size of the window;
  • In JavaScript, the goal is to get a reference for the canvas and adjust its size;
  • In Python, the goal is starting a window using PyGame and set the size;
  • In Lua, the goal is starting a window using LÖVE (Love2D) and set the size.
extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))

    print("Hello, my name is Franco!")
let canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")

canvas.width = 320
canvas.height = 240

console.log("Hello, my name is Franco!")
import pygame

pygame.init()
# The additional parentheses are important (they create a Tuple in Python).
window = pygame.display.set_mode((320, 240))

print("Hello, my name is Franco!")

pygame.quit()
-- NOTE The name of the file must be "main.lua" (without quotes).
function love.load()
    love.window.setMode(320, 240)

    print("Hello, my name is Franco!")
end

Some examples already use variables and assignments. Python and Lua also use libraries.

If you are just starting programming, the = is not a logic operator for equality, as in Mathematics. It represents an assignment, which means that it stores a value in the memory that can be retrieved using a name. For instance, in the JavaScript code, canvas is a variable that stores a reference to the canvas created in HTML.

Besides, you can change Hello, my name is Franco! to any other text of your choice. The only requirement is that it is written in-between double quotes and does not contain an explicit line break (in other words, the whole text must be written in a single line). In programming, the defined text has a type called string.

In Learn Programming, every call to a subroutine (function, procedure or method) or every new composite data type provided a documentation link. This time, the author will assign the responsibility of searching for the documentation to you. To find out what a call does, you can search for its name and read the descriptive text.

Practice consulting the documentation:

Most links have a search field. In Lua, the documentation is in a single page. You can search for entries using the shortcut Ctrl F (search).

The Third Step: The Title of the Window

When one creates a library, a framework, or an engine for rendering (drawing in the screen), it is common starting by primitives such as pixels and lines. Drawing text to represent a word is slightly more complex.

If you have read the topic about Files in Learn Programming, you already know a way to draw text as an image. In Ideas, Rules, Simulation, the creation of a project for font rasterization requires concepts that will be introduced in the future.

A simple alternative to write text in a window before implementing a raster consists in using the title of the window. The title of the window allows writing a single, short line of text using a string. This can be useful for debugging, when one still has not implemented a raster for fonts.

extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")
let canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")

canvas.width = 320
canvas.height = 240

document.title = "Hello, my name is Franco!"
import pygame
import sys

pygame.init()
window = pygame.display.set_mode((320, 240))
pygame.display.set_caption("Hello, my name is Franco!")

while (True):
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            sys.exit(0)
function love.load()
    love.window.setMode(320, 240)
    love.window.setTitle("Hello, my name is Franco!")
end

The code in Python using PyGame is slightly more complex than the others. It uses a combination if repetition and conditional structures to keep the window opened, as well as close it when one uses the default shortcut (typically Alt F4) or the icon to close the window (typically a X). At this time, you do not need to worry about them; conditions and repetitions (or loops) will be commented soon.

If you do want to learn them now, consult Learn Programming:

Behind the scenes, GDScript with Godot Engine and Lua with LÖVE also define conditional and repetition structures with the same goal. However, they are abstracted by the implementation. Godot Engine and LÖVE are game engines. Engines (and frameworks, in general) are higher-level structures than a library such as PyGame. Frameworks adopt pre-defined conventions for certain features. In other words, there is a trade-off between liberty (and flexibility at times) for greater convenience of use.

Something similar happens in the JavaScript version. In this case, the browser is responsible for controlling the canvas life cycle in the opened window.

Fourth Step: Hello, World! in a Window

Godot Engine, the HTML canvas, PyGame and LÖVE provide resources to write text in a window. Thus, it is not necessary to use the title as a work-around; rather, text can be drawn directly using resources from each implementation.

To write text in a window, it is necessary to provide an ordered pair (x, y) as the initial position for the drawing. In graphical systems, the origin (0, 0) normally is represented in the top-left corner. The values of x grow to the right. The values of y grow to the left.

Thus, drawing text in the position (10, 20) means that it will start offset 10 pixels to the right and 20 pixels to the bottom. The next blocks write Hello, my name is Franco! at this position.

extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")

    var label = Label.new()
    label.text = "Hello, my name is Franco!"
    label.rect_position.x = 10
    label.rect_position.y = 20
    add_child(label)
let canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")

canvas.width = 320
canvas.height = 240

document.title = "Hello, my name is Franco!"

context.clearRect(0, 0, canvas.width, canvas.height)
context.fillText("Hello, my name is Franco!", 10, 20)
import pygame
import sys

pygame.init()
window = pygame.display.set_mode((320, 240))
pygame.display.set_caption("Hello, my name is Franco!")

font = pygame.font.Font(None, 20)
text = font.render("Hello, my name is Franco!", True, (255, 255, 255))
window.blit(text, (10, 20))
pygame.display.flip()

while (True):
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            sys.exit(0)
function love.load()
    love.window.setMode(320, 240)
    love.window.setTitle("Hello, my name is Franco!")
end

function love.draw()
    love.graphics.setColor(1.0, 1.0, 1.0)
    love.graphics.print("Hello, my name is Franco!", 10, 20)
end

The result will be similar to the contents displayed in the following canvas (the message is in Portuguese).

The message 'Olá, meu nome é Franco!' using a HTML Canvas.

In all cases, drawing text in the window is more complex than writing it at a console using print() or console.log(). This is the reason that introductory material (and even material for complex, advanced topics) usually use a console instead of graphics: the information conveyed in the console output can be the same, and it much simpler to output it.

Nevertheless, it is not impossible to draw text using a library. It certainly requires more work and lines of code, though this can be solved soon, with the creation of a subroutine to draw the text.

At this time, drawing text is simpler in JavaScript using canvas and Lua using LÖVE. The GDScript version is slightly more complex.

The Python version using PyGame is the most complex among the four. On the other hand, it is the one describes with the greatest clarity what is being performed by the computer:

  1. A font is chosen for drawing the text;
  2. The text to be written is chosen, along a color; In this case, (255, 255, 255) is white;
  3. Text is rendered as a bitmap image. A bitmap is a matrix (greatly simplifying, a table) that maps colors to positions of a rectangular area. Each position has a color corresponding to one pixel in the screen;
  4. The bitmap is drawn on the window.

Although it is more verbose and complex, the process is more illustrative. Now you understand how the text that shows in your screen is drawn. The computer does not know what is text; it only colors the chosen pixels with the desired colors.

It should be noticed that the text is drawn as an image in all examples. If you attempt to select the text using the mouse, it will not be possible. Although this can be a small inconvenience for you, it is an accessibility barrier to some people. For instance, the content is inaccessible for blind people.

For the time being, an alternative would be continuing to print the text to the console. Another option would be copying the text to the clipboard. For instance, in GDScript, this could be implemented using OS.clipboard.

extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")

    var label = Label.new()
    label.text = "Hello, my name is Franco!"
    label.rect_position.x = 10
    label.rect_position.y = 20
    add_child(label)

    OS.clipboard = "Hello, my name is Franco!"

Although better than nothing, these are not ideal solutions.

At some point, the series will comment about the creation of (more) accessible media content. Unfortunately, this is not yet the time, as it would require more than a window. If you are curious about it, you can learn about screen readers and text-to-speech (TTS) systems.

Fifth Step: Two Lines of Text

What should you do after writing your first line of text?

Write your second one.

extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")

    var label = Label.new()
    label.text = "Hello, my name is Franco!"
    label.rect_position.x = 10
    label.rect_position.y = 20
    add_child(label)

    var website = Label.new()
    website.text = "www.francogarcia.com"
    website.rect_position.x = 10
    website.rect_position.y = 40
    add_child(website)
let canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")

canvas.width = 320
canvas.height = 240

document.title = "Hello, my name is Franco!"

context.clearRect(0, 0, canvas.width, canvas.height)
context.fillText("Hello, my name is Franco!", 10, 20)
context.fillText("www.francogarcia.com", 10, 40)
import pygame
import sys

pygame.init()
window = pygame.display.set_mode((320, 240))
pygame.display.set_caption("Hello, my name is Franco!")

font = pygame.font.Font(None, 20)
text = font.render("Hello, my name is Franco!", True, (255, 255, 255))
window.blit(text, (10, 20))

website = font.render("www.francogarcia.com", True, (255, 255, 255))
window.blit(website, (10, 40))

pygame.display.flip()

while (True):
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            sys.exit(0)
function love.load()
    love.window.setMode(320, 240)
    love.window.setTitle("Hello, my name is Franco!")
end

function love.draw()
    love.graphics.setColor(1.0, 1.0, 1.0)
    love.graphics.print("Hello, my name is Franco!", 10, 20)
    love.graphics.print("www.francogarcia.com", 10, 40)
end

The result will be similar to the contents displayed in the following canvas (the message is in Portuguese).

'Olá, meu nome é Franco!' and 'www.francogarcia.com'.

Compare the new code with the previous one. What has changed?

In all versions, the implementation has duplicated only the essential part, changing the message and the position to draw it. To keep the second text aligned to the first, the value of x was kept as 20 and the value of y was increased to 40.

How would you write a third line?

Sixth Step: Colors

Some implementations (such as Lua with LÖVE) has mentioned colors. Colors can be used both for the background, and for the text.

Before modifying them, it is worth knowing that colors in computers are represented as values in color systems. For multimedia content, the color systems Red, Green and Blue (RGB) and Red, Green, Blue and Alpha (RGBA; Alpha represents the transparency) are commonly used.

In the RGB and RGBA color systems, colors are composed as combinations of shared of the primary colors red, green and blue (hence the names). Each primary color has a value ranging from a minimum to a maximum.

However, the value can be written two ways, depending on the implementation:

  1. As a real number, ranging from 0.0 (minimum value) to 1.0 (maximum value). One can understand it as a percentage of the participation of the primary color to the composition of the final color;
  2. As an integer number, usually ranging between 0 (minimum value) to 255 (maximum value). In this case, it is not possible to choose a decimal number (127 is valid, though 12.34 is not). The possible minimum and maximum value depend on the number of bytes used to encode the color. One byte (8 bits) can encode 256 different values; hence the interval. The explanation is available in Learn Programming: Arithmetic.

The value zero (0) for every primary color results black. The maximum value (1.0 or 255) for each primary color results white.

Furthermore, the value of alpha determines the transparency. The value zero (0) means that the color will be 100% transparent. The maximum value (1.0 or 255) means the color will be 100% opaque. Any other value means that the image will have an intermediate transparency. The closest the value is to zero, the greater the transparency.

extends Node

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")

    VisualServer.set_default_clear_color(Color(1.0, 1.0, 1.0))

    var label = Label.new()
    label.text = "Hello, my name is Franco!"
    label.rect_position.x = 10
    label.rect_position.y = 20
    label.modulate = Color(1.0, 0.0, 0.0)
    add_child(label)

    var website = Label.new()
    website.text = "www.francogarcia.com"
    website.rect_position.x = 10
    website.rect_position.y = 40
    website.modulate = Color(0.3, 0.6, 0.9, 0.5)
    add_child(website)
let canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")

canvas.width = 320
canvas.height = 240

document.title = "Hello, my name is Franco!"

context.clearRect(0, 0, canvas.width, canvas.height)
context.rect(0, 0, canvas.width, canvas.height)
context.fillStyle = "black"
context.fill()

context.fillStyle = "rgb(255, 0, 0)"
context.fillText("Hello, my name is Franco!", 10, 20)
context.fillStyle = `rgba(${0.3 * 255}, ${0.6 * 255}, ${0.9 * 255}, 255)`
context.fillText("www.francogarcia.com", 10, 40)
import pygame
import sys

pygame.init()
window = pygame.display.set_mode((320, 240))
pygame.display.set_caption("Hello, my name is Franco!")

window.fill((255, 255, 255))

font = pygame.font.Font(None, 20)
text = font.render("Hello, my name is Franco!", True, (255, 0, 0))
window.blit(text, (10, 20))

website = font.render("www.francogarcia.com", True, (0.3 * 255, 0.6 * 255, 0.9 * 255))
website.set_alpha(127)
window.blit(website, (10, 40))

pygame.display.flip()

while (True):
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            sys.exit(0)
function love.load()
    love.window.setMode(320, 240)
    love.window.setTitle("Hello, my name is Franco!")
end

function love.draw()
    love.graphics.setBackgroundColor(1.0, 1.0, 1.0)

    love.graphics.setColor(1.0, 0.0, 0.0)
    love.graphics.print("Hello, my name is Franco!", 10, 20)
    love.graphics.setColor(0.3, 0.6, 0.9, 0.5)
    love.graphics.print("www.francogarcia.com", 10, 40)
end

In the JavaScript version, the result will result will be similar to the contents displayed in the following canvas (the message is in Portuguese). In the other languages, the background will be white.

'Olá, meu nome é Franco!' and 'www.francogarcia.com' with custom colors.

In the modified code, the version in Lua with LÖVE becomes the simplest and most concise one. The JavaScript versions become slightly more complex, because it is necessary to draw a rectangle to color the entire canvas. The versions in GDScript and Python are still similar: a call to choose or apply a background color, some adjustments for the color of the text.

Furthermore, GDScript and Lua use real values for the primary colors in RGB and RGBA, while JavaScript and Python use integer values. The examples show a simple way to convert real color values (0.0 a 1.0) to integer ones: they can be multiplied by the desired percentage. To perform the inverse conversion (colors as integers to real numbers), one can use divisions by 255.0 (it is necessary to add .0 in programming languages such as GDScript to force a real division). For example, for the GDScript version:

label.modulate = Color(203 / 255.0, 127 / 255.0, 127 / 255.0, 127 / 255.0)

In both cases, a percentage of the total value is combined with the maximum value for each shading of each primary color. The multiplication or the division generate the expected value to convert from one representation to the other. Another way to convert values consists of using a color calculator or using programs called color pickers or color wheels, which allows selecting colors.

Thus, now you are able to write colored text over a colored background. For comparison purposes, the following examples provide equivalent code to create a program for console (terminal) with the same output using plain text.

extends Node

func _ready():
    print("Hello, my name is Franco!")
    print("www.francogarcia.com")
console.log("Hello, my name is Franco!")
console.log("www.francogarcia.com")
print("Hello, my name is Franco!")
print("www.francogarcia.com")
print("Hello, my name is Franco!")
print("www.francogarcia.com")

The version for console is more concise and simple, which makes it easier to be understood by a beginner; hence the choice in introductory materials. If one wanted to modify the colors in the console, the examples would become slightly more complex.

Concepts Covered From Learn Programming

Concepts from Learn Programming covered in this topic:

  1. Entry point;
  2. Output;
  3. Data types;
  4. Variables;
  5. Arithmetic;
  6. Libraries.

The RGB model has been previously discussed in Files (Portable Pixmap Format or PPM). The creation of a raster that converted text to image was discussed as well.

Additionally, the Python implementation had to use comparisons and repetition structures (or loops) to keep the window opened, as well as close it.

New Items for Your Inventory

Computational Thinking Abilities:

Tools:

  • Libraries, frameworks, and/or game engines:
    • Python: PyGame;
    • Lua: LÖVE (Love2D);
    • GDScript: Godot Engine;
    • JavaScript: HTML canvas.
  • Colors:
    • Colors calculators;
    • Color pickers;
    • Color wheels.

Skills:

  • Create a window;
  • Set the title of a window;
  • Use the title of a window for a debug message;
  • Write text in a window.

Concepts:

  • Simulation;
  • Models;
  • Colors;
  • Color systems (RGB, RGBA).

Programming resources:

  • Writing text in a graphical environment.

Practice

To learn programming, deliberate practice must follow the concepts. Try doing the next exercises to practice.

  1. Change the size of the window. For instance, set the values of x and y, in this order, to:

    • HD resolution: 1280 x 720;
    • Full HD resolution: 1920 x 1080;
    • Resolution of older laptops or with basic video cards: 1024 x 768 or 1366 x 768;
    • Zero for both values. What does happen?
    • Two negative values. What does happen?
  2. Change the text of one of the messages in the window;

  3. Write a third message in the window;

  4. Write two different messages starting at the very same position (for instance, (0, 0)). What does happen?

  5. Change the background and text colors to your favorite ones;

  6. Use transparent colors. Write two messages at the same position and watch the results;

  7. Write a long message. The goal is making it exceed the screen's space. What does happen?

  8. What does happen when:

    • You choose a position for the text that is out of the bounds of the window?
    • You choose a position for the text with negative values?
  9. How to make the program full screen, that is, remove all borders and bars from the window to make it completely fill the dimensions (resolution) of the screen? Research it. If you do it, you press Alt TAB to alternate between open windows using the keyboard.

    To close the window using a specific key, you will need to use, for instance, input and conditional structures. In particular, the input must be non-blocking. Therefore, it is not yet possible to do it in this new series (though it will be in future topics).

  10. How could use a custom font instead of the default one? Search the Internet for the solution for you technology of choice.

Deepening

In Ideas, Rules, Simulation, this section will provide complementary content. When it exists in the next topics, the subsections will detail concepts and techniques that are restricted to specific technologies. If a subsection includes a programming language of your choice, it is worth straying it.

GDScript: Using the Editor of Godot Engine

The GDScript example used a label with Label to write text. Although, as it has been done in the example, this has performed programmatically using GDScript, it is more common to create part of the content using the editor that is embedded to Godot Engine.

To learn how to do it, you can consult the page describing how to configure a development environment for GDScript (Godot).

GDScript: Writing Text Without Using a Label

Although the traditional way to write text in GDScript consists of using a Label, it is also possible to do it using a lower-level Application Programming Interfaces (API).

# The root must be a Node that allows drawing with _draw().
extends Control

var default_font = get_theme_default_font()

func _ready():
    OS.set_window_size(Vector2(320, 240))
    OS.set_window_title("Hello, my name is Franco!")

func _draw():
    VisualServer.set_default_clear_color(Color(1.0, 1.0, 1.0))

    draw_string(default_font, Vector2(10, 20), "Hello, my name is Franco!", Color(1.0, 0.0, 0.0))
    draw_string(default_font, Vector2(10, 40), "www.francogarcia.com", Color(0.3, 0.6, 0.9, 0.5))

It should be noted that the script's scene must be of a type that allows using _draw(), such as Control. Node, for instance, does not define the drawing method.

In the new version, the code becomes closer to the one written for the other programming languages.

Python with PyGame: True Type Fonts using FreeType

PyGame provides an additional module to draw TrueType, Type 1, and OpenType fonts using the FreeType library. The alternative implementation allows setting the transparency directly in the call to render().

import pygame
import sys

pygame.init()
window = pygame.display.set_mode((320, 240))
pygame.display.set_caption("Olá, meu nome é Franco!")

window.fill((255, 255, 255))

font = pygame.freetype.Font(None, 20)
text, text_rectangle = font.render("Olá, meu nome é Franco!", (255, 0, 0))
window.blit(text, (10, 20))

website_text, website_rectangle = font.render("www.francogarcia.com", (0.3 * 255, 0.6 * 255, 0.9 * 255, 127))
window.blit(website_text, (10, 40))

pygame.display.flip()

while (True):
    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            pygame.quit()
            sys.exit(0)

The changes are on the font creation (pygame.freetype.Font()) and how to draw the text.

The FreeType implementation is more modern than the regular one. If you prefer, you can use this new version.

Next Steps

This was the introductory topic of Ideas, Rules, Simulation.

Now you know how to create a window in GDScript, Python and Lua, as well as create a drawing region in JavaScript. In the four languages, you also know how to change the title and write text at an arbitrary position.

Perhaps part of the code is hard to understand -- especially the Python versions using PyGame. It is fine. A step at a time (or, if you are in a rush, start by Learn Programming).

The next topics will start incorporating additional resources from programming languages and multimedia content. After writing text, a next step can be drawing primitive images. To do this, the next topic will introduce pixels.

If you wish to contact me or have any questions, you can chat with me by:

Information about contact and social networks are also available at the footer of every page.

Your opinion about the series will be fundamental to enable me to create a material that is more accessible and simpler for more people.

Furthermore, if you have found this material useful, considering sharing it. If possible, use the hashtags #IdeasRulesSimulation and #FrancoGarciaCom.

Ideas, Rules, Simulation

  1. Motivation;
  2. Introduction: Window and Hello World;
  3. Pixels and drawing primitives (points, lines, and arcs);
  4. Randomness and noise;
  5. Coins and dice, rectangles and squares;
  6. Drawing with drawing primitives (strokes and fillings for circles, ellipses and polygons);
  7. Saving and loading image files;
  8. ...

This material is a work in progress; therefore, if you have arrived early and the previous items do not have links, please return to this page to check out updates.

I thank you for your attention. See you soon!

  • Video
  • Informatics
  • Programming
  • Beginner
  • Computational Thinking
  • Ideas, Rules, Simulation
  • Python
  • PyGame
  • Lua
  • LÖVE (Love2D)
  • Javascript
  • HTML Canvas
  • Godot
  • Gdscript