Interactive Python Games for Learning
Interactive Python Games for Learning
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
basic/[Link]
~~~~~~~~~~~~~~~~~~~~
import os
import sys
[Link](0, [Link]('..'))
import freegames
# 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 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']
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['[Link]']
# 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
## Setup
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)
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
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::
The CLI supports three commands: list, copy, and show. For a list of all games
run::
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::
__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
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'
cwd = [Link]()
path = [Link](cwd, filename)
if __name__ == '__main__':
main() # pragma: no cover
Backend File: free-python-games-master/src/freegames/[Link]
"""Ant, simple animation demo.
Exercises
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)
Exercises
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)
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)
if not inside(player):
draw(False)
return
draw(True)
ontimer(move, 50)
Exercises:
digits = 3
guesses = 10
if letters[0] == '0':
[Link]()
number = ''.join(letters)
counter = 1
while True:
print('Guess #', counter)
guess = input()
if len(guess) != digits:
print('Wrong number of digits. Try again!')
continue
clues = []
shuffle(clues)
if len(clues) == 0:
print('bagels')
else:
print(' '.join(clues))
counter += 1
if guess == number:
print('You got it!')
break
Exercises
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
clear()
goto(x, y)
dot(10)
ontimer(draw, 50)
Exercises
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()
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)
if inside(ball):
speed.y -= 0.35
[Link](speed)
dupe = [Link]()
[Link]()
draw()
ontimer(move, 50)
Exercises
def grid():
"""Draw Connect Four grid."""
bgcolor('light blue')
update()
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
num = ord(letter)
if [Link]():
base = ord('A')
else:
assert [Link]()
base = ord('a')
result += chr(num)
elif [Link]():
else:
result += letter
return result
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
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
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
Exercises
1. Keep score.
2. Vary the speed.
3. Vary the size of the balls.
4. Allow the bird to move forward and back.
"""
bird = vector(0, 0)
balls = []
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')
update()
def move():
"""Update object positions."""
bird.y -= 5
if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
[Link](ball)
if not inside(bird):
draw(False)
return
draw(True)
ontimer(move, 50)
Exercises
start = 1
end = 100
value = randint(start, end)
# print(value)
print("I'm thinking of a number between", start, 'and', end)
guess = None
Exercises:
size = 25
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)
Exercises
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
def step():
"""Compute one step in the Game of Life."""
neighbors = {}
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)
Exercises:
chunks = []
print('=' * 80)
story = ''.join(chunks)
print(story)
Backend File: free-python-games-master/src/freegames/[Link]
"""Maze, move from one side to another.
Excercises
def draw():
"""Draw maze."""
color('black')
width(5)
update()
width(2)
color('red')
goto(x, y)
dot(4)
Exercises:
car = path('[Link]')
tiles = list(range(32)) * 2
state = {'mark': None}
hide = [True] * 64
def xy(count):
"""Convert tiles count to (x, y) coordinates."""
return (count % 8) * 50 - 200, (count // 8) * 50 - 200
def draw():
"""Draw image and tiles."""
clear()
goto(0, 0)
shape(car)
stamp()
mark = state['mark']
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
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
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')
if bombs[x, y]:
end()
return
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)
Exercises
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()
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
if tiles[index] == 0:
return False
def world():
"""Draw world using path."""
bgcolor('black')
[Link]('blue')
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')
up()
goto(point.x + 10, point.y + 10)
dot(20, 'red')
update()
ontimer(move, 100)
Exercises
1. Add a color.
2. Complete circle.
3. Complete rectangle.
4. Complete triangle.
5. Add width parameter.
"""
end_fill()
if start is None:
state['start'] = vector(x, y)
else:
shape = state['shape']
end = vector(x, y)
shape(start, end)
state['start'] = None
Exercises
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 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 x < -185:
low = state[1]
high = state[1] + 50
if x > 185:
low = state[2]
high = state[2] + 50
ontimer(draw, 50)
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.
import random
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]
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)
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
Exercises
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)
if tile != pattern[index]:
exit()
[Link](tile)
flash(tile)
if len(guesses) == len(pattern):
grow()
onscreenclick(tap)
Exercises
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
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)
[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()
Exercises
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 floor(value):
"""Round value down to grid with square size 133."""
return ((value + 200) // 133) * 133 - 200
state = {'player': 0}
players = [drawx, drawo]
Exercises
tiles = {}
neighbors = [
vector(100, 0),
vector(-100, 0),
vector(0, 100),
vector(0, -100),
]
def load():
"""Load tiles and scramble."""
count = 1
tiles[mark] = None
if spot in tiles:
number = tiles[spot]
tiles[spot] = None
tiles[mark] = number
mark = spot
if number is None:
return
elif number < 10:
forward(20)
def draw():
"""Draw all tiles."""
for mark in tiles:
square(mark, tiles[mark])
update()
Exercises
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]()
[Link](p1head)
[Link](p2head)
Exercises
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()
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)
draw()
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)