(en) PyCheckers — #2 Creating the base application

in #utopian-io7 years ago (edited)

PyCheckers is series of articles in which I describe my process of creating a checkers board game (also known as English draughts) in Python programming language. This is a project for my studies and I still learn to code in Python, therefore I invite you all to follow up and learn with me.

Disclaimer: starting with this one, I'll be publishing posts from PyCheckers series using the Utopian.io app. This will slightly modify the posts' structure for the better (more headings, post overview at the beginning etc.). Hope you like the changes!

PyCheckers series


PyCheckers series logo.
Background image by Paul Brennan (Public Domain).
Python logo by Python Software Foundation

Introduction

Welcome to the second post in the PyCheckers series! Last time I introduced the project, described most of the English draughts rules and also I wrote about the game itself. The most important features of the PyCheckers game will be the availability to play the game against another human-player through Internet connection and single-player mode, where one will be able to play against a rather non-sophisticated artificiall intelligence algorithm (based on min-max algorithm).

One post is more than enought of talking, though, so today is the time to go into more technical aspects and finally start doing something for real (coding, yay!). Below I attach the contents of today's article.

What Will I Learn?

Today we will learn how to set up a development environment for Flask and how to create a simple base application with it.

  • How to install Python, Pip and Flask
  • What folder structure the project will be using
  • How to create a basic application in Flask
  • How to add templates and styles to the app
  • How to run your app on localhost

Requirements

This tutorial assumes that you're using a Linux distribution that is based on Ubuntu. This tutorial should work for other distros that have got APT package manager installed.

  • Ubuntu operating system (preferably 14.04 or newer)
  • Basic knowledge of terminal usage
  • Very basic knowledge of any programming language

Difficulty

This part is fairly simple, we are not doing any magic here, yet.

  • Basic

Contents

1. Technology stack

Here I'll describe my tech stack in details. Also, I'll write at least to some extent about my development and running environments (both localhost and remote).
It is important in case you would like to follow this series and develop the game on your own computer.

2. Setting up

In this part I explain how to set up the development environment, what requirements are there and what apps and packages to install in order to start developing PyCheckers game.

Then we will create the very basic Flask-powered app, upon which we will be able to expand.


1. Technology stack

Let's start with the technology stack I'll be using throughout the entire development process. This is a very important part if you'd like to work on the code simultaneously on your own. I assume that you'll be using a Linux distribution.

Python 3

The obvious part is that we have to have Python interpreter installed on our system. If you're using Ubuntu (or probably any other Debian-based installed), then you should already have Python installed in version 2. This is not satisfactory, as we'll be using it in version three.

If your system uses APT package manager, then you can simply open a terminal and enter:

$ sudo apt install python3

This should install required packages. After the setup is complete, you should be able to run python interpreter by using command in your terminal:

$ python3

Pip

Pip is a package manager for Python. It's name stands either for Pip Installs Packages, Pip Installs Python or Preferred Installer Program. We will need it to install Flask (and probably some other packages in the future). Again, type in your terminal:

$ sudo apt install python-pip

If the installations is successful, then by running the following command you'll get pip version printed out:

$ pip -V

Flask

flask.png


Flask logo by Armin Ronacher

Flask is the last package we will need for now. As its creators write on its page:

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. And before you ask: It's BSD licensed!
flask.poco.org

Flask is a super-simple framework that allows you to build websites and web applications with Python. It ships with such fundamental features like routing, templating and session management. It's also free, open-source and (from what I have found) it has got quite an active and helpful community.

To install flask we will have to use pip. In the terminal enter:

$ pip install Flask

You may also want to install Flask interpreter, so it is available from your terminal. To do so, enter this into the terminal:

$ sudo apt install python-flask

Front-end

I'll be using old-fashioned HTML and CSS to create the interface elements. Right now I am prototyping in plain CSS, but I might switch to SCSS in the future.

I am also using Kube CSS Framework by Imperavi to speed up the process. I have chosen Kube because it's lightweight and minimalistic.

2. Setting it up

After installing all the required packages, we can finally start creating our Flask-based application.

2.1. Folder structure

We will start by creating the folder structure for out app:

run.py
/pycheckers
. . /templates
. . . . base.html
. . . . index.html
. . /static
. . . . __init__.py
. . views.py

2.2. run.py file

run.py is a file with which we will be starting our application. It basically loads our entire app and start it. This is the content of the run.py file:

#!flask/bin/python
from pycheckers import app

