Python Shorts — Alphaflip Game

Here’s a simple Python text-based game that’s fun and challenging to play.

John Clark Craig
Better Programming
Published in
4 min readMay 12, 2022

--

Photo by Susan Holt Simpson on Unsplash

If anyone remembers the old TRS-80 computers, and the CLOAD Magazine programs you could load from cassette tape, you might have played a game I invented long, long ago, in a galaxy far, far away. Well, it kind of feels that way to me. Using very crude graphics, I created a little UFO that would zip around above a row of alphabet letters, swapping their order on command, until the alphabet was all back in order.

But that was then, and this is now.

I decided to revive that game using Python, and it turned out to be pretty easy and fun to do. Let’s take a look at the complete code listing for this game, then I’ll explain some of its useful parts, and show an example of the game play.

The alphaflip.py Source Code

from random import *game_size = 7
alpha = [chr(c + 97) for c in range(game_size)]
goal = alpha.copy()
shuffle(alpha)
score = 0
while alpha != goal:
print(f"\nScore: {score}\n{' '.join(alpha)}")
two_chars = input("Enter two letters for a flip: ")
two_chars = two_chars.strip().lower()
i = alpha.index(two_chars[0])
j = alpha.index(two_chars[1])
if i > j:
i, j = j, i
score += j - i + 1
while i < j:
alpha[i], alpha[j] = alpha[j], alpha[i]
i += 1
j -= 1
print(f"\nWinner! Score: {score}")

How Much of a Challenge Are You Up To?

As shown, game_size is set to 7, so the alpha list is comprised of the first 7 characters of the alphabet, “a” through “g”. This makes for an interesting and reasonable game, but you can set game_size as high as 26 if you dare.

A Few Code Comments

Most Python games import the random module to keep things shuffled or otherwise randomized from game to game. That explains the first line.

The list named alpha is filled with the first few letters of the alphabet, depending on game_size. A list comprehension makes setting up this list very concise and easy.

--

--

Author, inventor, entrepreneur — passionate about alternate energy, technology, and how Python programming can help you hack your life.