0% found this document useful (0 votes)
28 views76 pages

Interactive Python Games for Learning

The Free Python Games project is a collection of interactive games designed to teach programming concepts through practical application in Python. It emphasizes modular programming and separates frontend and backend components for better maintainability, allowing learners to understand game logic and user interaction. This project serves as both a toolkit for learning Python and a reference for basic game development, encouraging experimentation and modification of existing games.

Uploaded by

dev14334156
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views76 pages

Interactive Python Games for Learning

The Free Python Games project is a collection of interactive games designed to teach programming concepts through practical application in Python. It emphasizes modular programming and separates frontend and backend components for better maintainability, allowing learners to understand game logic and user interaction. This project serves as both a toolkit for learning Python and a reference for basic game development, encouraging experimentation and modification of existing games.

Uploaded by

dev14334156
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Free Python Games

Project
Introduction
The Free Python Games project is a collection of small and interactive games developed
using the Python programming language. The main objective of this project is to provide
learners and beginners with a practical platform to understand fundamental programming
concepts through real working applications. Instead of studying theory alone, users can
explore how logic, conditions, loops, functions, and modules are applied in an actual
project [Link] project also demonstrates how Python can be used to build
graphical applications with smooth user interaction and simple game mechanics. Each
game is implemented in a modular manner, making the code easy to read, modify, and
extend. Developers can analyze how events such as keyboard input, screen updates, and
object movements are handled [Link] studying this project, students can gain
confidence in reading large codebases and understanding how different files work
together to form a complete application. The project encourages experimentation and
learning by modifying existing games or creating new ones using the same structure.
Overall, the Free Python Games project serves as a valuable educational resource for
anyone interested in Python programming and basic game development.
Abstract
This project focuses on the design and implementation of a collection of simple games
using Python. It provides a structured and well-organized source code repository that
helps learners understand how real-world applications are built using modular
programming techniques. The games included in this project demonstrate essential
concepts such as control flow, object movement, collision detection, scoring systems, and
graphical [Link] documentation emphasizes the organization of source code into
frontend and backend components, highlighting how user interaction and game logic are
separated for better maintainability. By examining the backend logic, users can
understand how decisions are processed, how game states are managed, and how data is
updated during [Link] the same time, the frontend part illustrates how visual
elements are displayed on the screen and how user input is captured and forwarded to the
game engine. This separation of responsibilities improves clarity and scalability of the
[Link], this project acts as both a learning toolkit and a reference implementation
for students who want to understand Python-based application development. It bridges
the gap between theoretical programming knowledge and practical software development
experience.
Project File Structure
project_word/
│ free-python-games-master/
│ │ .gitignore
│ │ .pylintrc
│ │ LICENSE
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ [Link]
│ │ .github/
│ │ │ workflows/
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ docs/
│ │ │ Makefile
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ [Link]
│ │ │ _static/
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ _templates/
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ src/
│ │ │ freegames/
│ │ │ │ __init__.py
│ │ │ │ __main__.py
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ │ │ [Link]
│ │ tests/
│ │ │ __init__.py
│ │ │ [Link]
│ │ │ test_ant.py
│ │ │ test_avoid.py
│ │ │ test_bagels.py
│ │ │ test_bounce.py
│ │ │ test_cannon.py
│ │ │ test_connect.py
│ │ │ test_crypto.py
│ │ │ test_doctest.py
│ │ │ test_fidget.py
│ │ │ test_flappy.py
│ │ │ test_guess.py
│ │ │ test_illusion.py
│ │ │ test_life.py
│ │ │ test_madlibs.py
│ │ │ test_main.py
│ │ │ test_maze.py
│ │ │ test_memory.py
│ │ │ test_minesweeper.py
│ │ │ test_pacman.py
│ │ │ test_paint.py
│ │ │ test_pong.py
│ │ │ test_rps.py
│ │ │ test_simonsays.py
│ │ │ test_snake.py
│ │ │ test_tictactoe.py
│ │ │ test_tiles.py
│ │ │ test_tron.py
│ │ │ test_typing.py
│ │ │ test_utils.py
2.1 Hardware Requirement
PROCESSOR Intel Core i3 or higher
STORAGE Minimum 200 MB free space
RAM Minimum 2 GB
HARD DISK Any standard HDD / SSD

2.2 Software Requirement


FRONT END Python Turtle Graphics / Pygame
DATA BASE Not Required
OPERATING SYSTEM Windows / Linux / macOS
SERVER SIDE Not Required
BACK END LANGUAGE Python 3.x
IDE / EDITOR VS Code / PyCharm / Any
Frontend
Source Code
Frontend File: free-python-games-master/docs/_templates/[Link]
<h3>Donate</h3>
<p>If you or your organization uses Free Games, consider donating:</p>
<p>
<a href="[Link] target="_blank">Donate to Free Python
Games</a>
</p>
Frontend File: free-python-games-master/docs/_templates/[Link]
{#
basic/[Link]
~~~~~~~~~~~~~~~~~~~

Sphinx sidebar template: local table of contents.

:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.


:license: BSD, see LICENSE for details.
#}
{%- if display_toc %}
<h3><a href="{{ pathto(master_doc) }}">{{ _('Contents') }}</a></h3>
{{ toc }}
{%- endif %}
Frontend File: free-python-games-master/docs/_templates/[Link]
{#
Modified by Grant Jenks, 2017.

basic/[Link]
~~~~~~~~~~~~~~~~~~~~

Sphinx sidebar template: quick search box.

:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.


:license: BSD, see LICENSE for details.
#}
{%- if pagename != "search" and builder != "singlehtml" %}
<div id="searchbox" style="display: none" role="search">
<h3>{{ _('Search') }}</h3>
<form class="search" action="{{ pathto('search') }}" method="get">
<div><input type="text" name="q" /></div><br>
<div><input type="submit" value="{{ _('Search') }}" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
{%- endif %}
Frontend File: free-python-games-master/docs/_templates/[Link]
<h3>Topics</h3>
{{ toctree(includehidden=theme_sidebar_includehidden,
collapse=theme_sidebar_collapse) }}
{% if theme_extra_nav_links %}
<ul>
{% for text, uri in theme_extra_nav_links.items() %}
<li><a href="{{ uri }}">{{ text }}</a></li>
{% endfor %}
</ul>
{% endif %}
Backend
Source Code
Backend File: free-python-games-master/docs/[Link]
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# [Link]

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,


# add these directories to [Link] here. If the directory is relative to the
# documentation root, use [Link] to make it absolute, like shown here.

import os
import sys
[Link](0, [Link]('..'))
import freegames

# -- Project information -----------------------------------------------------

project = 'Free Python Games'


copyright = freegames.__copyright__
author = freegames.__author__

# The short X.Y version


version = freegames.__version__
# The full version, including alpha/beta/rc tags
release = freegames.__version__

# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.


#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named '[Link].*') or your custom
# ones.
extensions = [
'[Link]',
'[Link]',
'[Link]',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.


# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.


master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation


# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'

# List of patterns, relative to source directory, that match files and


# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', '[Link]', '.DS_Store']

# The name of the Pygments (syntax highlighting) style to use.


pygments_style = None

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'logo': '[Link]',
'logo_name': True,
'logo_text_align': 'center',
'analytics_id': 'UA-19364636-2',
'show_powered_by': False,
'show_related': True,
'github_user': 'grantjenks',
'github_repo': 'free-python-games',
'github_type': 'star',
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "[Link]" will overwrite the builtin "[Link]".
html_static_path = ['_static']

# Custom sidebar templates, must be a dictionary that maps document names


# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['[Link]', '[Link]', '[Link]',
# '[Link]']``.
html_sidebars = {
'**': [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
]
}

# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.


htmlhelp_basename = 'FreePythonGamesDoc'

# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').


#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.


#
# 'preamble': '',

# Latex figure (float) alignment


#
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples


# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, '[Link]', 'Free Python Games Documentation',
'Grant Jenks', 'manual'),
]

# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples


# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'freepythongames', 'Free Python Games Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples


# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'FreePythonGames', 'Free Python Games Documentation',
author, 'FreePythonGames', 'Free Python Games for fun and learning.',
'Miscellaneous'),
]

# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.


epub_title = project

# The unique identifier of the text. This can be a ISBN number


# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.


#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['[Link]']

# -- Extension configuration -------------------------------------------------

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
Backend File: free-python-games-master/docs/[Link]
import pyautogui
import [Link] as kb
import queue
import subprocess as sp
import threading
import time

slide = 0
slides = [
'''
# Give the Gift of Python

## Grant Jenks

# 1. Python trainer for Fortune 100 companies.


# 2. Married to Chemistry teacher, father of two.
# 3. 100s of hours of 4-12th grade instruction.
'''.splitlines(),
'''

## Setup

# 1. Install Python: [Link]


# 2. Run IDLE: $ python -m [Link]
# 3. Use built-in Turtle module!
'''.splitlines(),
[
'',
'## Open the Turtle Window',
'',
'from turtle import *', 0.5,
'reset()', 0.5,
],
[
'',
'## Basic Commands',
'',
'forward(100)', 1,
'right(90)', 1,
'fd(100)', 1,
'rt(90)', 1,
'backward(-100)', 1,
'left(-90)', 1,
'forward(100)', 1,
'right(90)', 1,
'undo()', 1,
'undo()', 1,
],
[
'',
'## Loops',
'',
'reset()', 0.5,
'for each in range(5):', 0.5,
'bk(100)', 0.5,
'lt(144)', 0.5,
'', 3,
],
[
'',
'## Functions and Shapes',
'',
'def square():', 0.5,
'begin_fill()', 0.5,
'for each in range(4):', 0.5,
'forward(100)', 0.5,
'right(90)', 0.5,
-1,
'end_fill()', 0.5,
'',
'reset()', 0.5,
'square()', 3,
],
[
'',
'## Dots',
'',
'reset()', 0.5,
'help(dot)', 1,
'dot(100)', 1,
],
[
'',
'## Colors'
'',
'reset()', 0.5,
'from itertools import *', 0.5,
"colors = cycle(['red', 'green', 'blue', 'purple'])", 0.5,
'def present():', 0.5,
'for i in range(4):', 0.5,
'color(next(colors))', 0.5,
'square()', 0.5,
'left(90)', 0.5,
'',
'present()', 5,
],
[
'',
'## Locations',
'',
'reset()', 0.5,
'def line(a, b, x, y):', 0.5,
'up()', 0.5,
'goto(a, b)', 0.5,
'down()', 0.5,
'goto(x, y)', 0.5,
'',
"color('red')", 0.5,
'width(20)', 0.5,
'line(-100, -100, 0, 200)', 1,
'line(0, 200, 100, -100)', 1,
'line(100, -100, -100, -100)', 1,
],
[
'',
'## Mouse Inputs',
'',
'width(10)', 0.5,
"color('green')", 0.5,
'def tap(x, y):', 0.5,
'goto(x, y)', 0.5,
'dot(20)', 0.5,
'',
'onscreenclick(tap)', 0.5,
],
[
'',
'## Keyboard Events',
'',
'reset()', 0.5,
'width(10)', 0.5,
"onkey(lambda: fd(30), 'Up')", 0.5,
"onkey(lambda: bk(30), 'Down')", 0.5,
"onkey(lambda: lt(30), 'Left')", 0.5,
"onkey(lambda: rt(30), 'Right')", 0.5,
'listen()', 0.5,
],
[
'',
'## Animation',
'',
'hideturtle()', 0.5,
'tracer(False)', 0.5,
'running = True', 0.5,
'def draw():', 0.5,
'clear()', 0.5,
'present()', 0.5,
'update()', 0.5,
'left(1)', 0.5,
'if running:', 0.5,
'ontimer(draw, 100)',
'',
'reset()', 0.5,
'draw()', 0.5,
],
'''

## Free Python Games

# 1. Search: Free Python Games


# 2. $ python -m pip install freegames
# 3. [Link]
'''.splitlines(),
]

def worker():
global slide
while True:
key = [Link]()
if key == [Link]:
print('Typing slide', slide)
parts = slides[slide]
for part in parts:
if part == '':
[Link]('enter')
[Link](0.25)
elif part == -1:
[Link]('backspace')
elif isinstance(part, str):
[Link](part, interval=0.1)
[Link]('enter')
else:
[Link](part)
slide += 1

def ticker():
def on_press(key):
[Link](key)

with [Link](on_press=on_press) as listener:


[Link]()

def commander():
global slide
while True:
value = input()
if value == 'q':
exit()
try:
slide = int(value)
except ValueError:
pass

def main():
global inputs
idle = [Link](['python', '-m', '[Link]'])
inputs = [Link]()
work = [Link](target=worker)
[Link]()
tick = [Link](target=ticker)
[Link]()
cmdr = [Link](target=commander)
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

