Simple Snake (Refresh Games) Mac OS
Premise
Being the *nix fanboy that I am, I love having terminal access to my system. Most *nix based OS’s have the same base set of awesome command-line tools. The majority of these are simply “set and run” programs, but some have Text User Interfaces, (TUI), as well. A few of my favourites include screen, bmon, htop and lynx. Be sure to check those out if you haven’t already.
- Simple Snake game using OpenGL C, including a discrete snake robot model for producing real snakelike movements. (Linux, Ubuntu, Mac OS X, etc.) clone the game.
- Mac OS X To compile the game, you will need to have access to cmake. Brew install cmakeor download the latest version from cmake.org. If the cmakecommand is available in your terminal you have successfully installed CMake.
Feb 26, 2021 Perkin Haywood, Verutti Rozas Sal’s Krogh Pingree, O/Z Culbertson, Mac’s Wimbledon, A.E.O. McCarty Olde Cellar Rager Latham, Eckart Bullard Bruening Kerstner Oakville, Banker Russell, Gen Mdse Swenson G.W. Schaefer Whitesville, Wagner’s Blake’s Cigar Pendleton, John. Screenshots Screen Snake is a re-make of the classic snake game. But instead of moving the snake in a window, the snake moves across your screen itself, or even from screen to screen. This version includes multiplayer games, highscores, levels, and various little additions that should make the gameplay comfortable and fun.
If you’ve ever written a small command-line program that relied on any kind of user input, you’ve probably already coded your own rudimentary menu system at some point. It’s really not that difficult, but.. things can quickly get messy and you’d soon wish you had found an easier way of handling terminal control. Enter ncurses (new curses), a library for writing terminal-independent TUIs.
The project
There’s quite a few run-of-the-mill tutorials for curses out there, but doing a traditional “Hello World!” program just feels so uninspired. Instead we are going to do a simplified version of the classic game Snake, let’s call it PieceOfCakeSnake. In PieceOfCakeSnake you win simply by playing, there is no opponents, no consumables and no way of dying. Just a single, fixed-size, snake moving around in it’s little box world. The game starts right away upon launch and Snakey, our main character, is moving happily along from the get-go. The game ends when ‘x‘ is pressed.
Hammer and chisel
For no particular reason, I’m going to use Xcode for PieceOfCakeSnake and write it in C. If you want to use another editor be my guest, it’s much the same since it’s going to be run in a regular terminal anyway.
Now fire up Xcode and create a new project. Chose “Command Line Utility” > “Standard Tool”. Name the project and save it where you want.
Xcode have already created a main.c
file for us that simply outputs “Hello World!” and exits. Click “Run” > “Console” and click “Build and Go”. If all is well, the program builds without error and you should see something like this:
Now, ncurses comes native with Mac OS X, but for other systems you might need to install it beforehand. E.g. for Ubuntu there is the libncurses5
package.
There is still a little more to be done before we start coding. To get access to all the ncurses functions we have to tell the linker, to include the library at compile time. This is done by adding the line #include <ncurses.h>
at the top of main.c
and by supplying the linker flag -lncurses
to the compiler. If you are compiling this from the terminal with GCC, the command would be:
Where pocs
is the resultant executable. In Xcode however, we rely on the provided build system and so, the linker flag is set in the project properties. Click “Project” > “Edit Project Settings”, chose the “Build” tab and find the field named “Other Linker Flags” and insert “-lncurses”.
That should do it, we are set to go.
How To Refresh On Mac
Let’s see some code
In this first step, we’ll create a world for Snakey, a square box positioned in the middle of the terminal screen. Here’s the code:
Running this example, you should see something like this:
Notice the WINDOW
type. With ncurses everything is drawn on windows. By default, ncurses sets up a root window, stdscr
, which backdrops the current terminal display.
To use it we call initscr()
, which prepares the terminal for curses mode, allocates memory for stdscr
and so forth.
The windows in ncurses are buffered, in the sense that you can do multiple drawing operations on a window, before making them show up on screen. To display the contents of a window in the actual terminal, the window needs to be refreshed.
For stdscr
, this is done by calling refresh()
, for child windows we use wrefresh()
. This also shows the easy-to-remember naming convention used in the ncurses library – most functions that can be applied to stdscr
, also has a counterpart, which applies to child windows, simply named by prepending a ‘w’ to the function name. E.g. refresh()
and wrefresh()
. We’ll se more of this in the finished version.
Instead of drawing the box manually, we take a shortcut by creating a new window and using the function box()
to draw a border around the window. box()
can use any displayable character to draw the borders. Using 0 defaults to a system specific line character.
Note: COLS
and LINES
are environment variables, that holds the current width and height of your terminal. That is the number of horizontal and vertical character positions available in the window.
The getch()
function is simply there to pause program execution until some keyboard input is received. Thus a key press exits the program.
Functions delwin()
and endwin()
handles memory deallocation and returns the terminal to it’s former state. If these are omitted, the terminal will not behave as expected upon program termination and will probably need to be reset.
Time for some action
Now for the fun part – putting Snakey in his box and getting him to move about. Since this entry is about ncurses, I’m not going to go into the mechanics of the game itself. It’s a very simple implementation and the code should be rather self explanatory. You can download the source file here or just read from the following:
And here is what the game should look like in the terminal:
There is a few new ncurses functions being used here. Let’s start at the top. In main I’ve added:
From top to bottom. noecho()
subverts the terminal from printing back the users key presses. This is useful, since otherwise we would quickly have a lot of garbage on-screen from using the arrow keys to guide Snakey.
cbreak()
disables line buffering and feeds input directly to the program. If this wasn’t called, character input would be delayed until a newline was entered. Since we would like immediate response from Snakey, this is needed.
timeout()
sets an input delay, in milliseconds, for stdscr
, which is applied during input with getch()
and sibling functions. If the user doesn’t input anything within this given time period, getch()
returns with value ERR
. Useful in this part of the code, where we would like Snakey to move, even when we are not pressing any keys.:
The keypad()
function enables or disables special input characters for a given window. F keys and arrow keys for example.
printw()
works like the standard library function printf
. That is print a given string at the current cursor location.
To separate things a little, we have an auxiliary function move_snakey()
, which handles movement and redrawing of Snakey within the box. There is a few ncurses specific functions in there as well:
You could chose to add and remove individual characters if you want to be explicit, but I’m lazy, so I clear the whole window and redraw it again every time Snakey has moved. Clearing is done with clear()
for stdscr
and wclear()
for child windows.
The last function to mention is mvwaddch()
, which moves, notice mv, to coordinate x, y, in a child window, notice w, and adds a character at that position.
The mv prepend, like w, is also a part of the naming convention of ncurses. Thus most drawing operations have an extended version, that besides the item to be drawn, takes a set of coordinates of where to move the cursor before drawing it. E.g. printw()
and mvprintw
.
Goodbye Snakey
PieceOfCakeSnake is a very simple demonstration and only shows a very small subset of the features available with ncurses. For the inspired reader however, it should be no problem extending the game with a menu system, a scoreboard and more, using only the small part demonstrated here.
References and source
Latest versionReleased:
A extended version of package ``freegames``
Project description
Free Python Games is an Apache2 licensed collection of free Python gamesintended for education and fun. The games are written in simple Python code anddesigned for experimentation and changes. Simplified versions of severalclassic arcade games are included.
Python is one of the top-five most popular programming languages in the worldand available for free from Python.org. Pythonincludes an extensive Standard Library distributed with your installation. TheStandard Library has a module called Turtle which is a popular way to introduceprogramming to kids. Turtle was part of the original Logo programming languagedeveloped by Wally Feurzig and Seymour Papert in 1966. All of the games inFree Python Games are implemented using Python and its Turtle module.
Starting in 2012, Free Python Games began as an after school program toteach programming to inner-city youth. The goal was to have fun as much as itwas to learn. Since then the games have been improved and used in a variety ofsettings ranging from classrooms to summer day-camps.
The games run anywhere Python can be installed which includes desktop computersrunning Windows, Mac OS, or Linux and older or low-power hardware such as theRaspberry Pi. Kids across the United States in grades 6th-12th have enjoyedlearning about topics such as encryption and projectile motion through games.
Each game is entirely independent from the others and includes comments alongwith a list of exercises to work through with students. Creativity andflexibility is important. There is no right or wrong way to implement a newfeature or behavior! You never know which games students will engage with best.
Testimonials
“I love Free Python Games because the games are fun and they’re easy tounderstand and change. I like making my own games now.”
– Luke Martin, Student
“Free Python Games inspired and introduced a new hobby to our son. Thank you somuch for exposing him to coding. He is having so much fun!”
– Mary Lai, Parent
“Free Python Games are great because they really engage students and let themlearn at their own pace.”
– Rick Schertle, Teacher, Steindorf STEAM School
“Free Python Games combines play and learning in a flexible environment thatreduces the stress of a difficult topic like programming.”
– Brett Bymaster, Youth Pastor, The River Church Community
“Free Python Games is great for students, is highly organized and flexible,and seeks to unleash inquiry and understanding.”
– Terri Furton, Principal, Downtown College Prep
Features
- Fun to play!
- Simple Python code
- Easy to install
- Designed for education
- Depends only on the Python Standard Library
- Used in hundreds of hours of classroom instruction
- Fully Documented
- 100% Test Coverage
- Developed on Python 3.7
- Tested on CPython 2.7, 3.4, 3.5, 3.6, and 3.7
- Tested on Windows, Mac OS X, Raspbian (Raspberry Pi), and Linux
- Tested using Travis CI and AppVeyor CI
Quickstart
Installing Free Python Games is simple with pip:
Free Python Games supports a command-line interface (CLI). Help for the CLI isavailable using:
The CLI supports three commands: list, copy, and show. For a list of all gamesrun:
Simple Snake (refresh Games) Mac Os Catalina
Any of the listed games may be played by executing the Python module from thecommand-line. To reference the Python module, combine “freegames” with the nameof the game. For example, to play the “snake” game run:
Games can be modified by copying their source code. The copy command willcreate a Python file in your local directory which you can edit. For example,to copy and play the “snake” game run:
Python includes a built-in text editor named IDLE which can also execute Pythoncode. To launch the editor and make changes to the “snake” game run:
You can also access documentation in the interpreter with Python’s built-inhelp function:
Free Games
Paint
Paint – draw lines and shapes on the screen. Click to mark the start of ashape and click again to mark its end. Different shapes and colors can beselected using the keyboard.
Snake
Snake – classic arcade game. Use the arrow keys to navigate and eat thegreen food. Each time the food is consumed, the snake grows one segmentlonger. Avoid eating yourself or going out of bounds!
Pacman
Pacman – classic arcade game. Use the arrow keys to navigate and eat allthe white food. Watch out for red ghosts that roam the maze.
Cannon
Cannon – projectile motion. Click the screen to fire your cannnonball. Thecannonball pops blue balloons in its path. Pop all the balloons before they cancross the screen.
Connect
Connect – Connect 4 game. Click a row to drop a disc. The first player toconnect four discs vertically, horizontally, or diagonally wins!
Flappy
Flappy – Flappy-bird inspired game. Click the screen to flap yourwings. Watch out for black ravens as you fly across the screen.
Memory
Memory – puzzle game of number pairs. Click a tile to reveal anumber. Match two numbers and the tiles will disappear to reveal an image.
Pong
Pong – classic arcade game. Use the keyboard to move your paddle up anddown. The first player to miss the ball loses.
Simon Says
Simon Says – classic memory puzzle game. Click the screen to start. Watchthe pattern and then click the tiles in the same order. Each time you get thesequence right the pattern gets one step longer.
Tic Tac Toe
Tic Tac Toe – classic game. Click the screen to place an X or O. Connectthree in a row and you win!
Tiles
Tiles – puzzle game of sliding numbers into place. Click a tile adjacent tothe empty square to swap positions. Can you make the tiles count one to fifteenfrom left to right and bottom to top?
Tron
Tron – classic arcade game. Use the keyboard to change the direction ofyour Tron player. Avoid touching the line drawn by your opponent.
Life
Life – Conway’s Game of Life. The classic, zero-player, cellular automationcreated in 1970 by John Conway.
Maze
Maze – move from one side to another. Inspired by A Universe in One Lineof Code with 10 PRINT. Tap the screen to trace a path from one side toanother.
Fidget
Fidget – fidget spinner inspired animation. Click the screen to acceleratethe fidget spinner.
User Guide
For those wanting more details, this part of the documentation describescurriculum, API, and development.
References
Free Python Games License
Copyright 2017-2020 Grant Jenks
Licensed under the Apache License, Version 2.0 (the “License”); you may not usethis file except in compliance with the License. You may obtain a copy of theLicense at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributedunder the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied. See the License for thespecific language governing permissions and limitations under the License.
Release historyRelease notifications RSS feed
2.3.3
2.3.2
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Filename, size | File type | Python version | Upload date | Hashes |
---|---|---|---|---|
Filename, size freegames-extended-2.3.3.tar.gz (372.6 kB) | File type Source | Python version None | Upload date | Hashes |
Hashes for freegames-extended-2.3.3.tar.gz
Algorithm | Hash digest |
---|---|
SHA256 | e97e0f6a2d66e09492aa89632b279c97d49485d61ef0e64e43b784b60b0202ea |
MD5 | d25106849bd85632c77799d8db0a98c3 |
BLAKE2-256 | 6afd5ebb2e16a02839a15c7f3f21e9a83ee9545ace6686f765bd44a15212e23f |