app.run(host='127.0.0.1', port=5000, debug=True)

We import our app from pycheckers module (the folder called pycheckers), and then run it by invoking app.run() method. Both host, port and debug arguments are the same as default ones, but I entered them to be clear and for future changes.

2.3. /pycheckers contents

It's where we store all of our application files: Python logic, additional utilities, static files, templates and so on.

Firstly, let's initialize our app in the __init__.py file:

from flask import Flask

app = Flask(__name__)

from pycheckers import views

This imports Flask object into app variable. We also import our routing settings here (views). The basic content of the views.py file:

from hello_world import app

@app.route('/')
def index():
    return "Hello world!"

What we are telling Flask is that for the root URL address of the app (/), we want to execute index() function, which returns "Hello world!" string.

Right now, if we go into our app folder (where the run.py file is located) and start our app by entering into the terminal:

python3 run.py

it should be up and running. If you go to localhost:5000 in your browser, then you should see Hello world! printed out on your screen.

2.4. Templates

We don't want to only output plain text, are we? Flask supports Jinja 2 template engine by default and we'll be using it.

I won't go into details on Jinja here, but I'll quickly note for you:

{{ }} — double brackets are used to print a variable, like {{ variable_name }}
{% %} — single brackets with percentages inside are used for constructions like loop, if-else, nesting templates and others, like {% if x in y %} X is in Y! {% endif %}

We already have /templates folder in our app, and that's where we'll be storing all of our templates. Inside we already have base.html and index.html files. Let's see the first one:

<html>
<head>
    <title>{% block title %}{% endblock %} - PyCheckers </title>
</head>
<body>

    <h1>PyCheckers</h1>

    <div id="content">
        {% block content %}{% endblock %}
    </div>

    <footer>
        <p>PyCheckers game footer.</p>
    </footer>

</body>
</html>

This is called base for a reason: this is a basic template that we will use to render all other templates. It's a handy way for creating DRY (don't repeat yourself) code, since we can store header and footer of our site here to use it everywhere else.

{% block content %}{% endblock %} is the crucial part. In other templates, like index.html, we will let know Jinja, that the content of content block should be placed there:

{% extends "base.html" %}
{% block title %}Homepage{% endblock %}

{% block content %}
    <h2>Homepage</h2>

    <p>
      Welcome to PyCheckers game.
    </p>
{% endblock %}

Now we just have to link our routing paths with templates. Let's modify views.py file like that:

from hello_world import app

@app.route('/')

def index():
    return render_template('index.html')

If you go now to localhost:5000, you should see a nice webpage with <h1> and <h2> tags, and also a <p> underneath them.

2.5. Static files (css and js)

Lastly, we will want to add some stylesheets and maybe javascript to our app. That's when the /static folder comes in handy. There we will store all our static files. Below is the example structure of that folder:

/static
. . /css
. . . . style.css
. . /js
. . . . main.js

To get access to these files in a template, we can use built-in url_for() function. Modify the <head> block in our base.html file by adding there the following line:

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

Just before the </body> closing tag, add the javascript file:

<script src="{{ url_for('static', filename='js/script.js') }}"></script>

This way Flask will automatically render the valid path to the file. They will also be automatically added to all our templates, since they extend this base.html one.

Summing it up

Today we set up our development environment by installing the necessary packages. Then we created a very basic skeleton for our app with Flask. Next time we will create a checkers board filled with pieces, and we will also allow the pieces to be selected and moved around the board!

I encourage you to follow my PyCheckers series if you're interested in technology, programming and artificial intelligence or any similar field. PyCheckers will get into algorithmic thinking and learn some new programming skills.

Also, feel free to comment articles in this series. I am not a professional programmer, so there for sure will be some bugs, mistakes and things that could be done better. If you spot anything like that, have got something else to add or want to ask some questions—feel free to do it!

Thank you for your attention and see you next time!


PyCheckers Series (Curriculum)

This is a second post in the PyCherckers series, in which I write about an English-draughts-game I develop in Python 3 and Flask web-framework for my classess at university. Below you can find links to previous posts:

#1 — Introduction (on Steemit)

Here I talk about the origin of the project, why I do it, how I plan to do it and so on. I also describe English draugts rules extensively for those who do not know them.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Hey @mciszczon I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Coin Marketplace

STEEM 0.19
TRX 0.16
JST 0.033
BTC 64189.84
ETH 2796.72
USDT 1.00
SBD 2.65