if __name__ == '__main__':
main()
Backend File: free-python-games-master/src/freegames/__init__.py
"""Free Python Games

Free Python Games is an Apache2 licensed collection of free Python games


intended for education and fun. The games are written in simple Python code and
designed for experimentation and changes. Simplified versions of several
classic arcade games are included.

Python is one of the top-five most popular programming languages in the world
and available for free from [Link]. Python includes an extensive
Standard Library distributed with your installation. The Standard Library has a
module called Turtle which is a popular way to introduce programming to
kids. Turtle was part of the original Logo programming language developed by
Wally Feurzig and Seymour Papert in 1966. All of the games in Free Python Games
are implemented using Python and its Turtle module.

Starting in 2012, Free Python Games began as an after school program to teach
programming to inner-city youth. The goal was to have fun as much as it was to
learn. Since then the games have been improved and used in a variety of
settings ranging from classrooms to summer day-camps.

The games run anywhere Python can be installed which includes desktop computers
running Windows, Mac OS, or Linux and older or low-power hardware such as the
Raspberry Pi. Kids across the United States in grades 6th-12th have enjoyed
learning about topics such as encryption and projectile motion through games.

Each game is entirely independent from the others and includes comments along
with a list of exercises to work through with students. Creativity and
flexibility is important. There is no right or wrong way to implement a new
feature or behavior! You never know which games students will engage with best.

Free Python Games supports a command-line interface (CLI). Help for the CLI is
available using::

$ python3 -m freegames --help

The CLI supports three commands: list, copy, and show. For a list of all games
run::

$ python3 -m freegames list

Any of the listed games may be played by executing the Python module from the
command-line. To reference the Python module, combine "freegames" with the name
of the game. For example, to play the "snake" game run::

$ python3 -m [Link]

Games can be modified by copying their source code. The copy command will
create a Python file in your local directory which you can edit. For example,
to copy and play the "snake" game run::

$ python3 -m freegames copy snake


$ python3 [Link]
Python includes a built-in text editor named IDLE which can also execute Python
code. To launch the editor and make changes to the "snake" game run::

$ python3 -m [Link] [Link]


"""

from .utils import floor, line, path, square, vector

__all__ = ['floor', 'line', 'path', 'square', 'vector']

__title__ = 'freegames'
__version__ = '2.5.3'
__author__ = 'Grant Jenks'
__license__ = 'Apache 2.0'
__copyright__ = '2017-2023, Grant Jenks'
Backend File: free-python-games-master/src/freegames/__main__.py
"""Free Games CLI
"""

import argparse
import os
import runpy

def game_file(name):
"""Return True if filename represents a game."""
return (
[Link]('.py')
and not [Link]('__')
and name != '[Link]'
)

def main():
directory = [Link]([Link](__file__))
contents = [Link](directory)
games = sorted(name[:-3] for name in contents if game_file(name))

parser = [Link](
prog='freegames',
description='Free Python Games',
epilog='Copyright 2023 Grant Jenks',
)
subparsers = parser.add_subparsers(dest='command', help='sub-command help')
[Link] = True

subparsers.add_parser('list', help='list games')

parser_play = subparsers.add_parser('play', help='play free Python games')


parser_play.add_argument('game', choices=games, help='game name')

parser_show = subparsers.add_parser('show', help='show game source code')


parser_show.add_argument('game', choices=games, help='game name')

parser_copy = subparsers.add_parser('copy', help='copy game source code')


parser_copy.add_argument('game', choices=games, help='game name')
parser_copy.add_argument(
'--force',
action='store_true',
help='overwrite existing file',
)

args = parser.parse_args()

if [Link] == 'list':
for game in games:
print(game)
elif [Link] == 'play':
runpy.run_module('freegames.' + [Link])
elif [Link] == 'show':
with open([Link](directory, [Link] + '.py')) as reader:
print([Link]())
else:
assert [Link] == 'copy'
filename = [Link] + '.py'

with open([Link](directory, filename)) as reader:


text = [Link]()

cwd = [Link]()
path = [Link](cwd, filename)

if [Link] or not [Link](path):


with open(path, 'w') as writer:
[Link](text)
else:
print('ERROR: File already exists. Specify --force to overwrite.')

if __name__ == '__main__':
main() # pragma: no cover
Backend File: free-python-games-master/src/freegames/[Link]
"""Ant, simple animation demo.

Exercises

1. Wrap ant around screen boundaries.


2. Make the ant leave a trail.
3. Change the ant color based on position.
Hint: colormode(255); color(0, 100, 200)
"""

from random import *


from turtle import *

from freegames import vector

ant = vector(0, 0)
aim = vector(2, 0)

def wrap(value):
"""Wrap value around -200 and 200."""
return value # TODO

def draw():
"""Move ant and draw screen."""
[Link](aim)
ant.x = wrap(ant.x)
ant.y = wrap(ant.y)

[Link](random() - 0.5)
[Link](random() * 10 - 5)

clear()
goto(ant.x, ant.y)
dot(4)

ontimer(draw, 100)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
up()
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Avoid, classic arcade game.

Exercises

1. Display the duration of the game.


2. Vary the size of the bombs.
3. Vary the speed of the bombs.
"""

from random import *


from turtle import *

from freegames import vector

north, south = vector(0, 4), vector(0, -4)


east, west = vector(4, 0), vector(-4, 0)
options = north, south, east, west

player = vector(0, 0)
aim = choice(options).copy()
bombs = []
speeds = []

def inside(point):
"""Return True if point on screen."""
return -200 < point.x < 200 and -200 < point.y < 200

def draw(alive):
"""Draw screen objects."""
clear()
goto(player.x, player.y)
color = 'blue' if alive else 'red'
dot(10, color)
for bomb in bombs:
goto(bomb.x, bomb.y)
dot(20, 'black')
update()

def move():
"""Update player and bomb positions."""
[Link](aim)

for bomb, speed in zip(bombs, speeds):


[Link](speed)

if randrange(10) == 0:
speed = choice(options).copy()
offset = randrange(-199, 200)

if speed == north:
bomb = vector(offset, -199)
if speed == south:
bomb = vector(offset, 199)
if speed == east:
bomb = vector(-199, offset)
if speed == west:
bomb = vector(199, offset)

[Link](bomb)
[Link](speed)

for index in reversed(range(len(bombs))):


bomb = bombs[index]
if not inside(bomb):
del bombs[index]
del speeds[index]

if not inside(player):
draw(False)
return

for bomb in bombs:


if abs(bomb - player) < 15:
draw(False)
return

draw(True)
ontimer(move, 50)

setup(420, 420, 370, 0)


hideturtle()
up()
tracer(False)
listen()
onkey(lambda: [Link](north), 'Up')
onkey(lambda: [Link](south), 'Down')
onkey(lambda: [Link](east), 'Right')
onkey(lambda: [Link](west), 'Left')
move()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Bagels, a number puzzle game.

Exercises:

1. Can you guess the number?


2. How much harder is 6 digits? Do you need more guesses?
3. What's the maximum number of digits we could support?

Adapted from code in [Link]


"""

