Posts

Showing posts with the label python

Generating (better) random mazes

Image
Pt En In this previous post I shared some code and animations of an algorithm that created random mazes. I shared it with you and I got some feedback on Facebook, saying that even the stupidly large mazes I gave you were really easy to solve (I think this link can show you what I am talking about). So it was about time I got you some new mazes! And this time, I don't think they are as easy to solve as the old ones. The mazes I am sharing today were created by code found in this GitHub repo . The README will tell you to run the wilson_generator.py file. You can also download the (windows) executable that is zipped inside the wilsonExe rar. (please notice that in both cases, you can use the wilsonconfig.ini file to change the size of the maze) The way our algorithm works is really simple. It will start a random walk on the top left corner of the window. Whenever the random walk intersects itself (creating a loop), it removes the loop from the walk, and then c...

Introduction to the Hill Cipher

Image
Pt En The Hill cipher is a very simple cipher that works by using modular arithmetic and matrices. In a nutshell, your key is a matrix in some $\mathbb{Z}_m$ and you encrypt messages by breaking them up into pieces and then multiplying the pieces by the key matrix. That's it. I will be giving a workshop on this subject in a near future, and so I decided to write a Python notebook with a brief explanation of how the Hill cipher works, as well as providing an implementation of said cipher. The notebook can be downloaded and read here . I will be glad if you leave any suggestions/comments in the section below! A cifra de Hill é uma cifra simples que faz uso de noções de aritmética modular e de álgebra linear (mais concretamente, matrizes). Em duas frases, a cifra de Hill tem como chave uma matriz num dado $\mathbb{Z}_m$ e o modo como encripta mensagens é partindo-a em bocados com o mesmo tamanho e depois multiplicando a matriz chave por esses bocados. Num...

DumbFire, a simple shooting game

Image
Pt En DumbFire is a very simple shooting game that I created with Python and pygame and you can find the code here . As of now, the game does not have a menu whatsoever nor it has any kind of instructions... (btw, to play it use the WASD keys to move and the space bar to shoot; if the coloured balls hit you, you lose health; if you shoot them, you get health back) I have been incredibly busy so I am not sure I will tidy this up any time soon but feel free to fork the repo in GitHub and to add different types of enemies and maybe some kind of power-up or whatnot. Actually, I would be very interested in hearing from you the answer to: if I could only add one single extra functionality to the game, what would that be? O jogo DumbFire é um jogo simplecíssimo de tiros que eu fiz com Python e com pygame. O código está no repo usual e convido-vos a fazerem uma cópia do mesmo para experimentarem alterar os tipos de inimigos, talvez juntar um ou outro power-up, etc. De mome...

Random maze generation

Image
Pt En In this post I just want to share a simple algorithm that I used to create random mazes. The idea came from an e-mail I got, about a past competition, where one of the contestants did this exact thing: a program to generate random mazes. I saw the animation of the program working here and I deduced how to do it. All the code can be found on GitHub , as well as an executable of the program, the animations from the beginning and end of this post, an image of a bigger maze, and this other animation: where you can see a different style of maze; a less straight one. The maze starts in the top left red corner and ends wherever the other red square is, which need not be on the bottom right corner. The algorithm is simple: travel randomly inside the black area without ever hitting a white path; whenever no random move can be made, start going back until you find a place where the path can branch out again. While we are creating white paths, keep updating the fin...

Square roots by hand (and Newton's method)

Image
Pt En Na primária aprendemos a fazer somas, subtrações, multiplicações e divisões; o que nunca nos ensinam é a calcular raízes quadradas. Existe um algoritmo (não muito simples) para calcularmos raízes quadradas à mão, mas muitas vezes uma boa aproximação chega-nos. Acontece também que para o caso das raízes quadradas existe um truque muito simples que pode ser explicado com geometria, e esse truque produz aproximações muito boas! O que veremos mais adiante é que esse truque está relacionado com um método mais geral para resolver equações. Para explicar o truque vamos aplicá-lo diretamente. Vamos tentar encontrar a raíz quadrada de $7373$. A primeira coisa a fazer é arranjar um palpite. Quanto melhor for o palpite inicial, melhores vão ser as aproximações, mas não é preciso um palpite muito bom para que as aproximações sejam satisfatórias! Sei que $80^2 = 6400$ e $90^2 = 8100$ e $7373$ está mais ou menos no meio, portanto posso tomar $85$ como palpite inicial. Se quiserm...

Tutorial on programming a memory card game

Image
Pt En Este post vai ser um tutorial, não muito detalhado, sobre como fazer um jogo de memória com Python e pygame. O jogo que vamos implementar é um jogo comum: viramos uma série de cartas para baixo e temos que as virar duas a duas, tentando encontrar os pares. Claro que quando viramos duas cartas que não são um par, temos de as voltar de novo para baixo. Quando estou a criar um jogo, gosto de o ir desenvolvendo por etapas funcionais: partir o processo em várias fases que representem pontos nos quais eu tenho algo que posso testar. Deste modo, não só o processo se torna muito mais interessante, como posso ir controlando o aspeto do que estou a produzir. Deixo de seguida uma lista das etapas que eu pensei para este projeto; cada ponto da lista descreve a funcionalidade que o jogo já suporta: Criar um ecrã onde mostro todas as cartas dispostas, face para baixo; Clicar em cima de uma carta faz com que ela se vire para cima; Clicar na segunda carta verifica se encontrei...