SECRET OF CSS

Python Shorts — Alphaflip Game. Here’s a simple Python text-based game… | by John Clark Craig


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

0*etigujAQ2 YTHcZZ
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.

The list named alpha is copied to a second list named goal. Be careful when copying Python lists and other objects. For instance, you might not get a complete copy if the list contains other lists or objects. The copy() operation works fine here, but always consider if deepcopy() might be safer. If you simply were to set goal = alpha both lists would reference the same items in memory, causing problems right away.

The index variables i and j are set by finding the location in the list of the two characters input by the user. The list method index() finds these locations.

The While Loop

All the remaining code lines, except the very last one, cause the program to print the score so far, and then to ask for a range of letters to have their order reversed, or flipped. This repeats until all the letters are in the right order, at which time the last line of code lets you know you are a winner, and it shows your final score. The smaller the score, the bigger the bragging rights you have.

Shuffle, F-strings, and Swaps, Oh My!

A list can be randomly shuffled in place with the random module’s shuffle() method. My program calls shuffle() at the start to, well, shuffle the letters around in the list named alpha.

The two print commands use f-strings for efficient, powerful, and easy-to-read code for displaying intermediate and final results as the game proceeds. I’m so enthralled with f-strings that I wrote a whole Medium article on the subject.

A cool feature of Python is how you can swap two variables in one command. For example, to swap the contents of two variables, simply assign them to each other, something like this: x,y = y,x. This technique is used twice in the program, to swap the indexes into sequential order, and to swap pairs of letters in alpha as the game proceeds.

A New Way to Score

In my original TRS-80 game, I tallied the number of flips to provide a score. But it turns out that a much better way to score the game is to add up the total number of characters that are flipped. This challenges you to plan ahead, to figure a strategy to group the letters efficiently to get them all in order. Try it and you’ll quickly get the feel for what I’m driving at.

Example of Play

Here’s a sample game with the game size set to 7. I played several games to get my score down to 10 for this example. My most often score was closer to 21. Can you beat 10?

1*UbtKC18Po4ruET17fm5Rkg



News Credit

%d bloggers like this: