Sunday, October 25, 2015

pencilWars using PyGame in Python

 About two years ago, Congress gave me some forced time off so I decided to learn some Python in addition to working on the house. Ever since learning BASIC on my Atari 400 (with the Atari 410 cassette drive!), I’ve liked interpreted languages. I probably inherited that from my dad who was an APL and SAS programmer back in the day. I still only program in Matlab for work. When I (tried) learning C++ and Java, I felt the same frustration recently expressed by Wil Wheaton. So Python had its appeal - interpreted, seemingly widespread, and free. I wrote a game because I didn’t have a particular problem I wanted to solve other than having fun and learning something new - just like when I banged away on my Atari, except now I don’t have to use a membrane keyboard and black and white television.

PencilWars is based on a paper-and-pencil game of the same name detailed in Tom Angleberger's Oragami Yoda. It is built using the pygame 1.9 package and runs in either Python 2.7 or 3.4. You can download the source code here.

Screen shot of pencilWars. Player 2 just moved indicated by the red pencil stroke and it's now Player 1's turn.
The architecture of the game is very similar to my last blog post Arduino Pong, although pencilWars has more states. In pencilWars, the user clicks the mouse - depending upon the state of the game this either selects a ship or moves the ship. To move the ship, the user "flicks" the mouse while holding down the mouse button in the desired direction of motion. The distance the ship moves is based on the velocity of the mouse during the click and not the distance moved. This action is the challenge.

The users take turns. If one hits an asteroid, they lose a turn. If one hits the space station in the middle of the page, they lose their ship. The first to destroy their opponent's ships wins.

One of the more interesting things I had to figure out was a function to determine the distance between the location of an sprite (ship, asteroid, station) and a line segment (the path taken by another ship). If the distance is less than sum of the two sprites' radii, there was a collision. 

I hope you enjoy playing. 

No comments:

Post a Comment