Python Game Code You Can Copy and Paste

Every game below is a complete program in a single file, tested on Python 3.13. Copy the code, save it as a .py file and run it with python filename.py. The console games only use the standard library, so there's nothing to install.

Want to understand the code rather than just run it? Each game's page explains it step by step and has three coding challenges.

1. Tic Tac Toe in Python

73 lines · plays on this site · how it works and challenges

import random

# The board is a list of 9 squares: index 0 is the top-left, 8 is the bottom-right.
board = [" "] * 9
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8),   # rows
         (0, 3, 6), (1, 4, 7), (2, 5, 8),   # columns
         (0, 4, 8), (2, 4, 6)]              # diagonals


def show(board):
    print()
    for r in range(3):
        print(" " + " | ".join(board[r * 3:r * 3 + 3]))
        if r < 2:
            print("---+---+---")
    print()


def winner(board):
    for a, b, c in LINES:
        if board[a] != " " and board[a] == board[b] == board[c]:
            return board[a]
    return None


def free_squares(board):
    return [i for i in range(9) if board[i] == " "]


def computer_move(board):
    # 1. win if we can, 2. block X, 3. take the centre, 4. pick any free square
    for mark in ["O", "X"]:
        for i in free_squares(board):
            board[i] = mark
            found = winner(board) == mark
            board[i] = " "
            if found:
                return i
    if board[4] == " ":
        return 4
    return random.choice(free_squares(board))


print("TIC TAC TOE  -  you are X, the computer is O")
print("Squares:  1 | 2 | 3   then 4 5 6, then 7 8 9")
show(board)

while True:
    move = input("Your move (1-9): ").strip()
    if not move.isdigit() or not 1 <= int(move) <= 9:
        print("Type a number from 1 to 9.")
        continue
    square = int(move) - 1
    if board[square] != " ":
        print("That square is taken.")
        continue
    board[square] = "X"
    if winner(board) or not free_squares(board):
        break
    spot = computer_move(board)
    board[spot] = "O"
    print(f"The computer takes square {spot + 1}.")
    show(board)
    if winner(board) or not free_squares(board):
        break

show(board)
if winner(board) == "X":
    print("You win! Three in a row.")
elif winner(board) == "O":
    print("The computer wins this time.")
else:
    print("It's a draw. Nobody got three in a row.")

2. Rock Paper Scissors in Python

41 lines · plays on this site · how it works and challenges

import random

NAMES = {"r": "rock", "p": "paper", "s": "scissors"}
BEATS = {"rock": "scissors", "scissors": "paper", "paper": "rock"}


def round_result(me, cpu):
    if me == cpu:
        return "tie"
    if BEATS[me] == cpu:
        return "win"
    return "lose"


print("ROCK PAPER SCISSORS  -  first to 3 wins")
my_score = 0
cpu_score = 0

while my_score < 3 and cpu_score < 3:
    key = input("\nr, p or s? ").strip().lower()
    if key not in NAMES:
        print("Please type r, p or s.")
        continue
    me = NAMES[key]
    cpu = random.choice(list(BEATS))
    print(f"You chose {me}. The computer chose {cpu}.")
    result = round_result(me, cpu)
    if result == "win":
        my_score += 1
        print(f"{me.capitalize()} beats {cpu}. You win the round!")
    elif result == "lose":
        cpu_score += 1
        print(f"{cpu.capitalize()} beats {me}. The computer wins the round.")
    else:
        print("Same choice. It's a tie!")
    print(f"Score: you {my_score} - {cpu_score} computer")

if my_score == 3:
    print("\nYou win the match!")
else:
    print("\nThe computer wins the match. Rematch?")

3. Snake Game in Python (Turtle)

90 lines · keyboard turtle game: run it on your computer · how it works and challenges

import random
import turtle

STEP = 20          # size of one grid square in pixels
LIMIT = 280        # the walls are at -280 and 280

screen = turtle.Screen()
screen.setup(620, 620)
screen.bgcolor("black")
screen.title("Snake")
screen.tracer(0)               # we redraw the screen ourselves

pen = turtle.Turtle()
pen.hideturtle()
pen.penup()

snake = [(0, 0), (-20, 0), (-40, 0)]   # head first
direction = (STEP, 0)
food = (100, 100)
score = 0


def move(head, direction):
    return (head[0] + direction[0], head[1] + direction[1])


def hits_wall(head):
    return abs(head[0]) > LIMIT or abs(head[1]) > LIMIT


def new_food():
    while True:
        spot = (random.randint(-14, 14) * STEP, random.randint(-14, 14) * STEP)
        if spot not in snake:
            return spot