from random import sample, shuffle

digits = 3
guesses = 10

print('I am thinking of a', digits, 'digit number.')


print('Try to guess what it is.')
print('Here are some clues:')
print('When I say: That means:')
print(' pico One digit is correct but in the wrong position.')
print(' fermi One digit is correct and in the right position.')
print(' bagels No digit is correct.')
print('There are no repeated digits in the number.')

# Create a random number.

letters = sample('0123456789', digits)

if letters[0] == '0':
[Link]()

number = ''.join(letters)

print('I have thought up a number.')


print('You have', guesses, 'guesses to get it.')

counter = 1

while True:
print('Guess #', counter)
guess = input()

if len(guess) != digits:
print('Wrong number of digits. Try again!')
continue

# Create the clues.

clues = []

for index in range(digits):


if guess[index] == number[index]:
[Link]('fermi')
elif guess[index] in number:
[Link]('pico')

shuffle(clues)

if len(clues) == 0:
print('bagels')
else:
print(' '.join(clues))

counter += 1

if guess == number:
print('You got it!')
break

if counter > guesses:


print('You ran out of guesses. The answer was', number)
break
Backend File: free-python-games-master/src/freegames/[Link]
"""Bounce, a simple animation demo.

Exercises

1. Make the ball speed up and down.


2. Change how the ball bounces when it hits a wall.
3. Make the ball leave a trail.
4. Change the ball color based on position.
Hint: colormode(255); color(0, 100, 200)
"""

from random import *


from turtle import *

from freegames import vector

def value():
"""Randomly generate value between (-5, -3) or (3, 5)."""
return (3 + random() * 2) * choice([1, -1])

ball = vector(0, 0)
aim = vector(value(), value())

def draw():
"""Move ball and draw game."""
[Link](aim)

x = ball.x
y = ball.y

if x < -200 or x > 200:


aim.x = -aim.x

if y < -200 or y > 200:


aim.y = -aim.y

clear()
goto(x, y)
dot(10)

ontimer(draw, 50)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
up()
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Cannon, hitting targets with projectiles.

Exercises

1. Keep score by counting target hits.


2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.
"""

from random import randrange


from turtle import *

from freegames import vector

ball = vector(-200, -200)


speed = vector(0, 0)
targets = []

def tap(x, y):


"""Respond to screen tap."""
if not inside(ball):
ball.x = -199
ball.y = -199
speed.x = (x + 200) / 25
speed.y = (y + 200) / 25

def inside(xy):
"""Return True if xy within screen."""
return -200 < xy.x < 200 and -200 < xy.y < 200

def draw():
"""Draw ball and targets."""
clear()

for target in targets:


goto(target.x, target.y)
dot(20, 'blue')

if inside(ball):
goto(ball.x, ball.y)
dot(6, 'red')

update()

def move():
"""Move ball and targets."""
if randrange(40) == 0:
y = randrange(-150, 150)
target = vector(200, y)
[Link](target)

for target in targets:


target.x -= 0.5

if inside(ball):
speed.y -= 0.35
[Link](speed)

dupe = [Link]()
[Link]()

for target in dupe:


if abs(target - ball) > 13:
[Link](target)

draw()

for target in targets:


if not inside(target):
return

ontimer(move, 50)

setup(420, 420, 370, 0)


hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Connect Four

Exercises

1. Change the colors.


2. Draw squares instead of circles for open spaces.
3. Add logic to detect a full row.
4. Create a random computer player.
5. How would you detect a winner?
"""

from turtle import *

from freegames import line

turns = {'red': 'yellow', 'yellow': 'red'}


state = {'player': 'yellow', 'rows': [0] * 8}

def grid():
"""Draw Connect Four grid."""
bgcolor('light blue')

for x in range(-150, 200, 50):


line(x, -200, x, 200)

for x in range(-175, 200, 50):


for y in range(-175, 200, 50):
up()
goto(x, y)
dot(40, 'white')

update()

def tap(x, y):


"""Draw red or yellow circle in tapped row."""
player = state['player']
rows = state['rows']