def square(x, y, color):
    pen.goto(x - 9, y - 9)
    pen.color(color)
    pen.begin_fill()
    for _ in range(4):
        pen.forward(18)
        pen.left(90)
    pen.end_fill()


def draw():
    pen.clear()
    square(food[0], food[1], "red")
    for x, y in snake:
        square(x, y, "lime")
    pen.goto(-280, 290)
    pen.color("white")
    pen.write(f"Score: {score}", font=("Arial", 14, "bold"))
    screen.update()


def turn(dx, dy):
    global direction
    if (dx, dy) != (-direction[0], -direction[1]):   # no reversing into yourself
        direction = (dx, dy)


def tick():
    global food, score
    head = move(snake[0], direction)
    if hits_wall(head) or head in snake:
        pen.goto(0, 0)
        pen.color("white")
        pen.write(f"Game over! Score: {score}", align="center", font=("Arial", 24, "bold"))
        screen.update()
        return
    snake.insert(0, head)
    if head == food:
        score += 1
        food = new_food()
    else:
        snake.pop()
    draw()
    screen.ontimer(tick, 120)


screen.listen()
screen.onkey(lambda: turn(0, STEP), "Up")
screen.onkey(lambda: turn(0, -STEP), "Down")
screen.onkey(lambda: turn(-STEP, 0), "Left")
screen.onkey(lambda: turn(STEP, 0), "Right")
tick()
screen.mainloop()

4. Hangman in Python

52 lines · plays on this site · how it works and challenges

import random

WORDS = ["python", "keyboard", "variable", "function", "rocket", "puzzle",
         "planet", "laptop", "garden", "pirate", "jungle", "tomato"]

STAGES = [
    "  +---+\n      |\n      |\n      |\n     ===",
    "  +---+\n  O   |\n      |\n      |\n     ===",
    "  +---+\n  O   |\n  |   |\n      |\n     ===",
    "  +---+\n  O   |\n /|   |\n      |\n     ===",
    "  +---+\n  O   |\n /|\\  |\n      |\n     ===",
    "  +---+\n  O   |\n /|\\  |\n /    |\n     ===",
    "  +---+\n  O   |\n /|\\  |\n / \\  |\n     ===",
]


def masked(word, guessed):
    return " ".join(ch if ch in guessed else "_" for ch in word)


word = random.choice(WORDS)
guessed = set()
wrong = 0

print("HANGMAN  -  guess the word one letter at a time")
while wrong < 6:
    print()
    print(STAGES[wrong])
    print("Word:", masked(word, guessed))
    if guessed:
        print("Tried:", " ".join(sorted(guessed)))
    if all(ch in guessed for ch in word):
        break
    letter = input("Guess a letter: ").strip().lower()
    if len(letter) != 1 or not letter.isalpha():
        print("Type a single letter.")
    elif letter in guessed:
        print("You already tried", letter)
    else:
        guessed.add(letter)
        if letter in word:
            print("Yes!", letter, "is in the word.")
        else:
            wrong += 1
            print("No", letter, "-", 6 - wrong, "wrong guesses left.")

if wrong < 6:
    print(f"\nYou got it: {word.upper()}!")
else:
    print()
    print(STAGES[6])
    print(f"Out of guesses. The word was {word.upper()}.")

5. Number Guessing Game in Python

33 lines · plays on this site · how it works and challenges

import random

LEVELS = {"easy": 10, "normal": 50, "hard": 100}

print("NUMBER GUESSING GAME")
level = input("Pick a level - easy, normal or hard: ").strip().lower()
if level not in LEVELS:
    print("I'll use normal.")
    level = "normal"
top = LEVELS[level]
secret = random.randint(1, top)
guesses = 0
print(f"I'm thinking of a number from 1 to {top}.")

while True:
    text = input("Your guess: ").strip()
    if not text.isdigit():
        print("That's not a whole number. Try again.")
        continue
    guess = int(text)
    guesses += 1
    if guess < secret:
        print("Higher!")
    elif guess > secret:
        print("Lower!")
    else:
        print(f"Correct! The number was {secret}.")
        break

if guesses == 1:
    print("First try. Amazing!")
else:
    print(f"You found it in {guesses} guesses.")

6. Pong-Style Paddle Game in Python

84 lines · keyboard turtle game: run it on your computer · how it works and challenges

import turtle

screen = turtle.Screen()
screen.title("Paddle Ball")
screen.bgcolor("black")
screen.setup(800, 600)
screen.tracer(0)


def make(shape, x, w=1, h=1):
    t = turtle.Turtle(shape)
    t.color("white")
    t.shapesize(stretch_wid=h, stretch_len=w)
    t.penup()
    t.goto(x, 0)
    return t


left = make("square", -350, h=5)
right = make("square", 350, h=5)
ball = make("circle", 0)
ball.dx, ball.dy = 4, 4                  # speed in x and y

score = [0, 0]
pen = turtle.Turtle()
pen.hideturtle()
pen.color("white")
pen.penup()
pen.goto(0, 250)


def show_score():
    pen.clear()
    pen.write(f"{score[0]}   {score[1]}", align="center", font=("Courier", 32, "bold"))


def paddle(p, dy):
    y = p.ycor() + dy
    if -250 < y < 250:
        p.sety(y)


screen.listen()
screen.onkeypress(lambda: paddle(left, 30), "w")
screen.onkeypress(lambda: paddle(left, -30), "s")
screen.onkeypress(lambda: paddle(right, 30), "Up")
screen.onkeypress(lambda: paddle(right, -30), "Down")
show_score()


def frame():
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

    if abs(ball.ycor()) > 290:          # top and bottom walls
        ball.dy = -ball.dy

    if ball.xcor() > 390:               # right player missed
        score[0] += 1
        ball.goto(0, 0)
        ball.dx = -4
        show_score()
    elif ball.xcor() < -390:            # left player missed
        score[1] += 1
        ball.goto(0, 0)
        ball.dx = 4
        show_score()

    # paddle hits: the ball is level with a paddle and close to its centre
    if 330 < ball.xcor() < 350 and abs(ball.ycor() - right.ycor()) < 55 and ball.dx > 0:
        ball.dx = -ball.dx * 1.05
    if -350 < ball.xcor() < -330 and abs(ball.ycor() - left.ycor()) < 55 and ball.dx < 0:
        ball.dx = -ball.dx * 1.05

    screen.update()
    if max(score) < 5:
        screen.ontimer(frame, 16)
    else:
        pen.goto(0, 0)
        pen.write("Left wins!" if score[0] == 5 else "Right wins!", align="center", font=("Courier", 28, "bold"))


frame()
screen.mainloop()

7. Mad Libs-Style Story Game in Python

25 lines · plays on this site · how it works and challenges

import random
import re

STORIES = [
    "Today I took my pet {animal} to the {place}. It started to {verb} so "
    "{adverb} that everyone gave it a {adjective} {food}.",
    "Breaking news: a giant {food} has landed on the {place}! Scientists say "
    "it can {verb} faster than a {animal}. People are feeling very {adjective}.",
    "My robot learned to {verb} {adverb}. Now it wants to open a {adjective} "
    "{place} that only sells {food} to every {animal} in town.",
]

story = random.choice(STORIES)
blanks = re.findall(r"{(\w+)}", story)     # the words this story needs

print("SILLY STORIES  -  give me some words, then read your story!")
words = {}
for blank in blanks:
    if blank not in words:
        article = "an" if blank[0] in "aeiou" else "a"
        answer = input(f"Give me {article} {blank}: ").strip()
        words[blank] = answer or "banana"

print("\nHere is your story:\n")
print(story.format(**words))

8. Text Adventure Game in Python

70 lines · plays on this site · how it works and challenges

ROOMS = {
    "dock": {"text": "You stand on a wooden dock. Your little boat bumps against it.",
             "exits": {"north": "path"}, "items": ["key"]},
    "path": {"text": "A sandy path. A lighthouse stands to the north, a shed to the east.",
             "exits": {"south": "dock", "east": "shed", "north": "lighthouse"}, "items": []},
    "shed": {"text": "A dusty shed full of nets and ropes.",
             "exits": {"west": "path"}, "items": ["matches", "rope"]},
    "lighthouse": {"text": "Inside the lighthouse. Stairs spiral upwards.",
                   "exits": {"south": "path", "up": "lamp room"}, "items": []},
    "lamp room": {"text": "The lamp room. A huge lamp waits to be lit. Far away, a ship's lights pass by.",
                  "exits": {"down": "lighthouse"}, "items": []},
}

room = "dock"
bag = []
print("LIGHTHOUSE ISLAND  -  type 'help' for commands")


def describe():
    here = ROOMS[room]
    print(f"\n== {room.upper()} ==")
    print(here["text"])
    if here["items"]:
        print("You see:", ", ".join(here["items"]))
    print("Exits:", ", ".join(here["exits"]))


describe()
while True:
    words = input("> ").strip().lower().split()
    if not words:
        continue
    verb, noun = words[0], " ".join(words[1:])

    if verb == "help":
        print("look, go <direction>, take <item>, inventory, light lamp, quit")
    elif verb == "look":
        describe()
    elif verb == "inventory":
        print("You carry:", ", ".join(bag) if bag else "nothing")
    elif verb == "go":
        exits = ROOMS[room]["exits"]
        if noun not in exits:
            print("You can't go that way.")
        elif exits[noun] == "lighthouse" and "key" not in bag:
            print("The lighthouse door is locked.")
        else:
            room = exits[noun]
            describe()
    elif verb == "take":
        if noun in ROOMS[room]["items"]:
            ROOMS[room]["items"].remove(noun)
            bag.append(noun)
            print("Taken:", noun)
        else:
            print("There is no", noun or "thing", "here.")
    elif verb == "light" and noun == "lamp":
        if room != "lamp room":
            print("There's no lamp here.")
        elif "matches" not in bag:
            print("You need something to light it with.")
        else:
            print("The lamp blazes into life! The ship turns towards the island.")
            print("You are rescued. THE END")
            break
    elif verb == "quit":
        print("Bye!")
        break
    else:
        print("I don't understand that. Try 'help'.")

9. Connect Four-Style Game in Python

70 lines · plays on this site · how it works and challenges

import random

ROWS, COLS = 6, 7
grid = [["." for _ in range(COLS)] for _ in range(ROWS)]   # row 0 is the top


def show():
    print()
    for row in grid:
        print(" " + " ".join(row))
    print(" " + " ".join(str(c + 1) for c in range(COLS)))


def drop(col, mark):
    for r in range(ROWS - 1, -1, -1):          # start at the bottom row
        if grid[r][col] == ".":
            grid[r][col] = mark
            return r
    return None                                  # the column is full


def wins(mark):
    for r in range(ROWS):
        for c in range(COLS):
            for dr, dc in [(0, 1), (1, 0), (1, 1), (1, -1)]:
                cells = [(r + dr * i, c + dc * i) for i in range(4)]
                if all(0 <= y < ROWS and 0 <= x < COLS and grid[y][x] == mark for y, x in cells):
                    return True
    return False


def open_cols():
    return [c for c in range(COLS) if grid[0][c] == "."]


def computer():
    for mark in ["O", "X"]:                      # win, else block
        for c in open_cols():
            r = drop(c, mark)
            found = wins(mark)
            grid[r][c] = "."
            if found:
                return c
    middle = [c for c in [3, 2, 4, 1, 5, 0, 6] if c in open_cols()]
    return random.choice(middle[:3])


print("FOUR IN A ROW  -  you are X")
show()
while True:
    text = input("Your column (1-7): ").strip()
    if not text.isdigit() or not 1 <= int(text) <= COLS or int(text) - 1 not in open_cols():
        print("Pick an open column from 1 to 7.")
        continue
    drop(int(text) - 1, "X")
    if wins("X"):
        show()
        print("Four in a row! You win!")
        break
    if not open_cols():
        show()
        print("The grid is full. It's a draw.")
        break
    col = computer()
    drop(col, "O")
    print(f"The computer drops into column {col + 1}.")
    show()
    if wins("O"):
        print("The computer got four in a row.")
        break

10. Minesweeper-Style Game in Python

77 lines · plays on this site · how it works and challenges

import random

SIZE, MINES = 6, 6
mines = set()
opened = set()
flags = set()


def neighbours(r, c):
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            y, x = r + dr, c + dc
            if (dr or dc) and 0 <= y < SIZE and 0 <= x < SIZE:
                yield y, x


def count(r, c):
    return sum((y, x) in mines for y, x in neighbours(r, c))


def place_mines(safe):
    cells = [(r, c) for r in range(SIZE) for c in range(SIZE) if (r, c) != safe]
    mines.update(random.sample(cells, MINES))


def open_square(r, c):
    if (r, c) in opened:
        return
    opened.add((r, c))
    if count(r, c) == 0:                 # flood fill: open the neighbours too
        for y, x in neighbours(r, c):
            open_square(y, x)


def show(reveal=False):
    print("\n    " + " ".join(str(c + 1) for c in range(SIZE)))
    for r in range(SIZE):
        row = []
        for c in range(SIZE):
            if reveal and (r, c) in mines:
                row.append("*")
            elif (r, c) in flags:
                row.append("F")
            elif (r, c) in opened:
                row.append(str(count(r, c)) if count(r, c) else " ")
            else:
                row.append("#")
        print(f" {r + 1}  " + " ".join(row))


print("MINE FINDER  -  open all the safe squares")
show()
while True:
    parts = input("Row and column (or f row col): ").lower().split()
    flag = parts[:1] == ["f"]
    if flag:
        parts = parts[1:]
    if len(parts) != 2 or not all(p.isdigit() and 1 <= int(p) <= SIZE for p in parts):
        print("Type two numbers from 1 to", SIZE)
        continue
    r, c = int(parts[0]) - 1, int(parts[1]) - 1
    if flag:
        flags ^= {(r, c)}              # flag on, or flag off again
        show()
        continue
    if not mines:
        place_mines((r, c))
    if (r, c) in mines:
        show(reveal=True)
        print("BOOM! You found a mine. Game over.")
        break
    open_square(r, c)
    flags -= opened
    show()
    if len(opened) == SIZE * SIZE - MINES:
        print("You cleared the field. You win!")
        break

11. Sudoku in Python

59 lines · plays on this site · how it works and challenges

import random

# A valid full grid from a pattern, then shuffled so every game is different.
def full_grid():
    nums = random.sample(range(1, 10), 9)
    rows = [g * 3 + r for g in random.sample(range(3), 3) for r in random.sample(range(3), 3)]
    cols = [g * 3 + c for g in random.sample(range(3), 3) for c in random.sample(range(3), 3)]
    return [[nums[(3 * (r % 3) + r // 3 + c) % 9] for c in cols] for r in rows]


def ok(grid, r, c, n):
    if n in grid[r]:
        return False
    if n in [grid[i][c] for i in range(9)]:
        return False
    br, bc = r // 3 * 3, c // 3 * 3
    return all(grid[y][x] != n for y in range(br, br + 3) for x in range(bc, bc + 3))


def show(grid):
    for r in range(9):
        if r % 3 == 0:
            print("  +-------+-------+-------+")
        row = ""
        for c in range(9):
            row += ("| " if c % 3 == 0 else "") + (str(grid[r][c]) if grid[r][c] else ".") + " "
        print(f"{r + 1} {row}|")
    print("  +-------+-------+-------+")
    print("    1 2 3   4 5 6   7 8 9")


answer = full_grid()
grid = [row[:] for row in answer]
holes = random.sample([(r, c) for r in range(9) for c in range(9)], 12)
for r, c in holes:
    grid[r][c] = 0

print("SUDOKU  -  fill the dots. Type: row column number (or 'hint')")
while any(0 in row for row in grid):
    show(grid)
    text = input("> ").strip().lower()
    if text == "hint":
        r, c = next((r, c) for r, c in holes if grid[r][c] == 0)
        grid[r][c] = answer[r][c]
        print(f"Row {r + 1}, column {c + 1} is {answer[r][c]}.")
        continue
    parts = text.split()
    if len(parts) != 3 or not all(p.isdigit() and 1 <= int(p) <= 9 for p in parts):
        print("Type three numbers from 1 to 9, like: 4 7 2")
        continue
    r, c, n = int(parts[0]) - 1, int(parts[1]) - 1, int(parts[2])
    if (r, c) not in holes:
        print("That square was given at the start.")
    elif not ok(grid, r, c, n) and grid[r][c] != n:
        print(f"{n} is already in that row, column or box.")
    else:
        grid[r][c] = n
show(grid)
print("Solved! Every row, column and box is complete.")

12. Battleship-Style Game in Python

72 lines · plays on this site · how it works and challenges

import random

SIZE = 6
LETTERS = "ABCDEF"
ships = []                       # each ship is a set of (row, col) squares


def place(length):
    while True:
        across = random.choice([True, False])
        r = random.randrange(SIZE - (0 if across else length - 1))
        c = random.randrange(SIZE - (length - 1 if across else 0))
        cells = {(r, c + i) if across else (r + i, c) for i in range(length)}
        if not any(cells & s for s in ships):    # no overlap
            ships.append(cells)
            return


def parse(text):
    text = text.strip().upper()
    if len(text) != 2 or text[0] not in LETTERS or not text[1].isdigit():
        return None
    r = int(text[1]) - 1
    if not 0 <= r < SIZE:
        return None
    return r, LETTERS.index(text[0])


def show():
    print("\n   " + " ".join(LETTERS))
    for r in range(SIZE):
        row = []
        for c in range(SIZE):
            if (r, c) in hits:
                row.append("X")
            elif (r, c) in misses:
                row.append("o")
            else:
                row.append("~")
        print(f" {r + 1} " + " ".join(row))


for length in (3, 2, 2):
    place(length)
hits, misses = set(), set()
shots = 20

print("SEA BATTLE  -  sink 3 ships in 20 shots")
while shots > 0:
    show()
    spot = parse(input(f"Shots left {shots}. Fire at: "))
    if spot is None:
        print("Type a letter A-F and a number 1-6, like C3.")
        continue
    if spot in hits or spot in misses:
        print("You already fired there.")
        continue
    shots -= 1
    ship = next((s for s in ships if spot in s), None)
    if ship:
        hits.add(spot)
        print("HIT!" + (" You sank a ship!" if ship <= hits else ""))
        if all(s <= hits for s in ships):
            show()
            print("All ships sunk. You win the battle!")
            break
    else:
        misses.add(spot)
        print("Splash. Miss.")
else:
    print("Out of shots! The ships were at:")
    print(", ".join(LETTERS[c] + str(r + 1) for s in ships for r, c in sorted(s)))

13. Maze Game in Python

76 lines · plays on this site · how it works and challenges

import random
from collections import deque

W, H = 7, 5                                     # maze size in cells
COLS, ROWS = W * 2 + 1, H * 2 + 1               # size in characters
maze = [["#"] * COLS for _ in range(ROWS)]


def carve(cx, cy):
    maze[cy * 2 + 1][cx * 2 + 1] = " "
    dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    random.shuffle(dirs)
    for dx, dy in dirs:
        nx, ny = cx + dx, cy + dy
        if 0 <= nx < W and 0 <= ny < H and maze[ny * 2 + 1][nx * 2 + 1] == "#":
            maze[cy * 2 + 1 + dy][cx * 2 + 1 + dx] = " "   # knock down the wall between
            carve(nx, ny)


def shortest_path(start, goal):
    came = {start: None}
    queue = deque([start])
    while queue:
        spot = queue.popleft()
        if spot == goal:
            break
        x, y = spot
        for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if maze[ny][nx] != "#" and (nx, ny) not in came:
                came[(nx, ny)] = spot
                queue.append((nx, ny))
    path = []
    while spot:
        path.append(spot)
        spot = came[spot]
    return path[::-1]


def show(trail=()):
    for y in range(ROWS):
        line = ""
        for x in range(COLS):
            if (x, y) == player:
                line += "@"
            elif (x, y) == goal:
                line += "E"
            elif (x, y) in trail:
                line += "."
            else:
                line += maze[y][x]
        print(line)


carve(0, 0)
player, goal = (1, 1), (COLS - 2, ROWS - 2)
MOVES = {"w": (0, -1), "s": (0, 1), "a": (-1, 0), "d": (1, 0)}
steps = 0

print("MAZE RUNNER  -  get from @ to E with w a s d")
while player != goal:
    show()
    keys = input("Move: ").strip().lower()
    if keys == "solve":
        show(shortest_path(player, goal))
        print("Follow the dots!")
        player = goal
        break
    for k in keys:
        if k in MOVES:
            nx, ny = player[0] + MOVES[k][0], player[1] + MOVES[k][1]
            if maze[ny][nx] == "#":
                print("Bump! A wall.")
                break
            player = (nx, ny)
            steps += 1
print(f"You escaped the maze in {steps} steps!" if steps else "Maze solved.")

14. Higher or Lower Game in Python

39 lines · plays on this site · how it works and challenges

import random


def judge(current, nxt, guess):
    if nxt == current:
        return "same"
    if (nxt > current) == (guess == "h"):
        return "right"
    return "wrong"


print("HIGHER OR LOWER  -  build the longest streak")
best = 0
playing = True
while playing:
    streak = 0
    current = random.randint(1, 100)
    while True:
        print(f"\nThe number is {current}.")
        guess = input("Higher or lower? (h/l): ").strip().lower()
        if guess not in ("h", "l"):
            print("Type h or l.")
            continue
        nxt = random.randint(1, 100)
        result = judge(current, nxt, guess)
        print(f"The next number is {nxt}.")
        if result == "wrong":
            print(f"Wrong! Your streak was {streak}.")
            break
        if result == "right":
            streak += 1
            print(f"Right! Streak: {streak}")
        else:
            print("Same number - free pass!")
        current = nxt
    best = max(best, streak)
    print(f"Best streak: {best}")
    playing = input("Play again? (y/n): ").strip().lower() == "y"
print("Thanks for playing!")

15. Word Guessing Game in Python

38 lines · plays on this site · how it works and challenges

import random

WORDS = ["apple", "bread", "chair", "dance", "eagle", "flame", "grape", "house",
         "juice", "lemon", "mango", "night", "ocean", "piano", "queen", "river",
         "smile", "tiger", "under", "voice", "water", "youth", "zebra", "cloud",
         "plant", "storm", "train", "brick", "sheep", "candy"]


def feedback(guess, secret):
    marks = ["-"] * 5
    left = {}
    for g, s in zip(guess, secret):          # count letters not matched exactly
        if g != s:
            left[s] = left.get(s, 0) + 1
    for i, (g, s) in enumerate(zip(guess, secret)):
        if g == s:
            marks[i] = "+"
        elif left.get(g, 0) > 0:
            marks[i] = "?"
            left[g] -= 1
    return "".join(marks)


secret = random.choice(WORDS)
print("WORD GUESS  -  find the 5-letter word in 6 tries")
print("+ right place   ? wrong place   - not in the word")
for attempt in range(1, 7):
    guess = input(f"\nGuess {attempt}/6: ").strip().lower()
    while len(guess) != 5 or not guess.isalpha():
        guess = input("Please type a 5-letter word: ").strip().lower()
    marks = feedback(guess, secret)
    print("  " + " ".join(guess.upper()))
    print("  " + " ".join(marks))
    if marks == "+++++":
        print(f"\nYou got it in {attempt}!")
        break
else:
    print(f"\nOut of tries. The word was {secret.upper()}.")

16. Coin Flip in Python

33 lines · plays on this site · how it works and challenges

import random

SIDES = {"h": "heads", "t": "tails"}

print("COIN FLIP CHALLENGE  -  call 10 flips")
score = 0
for flip in range(1, 11):
    call = input(f"Flip {flip}: heads or tails? (h/t) ").strip().lower()
    while call not in SIDES:
        call = input("Type h or t: ").strip().lower()
    coin = random.choice(["heads", "tails"])
    if SIDES[call] == coin:
        score += 1
        print(f"  It's {coin}. Correct!")
    else:
        print(f"  It's {coin}. Unlucky.")

print(f"\nYou called {score} out of 10.")
if score >= 7:
    print("Are you reading the coin's mind?")
elif score <= 3:
    print("Tough luck. Pure chance says about 5.")

# The experiment: flip lots of coins
flips = [random.choice("HT") for _ in range(10000)]
heads = flips.count("H")
print(f"\n10,000 flips: {heads} heads ({heads / 100:.1f}%), {10000 - heads} tails")

longest, run = 1, 1
for a, b in zip(flips, flips[1:]):
    run = run + 1 if a == b else 1
    longest = max(longest, run)
print(f"Longest run of the same side: {longest} in a row")

17. Turtle Race in Python

50 lines · plays on this site · how it works and challenges

import random
import turtle

COLORS = ["red", "blue", "green", "orange", "purple"]
FINISH = 200

print("TURTLE RACE  -  who will win?")
bet = input("Pick a colour (red, blue, green, orange, purple): ").strip().lower()
while bet not in COLORS:
    bet = input("Choose one of: " + ", ".join(COLORS) + ": ").strip().lower()

screen = turtle.Screen()
screen.setup(520, 360)
screen.bgcolor("lightgreen")

# draw the finish line
line = turtle.Turtle()
line.hideturtle()
line.speed(0)
line.penup()
line.goto(FINISH, 140)
line.pendown()
line.pensize(4)
line.goto(FINISH, -140)
line.penup()
line.goto(FINISH - 20, 150)
line.write("FINISH", font=("Arial", 12, "bold"))

racers = []
for i, color in enumerate(COLORS):
    t = turtle.Turtle()
    t.shape("turtle")
    t.color(color)
    t.penup()
    t.goto(-220, 100 - i * 50)
    t.pendown()
    racers.append(t)

winner = None
while winner is None:
    for t in racers:
        t.forward(random.randint(1, 10))
        if t.xcor() >= FINISH:
            winner = t
            break

champ = COLORS[racers.index(winner)]
print(f"The {champ} turtle wins!")
print("Your turtle won! Great pick." if champ == bet else f"Your {bet} turtle didn't win this time.")
turtle.done()

18. Python Quiz Game

47 lines · plays on this site · how it works and challenges

import random

QUESTIONS = [
    {"q": "What does print(2 ** 3) show?", "choices": ["6", "8", "9", "23"], "answer": "b",
     "why": "** means 'to the power of', so 2 ** 3 is 2 x 2 x 2 = 8."},
    {"q": "Which of these makes a list?", "choices": ["(1, 2)", "{1, 2}", "[1, 2]", "<1, 2>"], "answer": "c",
     "why": "Square brackets make a list. Round brackets make a tuple, curly ones a set."},
    {"q": "What type does input() always give you?", "choices": ["int", "str", "float", "bool"], "answer": "b",
     "why": "input() returns text (str). Use int() to turn it into a number."},
    {"q": "What is len('hello')?", "choices": ["4", "5", "6", "'o'"], "answer": "b",
     "why": "len() counts the characters: h-e-l-l-o is 5."},
    {"q": "Which keyword leaves a loop early?", "choices": ["stop", "exit", "break", "return"], "answer": "c",
     "why": "break ends the loop straight away. continue skips to the next round."},
    {"q": "What does range(3) produce?", "choices": ["1, 2, 3", "0, 1, 2", "0, 1, 2, 3", "3, 2, 1"], "answer": "b",
     "why": "range(3) starts at 0 and stops before 3."},
    {"q": "What is 7 // 2?", "choices": ["3.5", "3", "4", "1"], "answer": "b",
     "why": "// divides and drops the fraction, so 7 // 2 is 3. 7 % 2 would be the remainder, 1."},
    {"q": "How do you start a function?", "choices": ["function f():", "def f():", "func f():", "f() =>"], "answer": "b",
     "why": "Python functions start with def, then the name, brackets and a colon."},
]

random.shuffle(QUESTIONS)
score = 0
print("PYTHON QUIZ  -  answer with a, b, c or d")

for number, item in enumerate(QUESTIONS, 1):
    print(f"\nQ{number}. {item['q']}")
    for letter, choice in zip("abcd", item["choices"]):
        print(f"   {letter}) {choice}")
    reply = input("Your answer: ").strip().lower()
    while reply not in ("a", "b", "c", "d"):
        reply = input("Type a, b, c or d: ").strip().lower()
    if reply == item["answer"]:
        score += 1
        print("Correct!", item["why"])
    else:
        right = item["choices"]["abcd".index(item["answer"])]
        print(f"Not quite. The answer is {item['answer']}) {right}. {item['why']}")

total = len(QUESTIONS)
print(f"\nYou scored {score}/{total} ({score * 100 // total}%).")
if score == total:
    print("Perfect! You know your Python.")
elif score >= total // 2:
    print("Good work! Review the ones you missed and try again.")
else:
    print("Keep going! Every game on this site will help.")

19. Math Quiz Game in Python

38 lines · plays on this site · how it works and challenges

import operator
import random
import time

OPS = {"+": operator.add, "-": operator.sub, "x": operator.mul}


def make_question(level):
    sign = random.choice(list(OPS))
    top = 10 if level == 1 else 20
    a, b = random.randint(1, top), random.randint(1, top)
    if sign == "-" and b > a:
        a, b = b, a                      # no negative answers
    if sign == "x":
        b = random.randint(2, 9 if level == 1 else 12)
    return a, sign, b, OPS[sign](a, b)


print("MATH SPRINT  -  10 sums, as fast as you can")
level = input("Level 1 or 2? ").strip()
level = 2 if level == "2" else 1
score = 0
start = time.time()

for n in range(1, 11):
    a, sign, b, answer = make_question(level)
    reply = input(f"Q{n}: {a} {sign} {b} = ").strip()
    if reply.lstrip("-").isdigit() and int(reply) == answer:
        score += 1
        print("  ✓")
    else:
        print(f"  ✗  It's {answer}")

seconds = time.time() - start
print(f"\nScore: {score}/10 in {seconds:.1f} seconds")
print(f"That's {seconds / 10:.1f} seconds per question.")
if score == 10 and seconds < 40:
    print("Lightning fast and perfect!")

20. Typing Speed Game in Python

44 lines · plays on this site · how it works and challenges

import random
import time

LINES = [
    'print("Hello, world!")',
    "for i in range(10):",
    "total = sum(scores) / len(scores)",
    "if guess == secret:",
    "names = [n.upper() for n in names]",
    "while lives > 0:",
    "def greet(name):",
    "word = random.choice(WORDS)",
]


def accuracy(typed, target):
    right = sum(1 for a, b in zip(typed, target) if a == b)
    return round(100 * right / max(len(target), len(typed), 1))


def wpm(chars, seconds):
    return round((chars / 5) / (seconds / 60)) if seconds > 0 else 0


print("CODE TYPING TEST  -  type each line exactly")
speeds, scores = [], []
for target in random.sample(LINES, 3):
    print("\n   " + target)
    input("Press Enter when you're ready...")
    start = time.time()
    typed = input(">> ")
    seconds = time.time() - start
    acc = accuracy(typed, target)
    speed = wpm(len(typed), seconds)
    speeds.append(speed)
    scores.append(acc)
    print(f"{seconds:.1f}s  |  {speed} WPM  |  {acc}% accurate")
    if acc < 100:
        for i, (a, b) in enumerate(zip(typed, target)):
            if a != b:
                print(f"First mistake at character {i + 1}: you typed {a!r}, expected {b!r}")
                break

print(f"\nAverage: {sum(speeds) // len(speeds)} WPM at {sum(scores) // len(scores)}% accuracy")

How to run copied Python code

Frequently asked questions

Is this Python game code free to use?

Yes. Use it to learn, change it, and build your own games from it.

Which Python version do these games need?

Python 3.8 or newer. They're tested on Python 3.13 and use only the standard library (random, time, turtle, collections, operator, re).

Why doesn't the snake game run in the browser?

Snake and Paddle Ball use keyboard-controlled turtle windows, so they run on your computer. You can still play browser versions on their pages.