row = int((x + 200) // 50)


count = rows[row]

x = ((x + 200) // 50) * 50 - 200 + 25


y = count * 50 - 200 + 25

up()
goto(x, y)
dot(40, player)
update()

rows[row] = count + 1
state['player'] = turns[player]
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(tap)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Crypto: tool for encrypting and decrypting messages.

Exercises

1. Review 'ord' and 'chr' functions and letter-to-number mapping.


2. Explain what happens if you use key 26.
3. Find a way to decode a message without a key.
4. Encrypt numbers.
5. Make the encryption harder to decode.

Adapted from code in [Link]


"""

def encrypt(message, key):


"""Encrypt message with key."""
result = ''

# Iterate letters in message and encrypt each individually.

for letter in message:


if [Link]():

# Letters are numbered like so:


# A, B, C - Z is 65, 66, 67 - 90
# a, b, c - z is 97, 98, 99 - 122

num = ord(letter)

if [Link]():
base = ord('A')
else:
assert [Link]()
base = ord('a')

# The encryption equation:

num = (num - base + key) % 26 + base

result += chr(num)

elif [Link]():

# TODO: Encrypt digits.


result += letter

else:
result += letter

return result

def decrypt(message, key):


"""Decrypt message with key."""
return encrypt(message, -key)

def decode(message):
"""Decode message without key."""
pass # TODO

def get_key():
"""Get key from user."""
try:
text = input('Enter a key (1 - 25): ')
key = int(text)
return key
except:
print('Invalid key. Using key: 0.')
return 0

print('Do you wish to encrypt, decrypt, or decode a message?')


choice = input()

if choice == 'encrypt':
phrase = input('Message: ')
code = get_key()
print('Encrypted message:', encrypt(phrase, code))
elif choice == 'decrypt':
phrase = input('Message: ')
code = get_key()
print('Decrypted message:', decrypt(phrase, code))
elif choice == 'decode':
phrase = input('Message: ')
print('Decoding message:')
decode(phrase)
else:
print('Error: Unrecognized Command')
Backend File: free-python-games-master/src/freegames/[Link]
"""Fidget, inspired by fidget spinners.

Exercises

1. Change the spinner pattern.


2. Respond to mouse clicks.
3. Change its acceleration.
4. Make it go forwards and backwards.
"""

from turtle import *

state = {'turn': 0}

def spinner():
"""Draw fidget spinner."""
clear()
angle = state['turn'] / 10
right(angle)
forward(100)
dot(120, 'red')
back(100)
right(120)
forward(100)
dot(120, 'green')
back(100)
right(120)
forward(100)
dot(120, 'blue')
back(100)
right(120)
update()

def animate():
"""Animate fidget spinner."""
if state['turn'] > 0:
state['turn'] -= 1

spinner()
ontimer(animate, 20)

def flick():
"""Flick fidget spinner."""
state['turn'] += 10

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
width(20)
onkey(flick, 'space')
listen()
animate()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Flappy, game inspired by Flappy Bird.

Exercises

1. Keep score.
2. Vary the speed.
3. Vary the size of the balls.
4. Allow the bird to move forward and back.
"""

from random import *


from turtle import *

from freegames import vector

bird = vector(0, 0)
balls = []

def tap(x, y):


"""Move bird up in response to screen tap."""
up = vector(0, 30)
[Link](up)

def inside(point):
"""Return True if point on screen."""
return -200 < point.x < 200 and -200 < point.y < 200

def draw(alive):
"""Draw screen objects."""
clear()

goto(bird.x, bird.y)

if alive:
dot(10, 'green')
else:
dot(10, 'red')

for ball in balls:


goto(ball.x, ball.y)
dot(20, 'black')

update()

def move():
"""Update object positions."""
bird.y -= 5

for ball in balls:


ball.x -= 3

if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
[Link](ball)

while len(balls) > 0 and not inside(balls[0]):


[Link](0)

if not inside(bird):
draw(False)
return

for ball in balls:


if abs(ball - bird) < 15:
draw(False)
return

draw(True)
ontimer(move, 50)

setup(420, 420, 370, 0)


hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Guess a number within a range.

Exercises

1. Change the range to be from 0 to 1,000,000.


2. Can you still guess the number?
3. Print the number of guesses made.
4. Limit the number of guesses to the minimum required.
"""

from random import randint

start = 1
end = 100
value = randint(start, end)

# print(value)
print("I'm thinking of a number between", start, 'and', end)

guess = None

while guess != value:


text = input('Guess the number: ')
guess = int(text)

if guess < value:


print('Higher.')
elif guess > value:
print('Lower.')

print('Congratulations! You guessed the right answer:', value)


Backend File: free-python-games-master/src/freegames/[Link]
"""Illusion

Exercises:

1. Change the size of the squares.


2. Change the number of rows and lines.
"""

from itertools import cycle


from turtle import *

from freegames import line, square

size = 25

def draw_row(x, y):


for i in range(0, 10):
offset = x + (i * size * 2)
square(offset, y, size, 'black')

def draw_rows():
offsets = [-200, -190, -180, -190]
pairs = zip(cycle(offsets), range(150, -176, -25))
for offset, y in pairs:
draw_row(offset, y)

def draw_lines():
x = -200
y = 150
for i in range(0, 14):
line(x, y - i * size, x + 16 * size, y - i * size)

setup(420, 400, 30, 0)


hideturtle()
tracer(False)
listen()
draw_rows()
draw_lines()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Game of Life simulation.

Conway's game of life is a classic cellular automation created in 1970 by John


Conway. [Link]

Exercises

1. Can you identify any Still Lifes, Oscillators, or Spaceships?


2. How can you make the simulation faster? Or bigger?
3. How would you modify the initial state?
4. Try changing the rules of life :)
"""

from random import choice


from turtle import *

from freegames import square

cells = {}

def initialize():
"""Randomly initialize the cells."""
for x in range(-200, 200, 10):
for y in range(-200, 200, 10):
cells[x, y] = False

for x in range(-50, 50, 10):


for y in range(-50, 50, 10):
cells[x, y] = choice([True, False])

def step():
"""Compute one step in the Game of Life."""
neighbors = {}

for x in range(-190, 190, 10):


for y in range(-190, 190, 10):
count = -cells[x, y]
for h in [-10, 0, 10]:
for v in [-10, 0, 10]:
count += cells[x + h, y + v]
neighbors[x, y] = count

for cell, count in [Link]():


if cells[cell]:
if count < 2 or count > 3:
cells[cell] = False
elif count == 3:
cells[cell] = True

def draw():
"""Draw all the squares."""
step()
clear()
for (x, y), alive in [Link]():
color = 'green' if alive else 'black'
square(x, y, 10, color)
update()
ontimer(draw, 100)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
initialize()
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Mad Libs: Funny Story Creation Game

Exercises:

1. How to replace the story?


2. How load the story and from a file?
3. How to add additional parts of speech?
"""

# The quick brown fox jumps over the lazy dog.


template = 'The |1| |2| |3| |4| over the |5| |6|.'
parts = {
'1': 'adjective',
'2': 'adjective',
'3': 'noun',
'4': 'verb',
'5': 'adjective',
'6': 'noun',
}

chunks = []

for chunk in [Link]('|'):


if chunk in parts:
description = parts[chunk]
prompt = 'Enter [{}]: '.format(description)
word = input(prompt)
[Link](word)
else:
[Link](chunk)

print('=' * 80)
story = ''.join(chunks)
print(story)
Backend File: free-python-games-master/src/freegames/[Link]
"""Maze, move from one side to another.

Excercises

1. Keep score by counting taps.


2. Make the maze harder.
3. Generate the same maze twice.
"""

from random import random


from turtle import *

from freegames import line

def draw():
"""Draw maze."""
color('black')
width(5)

for x in range(-200, 200, 40):


for y in range(-200, 200, 40):
if random() > 0.5:
line(x, y, x + 40, y + 40)
else:
line(x, y + 40, x + 40, y)

update()

def tap(x, y):


"""Draw line and dot for screen tap."""
if abs(x) > 198 or abs(y) > 198:
up()
else:
down()

width(2)
color('red')
goto(x, y)
dot(4)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
draw()
onscreenclick(tap)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Memory, puzzle game of number pairs.

Exercises:

1. Count and print how many taps occur.


2. Decrease the number of tiles to a 4x4 grid.
3. Detect when all tiles are revealed.
4. Center single-digit tile.
5. Use letters instead of tiles.
"""

from random import *


from turtle import *

from freegames import path

car = path('[Link]')
tiles = list(range(32)) * 2
state = {'mark': None}
hide = [True] * 64

def square(x, y):


"""Draw white square with black outline at (x, y)."""
up()
goto(x, y)
down()
color('black', 'white')
begin_fill()
for count in range(4):
forward(50)
left(90)
end_fill()

def index(x, y):


"""Convert (x, y) coordinates to tiles index."""
return int((x + 200) // 50 + ((y + 200) // 50) * 8)

def xy(count):
"""Convert tiles count to (x, y) coordinates."""
return (count % 8) * 50 - 200, (count // 8) * 50 - 200

def tap(x, y):


"""Update mark and hidden tiles based on tap."""
spot = index(x, y)
mark = state['mark']

if mark is None or mark == spot or tiles[mark] != tiles[spot]:


state['mark'] = spot
else:
hide[spot] = False
hide[mark] = False
state['mark'] = None

def draw():
"""Draw image and tiles."""
clear()
goto(0, 0)
shape(car)
stamp()

for count in range(64):


if hide[count]:
x, y = xy(count)
square(x, y)

mark = state['mark']

if mark is not None and hide[mark]:


x, y = xy(mark)
up()
goto(x + 2, y)
color('black')
write(tiles[mark], font=('Arial', 30, 'normal'))

update()
ontimer(draw, 100)

shuffle(tiles)
setup(420, 420, 370, 0)
addshape(car)
hideturtle()
tracer(False)
onscreenclick(tap)
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Minesweeper

Exercises

1. What does the `seed(0)` function call do?


2. Change the number of bombs on the grid.
3. Change the size of the grid.
"""

from random import randrange, seed


from turtle import *

from freegames import floor, square

seed(0)
bombs = {}
shown = {}
counts = {}

def initialize():
"""Initialize `bombs`, `counts`, and `shown` grids."""
for x in range(-250, 250, 50):
for y in range(-250, 250, 50):
bombs[x, y] = False
shown[x, y] = False
counts[x, y] = -1

for count in range(8):


x = randrange(-200, 200, 50)
y = randrange(-200, 200, 50)
bombs[x, y] = True

for x in range(-200, 200, 50):


for y in range(-200, 200, 50):
total = 0
for i in (-50, 0, 50):
for j in (-50, 0, 50):
total += bombs[x + i, y + j]
counts[x, y] = total

def stamp(x, y, text):


"""Display `text` at coordinates `x` and `y`."""
square(x, y, 50, 'white')
color('black')
write(text, font=('Arial', 50, 'normal'))

def draw():
"""Draw the initial board grid."""
for x in range(-200, 200, 50):
for y in range(-200, 200, 50):
stamp(x, y, '?')

def end():
"""Draw the bombs as X's on the grid."""
for x in range(-200, 200, 50):
for y in range(-200, 200, 50):
if bombs[x, y]:
stamp(x, y, 'X')

def tap(x, y):


"""Respond to screen click at `x` and `y` coordinates."""
x = floor(x, 50)
y = floor(y, 50)

if bombs[x, y]:
end()
return

pairs = [(x, y)]

while pairs:
x, y = [Link]()
stamp(x, y, counts[x, y])
shown[x, y] = True

if counts[x, y] == 0:
for i in (-50, 0, 50):
for j in (-50, 0, 50):
pair = x + i, y + j
if not shown[pair]:
[Link](pair)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
initialize()
draw()
onscreenclick(tap)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Pacman, classic arcade game.

Exercises

1. Change the board.


2. Change the number of ghosts.
3. Change where pacman starts.
4. Make the ghosts faster/slower.
5. Make the ghosts smarter.
"""

from random import choice


from turtle import *

from freegames import floor, vector

state = {'score': 0}
path = Turtle(visible=False)
writer = Turtle(visible=False)
aim = vector(5, 0)
pacman = vector(-40, -80)
ghosts = [
[vector(-180, 160), vector(5, 0)],
[vector(-180, -160), vector(0, 5)],
[vector(100, 160), vector(0, -5)],
[vector(100, -160), vector(-5, 0)],
]
# fmt: off
tiles = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
# fmt: on
def square(x, y):
"""Draw square using path at (x, y)."""
[Link]()
[Link](x, y)
[Link]()
path.begin_fill()

for count in range(4):


[Link](20)
[Link](90)

path.end_fill()

def offset(point):
"""Return offset of point in tiles."""
x = (floor(point.x, 20) + 200) / 20
y = (180 - floor(point.y, 20)) / 20
index = int(x + y * 20)
return index

def valid(point):
"""Return True if point is valid in tiles."""
index = offset(point)

if tiles[index] == 0:
return False

index = offset(point + 19)

if tiles[index] == 0:
return False

return point.x % 20 == 0 or point.y % 20 == 0

def world():
"""Draw world using path."""
bgcolor('black')
[Link]('blue')

for index in range(len(tiles)):


tile = tiles[index]

if tile > 0:
x = (index % 20) * 20 - 200
y = 180 - (index // 20) * 20
square(x, y)

if tile == 1:
[Link]()
[Link](x + 10, y + 10)
[Link](2, 'white')
def move():
"""Move pacman and all ghosts."""
[Link]()
[Link](state['score'])

clear()

if valid(pacman + aim):
[Link](aim)

index = offset(pacman)

if tiles[index] == 1:
tiles[index] = 2
state['score'] += 1
x = (index % 20) * 20 - 200
y = 180 - (index // 20) * 20
square(x, y)

up()
goto(pacman.x + 10, pacman.y + 10)
dot(20, 'yellow')

for point, course in ghosts:


if valid(point + course):
[Link](course)
else:
options = [
vector(5, 0),
vector(-5, 0),
vector(0, 5),
vector(0, -5),
]
plan = choice(options)
course.x = plan.x
course.y = plan.y

up()
goto(point.x + 10, point.y + 10)
dot(20, 'red')

update()

for point, course in ghosts:


if abs(pacman - point) < 20:
return

ontimer(move, 100)

def change(x, y):


"""Change pacman aim if valid."""
if valid(pacman + vector(x, y)):
aim.x = x
aim.y = y

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
[Link](160, 160)
[Link]('white')
[Link](state['score'])
listen()
onkey(lambda: change(5, 0), 'Right')
onkey(lambda: change(-5, 0), 'Left')
onkey(lambda: change(0, 5), 'Up')
onkey(lambda: change(0, -5), 'Down')
world()
move()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Paint, for drawing shapes.

Exercises

1. Add a color.
2. Complete circle.
3. Complete rectangle.
4. Complete triangle.
5. Add width parameter.
"""

from turtle import *

from freegames import vector

def line(start, end):


"""Draw line from start to end."""
up()
goto(start.x, start.y)
down()
goto(end.x, end.y)

def square(start, end):


"""Draw square from start to end."""
up()
goto(start.x, start.y)
down()
begin_fill()

for count in range(4):


forward(end.x - start.x)
left(90)

end_fill()

def circle(start, end):


"""Draw circle from start to end."""
pass # TODO

def rectangle(start, end):


"""Draw rectangle from start to end."""
pass # TODO

def triangle(start, end):


"""Draw triangle from start to end."""
pass # TODO
def tap(x, y):
"""Store starting point or draw shape."""
start = state['start']

if start is None:
state['start'] = vector(x, y)
else:
shape = state['shape']
end = vector(x, y)
shape(start, end)
state['start'] = None

def store(key, value):


"""Store value in state at key."""
state[key] = value

state = {'start': None, 'shape': line}


setup(420, 420, 370, 0)
onscreenclick(tap)
listen()
onkey(undo, 'u')
onkey(lambda: color('black'), 'K')
onkey(lambda: color('white'), 'W')
onkey(lambda: color('green'), 'G')
onkey(lambda: color('blue'), 'B')
onkey(lambda: color('red'), 'R')
onkey(lambda: store('shape', line), 'l')
onkey(lambda: store('shape', square), 's')
onkey(lambda: store('shape', circle), 'c')
onkey(lambda: store('shape', rectangle), 'r')
onkey(lambda: store('shape', triangle), 't')
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Pong, classic arcade game.

Exercises

1. Change the colors.


2. What is the frame rate? Make it faster or slower.
3. Change the speed of the ball.
4. Change the size of the paddles.
5. Change how the ball bounces off walls.
6. How would you add a computer player?
6. Add a second ball.
"""

from random import choice, random


from turtle import *

from freegames import vector

def value():
"""Randomly generate value between (-5, -3) or (3, 5)."""
return (3 + random() * 2) * choice([1, -1])

ball = vector(0, 0)
aim = vector(value(), value())
state = {1: 0, 2: 0}

def move(player, change):


"""Move player position by change."""
state[player] += change

def rectangle(x, y, width, height):


"""Draw rectangle at (x, y) with given width and height."""
up()
goto(x, y)
down()
begin_fill()
for count in range(2):
forward(width)
left(90)
forward(height)
left(90)
end_fill()

def draw():
"""Draw game and move pong ball."""
clear()
rectangle(-200, state[1], 10, 50)
rectangle(190, state[2], 10, 50)
[Link](aim)
x = ball.x
y = ball.y

up()
goto(x, y)
dot(10)
update()

if y < -200 or y > 200:


aim.y = -aim.y

if x < -185:
low = state[1]
high = state[1] + 50

if low <= y <= high:


aim.x = -aim.x
else:
return

if x > 185:
low = state[2]
high = state[2] + 50

if low <= y <= high:


aim.x = -aim.x
else:
return

ontimer(draw, 50)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
listen()
onkey(lambda: move(1, 20), 'w')
onkey(lambda: move(1, -20), 's')
onkey(lambda: move(2, 20), 'i')
onkey(lambda: move(2, -20), 'k')
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Rock, Paper, Scissors

The game is played in a series as follows:

1. Player chooses "r" for rock, "p" for paper, or "s" for scissors.
2. The computer will also choose rock, paper, or scissors.
3. The result will either be a win, loss, or tie:
a. Rock crushes scissors.
b. Scissors cuts paper.
c. Paper covers rock.

First to score 5 points wins the series!


"""
# Exercises:
#
# 1. Create a strategy to rotate through 'r', 'p', and 's' in a cycle.
# 2. Create a strategy to do the same as the last computer choice.
# 3. Create a new strategy of your own.

import random

beats = {'r': 's', 'p': 'r', 's': 'p'}


loses = {value: key for key, value in [Link]()}
state = {'player': 0, 'computer': 0, 'ties': 0}
guesses = []
default = [Link]('rps')

def always_same():
return default

def random_strategy():
return [Link]('rps')

def beat_last():
if not guesses:
return default
last, _ = guesses[-1]
return loses[last]

strategies = [always_same, random_strategy, beat_last]


strategy = [Link](strategies)

def get_option():
while True:
choice = input('Enter "r" for rock, "p" for paper, "s" for scissors: ')
if choice not in beats:
print('Invalid choice.')
continue
return choice

print(__doc__)

while True:
player = get_option()
computer = strategy()
guess = (player, computer)
[Link](guess)

print('Player chooses:', player)


print('Computer chooses:', computer)

if player == computer:
state['ties'] += 1
print('Tie!')
elif beats[player] == computer:
state['player'] += 1
print('Player wins!')
else:
state['computer'] += 1
print('Computer wins!')

print()
print('Player points:', state['player'])
print('Computer points:', state['computer'])
print()

if state['player'] == 5:
print('PLAYER WINS!')
break

if state['computer'] == 5:
print('COMPUTER WINS!')
break

print('Computer strategy:', strategy.__name__)


Backend File: free-python-games-master/src/freegames/[Link]
"""Simon Says

Exercises

1. Speed up tile flash rate.


2. Add more tiles.
"""

from random import choice


from time import sleep
from turtle import *

from freegames import floor, square, vector

pattern = []
guesses = []
tiles = {
vector(0, 0): ('red', 'dark red'),
vector(0, -200): ('blue', 'dark blue'),
vector(-200, 0): ('green', 'dark green'),
vector(-200, -200): ('yellow', 'khaki'),
}

def grid():
"""Draw grid of tiles."""
square(0, 0, 200, 'dark red')
square(0, -200, 200, 'dark blue')
square(-200, 0, 200, 'dark green')
square(-200, -200, 200, 'khaki')
update()

def flash(tile):
"""Flash tile in grid."""
glow, dark = tiles[tile]
square(tile.x, tile.y, 200, glow)
update()
sleep(0.5)
square(tile.x, tile.y, 200, dark)
update()
sleep(0.5)

def grow():
"""Grow pattern and flash tiles."""
tile = choice(list(tiles))
[Link](tile)

for tile in pattern:


flash(tile)

print('Pattern length:', len(pattern))


[Link]()

def tap(x, y):


"""Respond to screen tap."""
onscreenclick(None)
x = floor(x, 200)
y = floor(y, 200)
tile = vector(x, y)
index = len(guesses)

if tile != pattern[index]:
exit()

[Link](tile)
flash(tile)

if len(guesses) == len(pattern):
grow()

onscreenclick(tap)

def start(x, y):


"""Start game."""
grow()
onscreenclick(tap)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
grid()
onscreenclick(start)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Snake, classic arcade game.

Exercises

1. How do you make the snake faster or slower?


2. How can you make the snake go around the edges?
3. How would you move the food?
4. Change the snake to respond to mouse clicks.
"""

from random import randrange


from turtle import *

from freegames import square, vector

food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)

def change(x, y):


"""Change snake direction."""
aim.x = x
aim.y = y

def inside(head):
"""Return True if head inside boundaries."""
return -200 < head.x < 190 and -200 < head.y < 190

def move():
"""Move snake forward one segment."""
head = snake[-1].copy()
[Link](aim)

if not inside(head) or head in snake:


square(head.x, head.y, 9, 'red')
update()
return

[Link](head)

if head == food:
print('Snake:', len(snake))
food.x = randrange(-15, 15) * 10
food.y = randrange(-15, 15) * 10
else:
[Link](0)

clear()

for body in snake:


square(body.x, body.y, 9, 'black')

square(food.x, food.y, 9, 'green')


update()
ontimer(move, 100)

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
listen()
onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
move()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Tic Tac Toe

Exercises

1. Give the X and O a different color and width.


2. What happens when someone taps a taken spot?
3. How would you detect when someone has won?
4. How could you create a computer player?
"""

from turtle import *

from freegames import line

def grid():
"""Draw tic-tac-toe grid."""
line(-67, 200, -67, -200)
line(67, 200, 67, -200)
line(-200, -67, 200, -67)
line(-200, 67, 200, 67)

def drawx(x, y):


"""Draw X player."""
line(x, y, x + 133, y + 133)
line(x, y + 133, x + 133, y)

def drawo(x, y):


"""Draw O player."""
up()
goto(x + 67, y + 5)
down()
circle(62)

def floor(value):
"""Round value down to grid with square size 133."""
return ((value + 200) // 133) * 133 - 200

state = {'player': 0}
players = [drawx, drawo]

def tap(x, y):


"""Draw X or O in tapped square."""
x = floor(x)
y = floor(y)
player = state['player']
draw = players[player]
draw(x, y)
update()
state['player'] = not player

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
grid()
update()
onscreenclick(tap)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Tiles, number swapping game.

Exercises

1. Track a score by the number of tile moves.


2. Permit diagonal squares as neighbors.
3. Respond to arrow keys instead of mouse clicks.
4. Make the grid bigger.
"""

from random import *


from turtle import *

from freegames import floor, vector

tiles = {}
neighbors = [
vector(100, 0),
vector(-100, 0),
vector(0, 100),
vector(0, -100),
]

def load():
"""Load tiles and scramble."""
count = 1

for y in range(-200, 200, 100):


for x in range(-200, 200, 100):
mark = vector(x, y)
tiles[mark] = count
count += 1

tiles[mark] = None

for count in range(1000):


neighbor = choice(neighbors)
spot = mark + neighbor

if spot in tiles:
number = tiles[spot]
tiles[spot] = None
tiles[mark] = number
mark = spot

def square(mark, number):


"""Draw white square with black outline and number."""
up()
goto(mark.x, mark.y)
down()
color('black', 'white')
begin_fill()
for count in range(4):
forward(99)
left(90)
end_fill()

if number is None:
return
elif number < 10:
forward(20)

write(number, font=('Arial', 60, 'normal'))

def tap(x, y):


"""Swap tile and empty square."""
x = floor(x, 100)
y = floor(y, 100)
mark = vector(x, y)

for neighbor in neighbors:


spot = mark + neighbor

if spot in tiles and tiles[spot] is None:


number = tiles[mark]
tiles[spot] = number
square(spot, number)
tiles[mark] = None
square(mark, None)

def draw():
"""Draw all tiles."""
for mark in tiles:
square(mark, tiles[mark])
update()

setup(420, 420, 370, 0)


hideturtle()
tracer(False)
load()
draw()
onscreenclick(tap)
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Tron, classic arcade game.

Exercises

1. Make the tron players faster/slower.


2. Stop a tron player from running into itself.
3. Allow the tron player to go around the edge of the screen.
4. How would you create a computer player?
"""

from turtle import *

from freegames import square, vector

p1xy = vector(-100, 0)
p1aim = vector(4, 0)
p1body = set()

p2xy = vector(100, 0)
p2aim = vector(-4, 0)
p2body = set()

def inside(head):
"""Return True if head inside screen."""
return -200 < head.x < 200 and -200 < head.y < 200

def draw():
"""Advance players and draw game."""
[Link](p1aim)
p1head = [Link]()

[Link](p2aim)
p2head = [Link]()

if not inside(p1head) or p1head in p2body:


print('Player blue wins!')
return

if not inside(p2head) or p2head in p1body:


print('Player red wins!')
return

[Link](p1head)
[Link](p2head)

square(p1xy.x, p1xy.y, 3, 'red')


square(p2xy.x, p2xy.y, 3, 'blue')
update()
ontimer(draw, 50)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: [Link](90), 'a')
onkey(lambda: [Link](-90), 'd')
onkey(lambda: [Link](90), 'j')
onkey(lambda: [Link](-90), 'l')
draw()
done()
Backend File: free-python-games-master/src/freegames/[Link]
"""Game to practice typing.

Exercises

1. Change the speed of letters.


2. Add uppercase letters.
3. Make the game faster as the score gets higher.
4. Make the letters more frequent as the score gets higher.
"""

from random import choice, randrange


from string import ascii_lowercase
from turtle import *

from freegames import vector

targets = []
letters = []
score = 0

def inside(point):
"""Return True if point on screen."""
return -200 < point.x < 200 and -200 < point.y < 200

def draw():
"""Draw letters."""
clear()

for target, letter in zip(targets, letters):


goto(target.x, target.y)
write(letter, align='center', font=('Consolas', 20, 'normal'))

update()

def move():
"""Move letters."""
if randrange(20) == 0:
x = randrange(-150, 150)
target = vector(x, 200)
[Link](target)
letter = choice(ascii_lowercase)
[Link](letter)

for target in targets:


target.y -= 1

draw()

for target in targets:


if not inside(target):
return

ontimer(move, 100)

def press(key):
"""Press key."""
global score

if key in letters:
score += 1
pos = [Link](key)
del targets[pos]
del letters[pos]
else:
score -= 1

print('Score:', score)

setup(420, 420, 370, 0)


hideturtle()
up()
tracer(False)
listen()
for letter in ascii_lowercase:
onkey(lambda letter=letter: press(letter), letter)
move()
done()

You might also like