├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── main.yml ├── .gitignore ├── 01_02 ├── oop_turtle.py ├── procedural.py └── starter_template.py ├── 01_03 └── basic_animation_example.py ├── 01_04 ├── global1.py └── global2.py ├── 01_05 └── stamps.py ├── 02_02 └── basic_snake_movement.py ├── 02_03 └── controlling_snake_direction.py ├── 02_04 └── collision_detection.py ├── 02_05 └── snake_food.py ├── 02_06 └── keeping_score.py ├── 02_07 └── game_reset.py ├── 03_01 └── lambda_callbacks.py ├── 03_02 └── messing.py ├── 03_03 ├── assets │ ├── bg2.gif │ ├── snake-food-32x32.gif │ └── snake-head-20x20.gif └── snake_game_with_graphics.py ├── 03_04 ├── assets │ ├── bg2.gif │ ├── snake-food-32x32.gif │ └── snake-head-20x20.gif └── snake_game_with_graphics.py ├── 03_05 ├── assets │ ├── bg2.gif │ ├── snake-food-32x32.gif │ └── snake-head-20x20.gif ├── high_score.txt └── snake_game_with_graphics.py ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE └── README.md /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) deotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Copy To Branches 2 | on: 3 | workflow_dispatch: 4 | jobs: 5 | copy-to-branches: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | fetch-depth: 0 11 | - name: Copy To Branches Action 12 | uses: planetoftheweb/copy-to-branches@v1 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | .idea 6 | *~ 7 | *.pyc 8 | -------------------------------------------------------------------------------- /01_02/oop_turtle.py: -------------------------------------------------------------------------------- 1 | # Import Turtle Graphics module 2 | import turtle 3 | 4 | # Create a turtle to do your bidding 5 | my_turtle = turtle.Turtle() 6 | my_turtle.shape("turtle") 7 | my_turtle.color("red") 8 | 9 | # Your turtle awaits your command 10 | my_turtle.forward(100) # Sample command 11 | 12 | # This statement (or an equivalent) is needed at the end of all your turtle programs. 13 | turtle.done() 14 | -------------------------------------------------------------------------------- /01_02/procedural.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | 3 | color("red") 4 | forward(100) 5 | right(90) 6 | forward(100) 7 | right(90) 8 | forward(100) 9 | right(90) 10 | forward(100) 11 | right(90) 12 | 13 | done() 14 | -------------------------------------------------------------------------------- /01_02/starter_template.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | 8 | # Create a window where we will do our drawing. 9 | screen = turtle.Screen() 10 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 11 | screen.title("Program Title") 12 | screen.bgcolor("cyan") 13 | 14 | # Create a turtle to do your bidding 15 | my_turtle = turtle.Turtle() 16 | my_turtle.shape("turtle") 17 | my_turtle.color("red") 18 | 19 | # Your turtle awaits your command 20 | my_turtle.forward(100) # Sample command 21 | 22 | # This statement (or an equivalent) is needed at the end of all your turtle programs. 23 | turtle.done() 24 | -------------------------------------------------------------------------------- /01_03/basic_animation_example.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | DELAY = 10 # Milliseconds between screen updates. 8 | 9 | 10 | def move_turtle(): 11 | my_turtle.forward(1) 12 | my_turtle.right(1) 13 | screen.update() 14 | screen.ontimer(move_turtle, DELAY) # After `DELAY` milliseconds, call move_turtle again. 15 | 16 | 17 | # Create a window where we will do our drawing. 18 | screen = turtle.Screen() 19 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 20 | screen.title("Turtle Animation") 21 | screen.bgcolor("cyan") 22 | 23 | # Create a turtle to do your bidding 24 | my_turtle = turtle.Turtle() 25 | my_turtle.shape("turtle") 26 | my_turtle.color("red") 27 | screen.tracer(0) # Turn off automatic animation 28 | 29 | # Set animation in motion 30 | move_turtle() 31 | 32 | # This statement (or an equivalent) is needed at the end of all your turtle programs. 33 | turtle.done() 34 | -------------------------------------------------------------------------------- /01_04/global1.py: -------------------------------------------------------------------------------- 1 | name = "Susan" 2 | print(name) 3 | 4 | 5 | def print_name(): 6 | name = "Peter" 7 | print(name) 8 | 9 | 10 | print_name() 11 | print(name) 12 | -------------------------------------------------------------------------------- /01_04/global2.py: -------------------------------------------------------------------------------- 1 | name = "Susan" 2 | print(name) 3 | 4 | 5 | def print_name(): 6 | global name 7 | name = "Peter" 8 | print(name) 9 | 10 | 11 | print_name() 12 | print(name) 13 | -------------------------------------------------------------------------------- /01_05/stamps.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | 8 | # Create a window where we will do our drawing. 9 | screen = turtle.Screen() 10 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 11 | screen.title("Stamping") 12 | screen.bgcolor("cyan") 13 | 14 | # Create a turtle to do your bidding 15 | stamper = turtle.Turtle() 16 | stamper.shape("square") 17 | stamper.color("red") 18 | stamper.shapesize(50 / 20) 19 | stamper.stamp() 20 | stamper.penup() 21 | stamper.shapesize(10 / 20) 22 | stamper.goto(100, 100) 23 | stamper.stamp() 24 | 25 | # This statement (or an equivalent) is needed at the end of all your turtle programs. 26 | turtle.done() 27 | -------------------------------------------------------------------------------- /02_02/basic_snake_movement.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | DELAY = 400 # Milliseconds 8 | 9 | 10 | def move_snake(): 11 | stamper.clearstamps() # Remove existing stamps made by stamper. 12 | 13 | new_head = snake[-1].copy() 14 | new_head[0] += 20 15 | 16 | # Add new head to snake body. 17 | snake.append(new_head) 18 | 19 | # Remove last segment of snake. 20 | snake.pop(0) 21 | 22 | # Draw snake for the first time. 23 | for segment in snake: 24 | stamper.goto(segment[0], segment[1]) 25 | stamper.stamp() 26 | 27 | # Refresh screen 28 | screen.update() 29 | 30 | # Rinse and repeat 31 | turtle.ontimer(move_snake, DELAY) 32 | 33 | 34 | # Create a window where we will do our drawing. 35 | screen = turtle.Screen() 36 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 37 | screen.title("Snake") 38 | screen.bgcolor("pink") 39 | screen.tracer(0) # Turn off automatic animation. 40 | 41 | # Create a turtle to do your bidding 42 | stamper = turtle.Turtle() 43 | stamper.shape("square") 44 | stamper.penup() 45 | 46 | # Create snake as a list of coordinate pairs. 47 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 48 | 49 | # Draw snake for the first time. 50 | for segment in snake: 51 | stamper.goto(segment[0], segment[1]) 52 | stamper.stamp() 53 | 54 | # Set animation in motion 55 | move_snake() 56 | 57 | # Finish nicely 58 | turtle.done() 59 | -------------------------------------------------------------------------------- /02_03/controlling_snake_direction.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | DELAY = 100 # Milliseconds 8 | 9 | offsets = { 10 | "up": (0, 20), 11 | "down": (0, -20), 12 | "left": (-20, 0), 13 | "right": (20, 0) 14 | } 15 | 16 | 17 | def go_up(): 18 | global snake_direction 19 | if snake_direction != "down": 20 | snake_direction = "up" 21 | 22 | 23 | def go_right(): 24 | global snake_direction 25 | if snake_direction != "left": 26 | snake_direction = "right" 27 | 28 | 29 | def go_down(): 30 | global snake_direction 31 | if snake_direction != "up": 32 | snake_direction = "down" 33 | 34 | 35 | def go_left(): 36 | global snake_direction 37 | if snake_direction != "right": 38 | snake_direction = "left" 39 | 40 | 41 | def move_snake(): 42 | stamper.clearstamps() # Remove existing stamps made by stamper. 43 | 44 | new_head = snake[-1].copy() 45 | new_head[0] += offsets[snake_direction][0] 46 | new_head[1] += offsets[snake_direction][1] 47 | 48 | # Add new head to snake body. 49 | snake.append(new_head) 50 | 51 | # Remove last segment of snake. 52 | snake.pop(0) 53 | 54 | # Draw snake for the first time. 55 | for segment in snake: 56 | stamper.goto(segment[0], segment[1]) 57 | stamper.stamp() 58 | 59 | # Refresh screen 60 | screen.update() 61 | 62 | # Rinse and repeat 63 | turtle.ontimer(move_snake, DELAY) 64 | 65 | 66 | # Create a window where we will do our drawing. 67 | screen = turtle.Screen() 68 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 69 | screen.title("Snake") 70 | screen.bgcolor("pink") 71 | screen.tracer(0) # Turn off automatic animation. 72 | 73 | # Event handlers 74 | screen.listen() 75 | screen.onkey(go_up, "Up") 76 | screen.onkey(go_right, "Right") 77 | screen.onkey(go_down, "Down") 78 | screen.onkey(go_left, "Left") 79 | 80 | # Create a turtle to do your bidding 81 | stamper = turtle.Turtle() 82 | stamper.shape("square") 83 | stamper.penup() 84 | 85 | # Create snake as a list of coordinate pairs. 86 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 87 | snake_direction = "up" 88 | 89 | # Draw snake for the first time. 90 | for segment in snake: 91 | stamper.goto(segment[0], segment[1]) 92 | stamper.stamp() 93 | 94 | # Set animation in motion 95 | move_snake() 96 | 97 | # Finish nicely 98 | turtle.done() 99 | -------------------------------------------------------------------------------- /02_04/collision_detection.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics module 2 | import turtle 3 | 4 | # Define program constants 5 | WIDTH = 500 6 | HEIGHT = 500 7 | DELAY = 500 # Milliseconds 8 | 9 | offsets = { 10 | "up": (0, 20), 11 | "down": (0, -20), 12 | "left": (-20, 0), 13 | "right": (20, 0) 14 | } 15 | 16 | 17 | def go_up(): 18 | global snake_direction 19 | if snake_direction != "down": 20 | snake_direction = "up" 21 | 22 | 23 | def go_right(): 24 | global snake_direction 25 | if snake_direction != "left": 26 | snake_direction = "right" 27 | 28 | 29 | def go_down(): 30 | global snake_direction 31 | if snake_direction != "up": 32 | snake_direction = "down" 33 | 34 | 35 | def go_left(): 36 | global snake_direction 37 | if snake_direction != "right": 38 | snake_direction = "left" 39 | 40 | 41 | def game_loop(): 42 | stamper.clearstamps() # Remove existing stamps made by stamper. 43 | 44 | new_head = snake[-1].copy() 45 | new_head[0] += offsets[snake_direction][0] 46 | new_head[1] += offsets[snake_direction][1] 47 | 48 | # Check collisions 49 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 50 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 51 | turtle.bye() 52 | else: 53 | # Add new head to snake body. 54 | snake.append(new_head) 55 | 56 | # Remove last segment of snake. 57 | snake.pop(0) 58 | 59 | # Draw snake for the first time. 60 | for segment in snake: 61 | stamper.goto(segment[0], segment[1]) 62 | stamper.stamp() 63 | 64 | # Refresh screen 65 | screen.update() 66 | 67 | # Rinse and repeat 68 | turtle.ontimer(game_loop, DELAY) 69 | 70 | 71 | # Create a window where we will do our drawing. 72 | screen = turtle.Screen() 73 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 74 | screen.title("Snake") 75 | screen.bgcolor("pink") 76 | screen.tracer(0) # Turn off automatic animation. 77 | 78 | # Event handlers 79 | screen.listen() 80 | screen.onkey(go_up, "Up") 81 | screen.onkey(go_right, "Right") 82 | screen.onkey(go_down, "Down") 83 | screen.onkey(go_left, "Left") 84 | 85 | # Create a turtle to do your bidding 86 | stamper = turtle.Turtle() 87 | stamper.shape("square") 88 | stamper.penup() 89 | 90 | # Create snake as a list of coordinate pairs. 91 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 92 | snake_direction = "up" 93 | 94 | # Draw snake for the first time. 95 | for segment in snake: 96 | stamper.goto(segment[0], segment[1]) 97 | stamper.stamp() 98 | 99 | # Set animation in motion 100 | game_loop() 101 | 102 | # Finish nicely 103 | turtle.done() 104 | -------------------------------------------------------------------------------- /02_05/snake_food.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 500 7 | HEIGHT = 500 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 10 10 | 11 | offsets = { 12 | "up": (0, 20), 13 | "down": (0, -20), 14 | "left": (-20, 0), 15 | "right": (20, 0) 16 | } 17 | 18 | 19 | def go_up(): 20 | global snake_direction 21 | if snake_direction != "down": 22 | snake_direction = "up" 23 | 24 | 25 | def go_right(): 26 | global snake_direction 27 | if snake_direction != "left": 28 | snake_direction = "right" 29 | 30 | 31 | def go_down(): 32 | global snake_direction 33 | if snake_direction != "up": 34 | snake_direction = "down" 35 | 36 | 37 | def go_left(): 38 | global snake_direction 39 | if snake_direction != "right": 40 | snake_direction = "left" 41 | 42 | 43 | def game_loop(): 44 | stamper.clearstamps() # Remove existing stamps made by stamper. 45 | 46 | new_head = snake[-1].copy() 47 | new_head[0] += offsets[snake_direction][0] 48 | new_head[1] += offsets[snake_direction][1] 49 | 50 | # Check collisions 51 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 52 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 53 | turtle.bye() 54 | else: 55 | # Add new head to snake body. 56 | snake.append(new_head) 57 | 58 | # Check food collision 59 | if not food_collision(): 60 | snake.pop(0) # Keep the snake the same length unless fed. 61 | 62 | # Draw snake for the first time. 63 | for segment in snake: 64 | stamper.goto(segment[0], segment[1]) 65 | stamper.stamp() 66 | 67 | # Refresh screen 68 | screen.update() 69 | 70 | # Rinse and repeat 71 | turtle.ontimer(game_loop, DELAY) 72 | 73 | 74 | def food_collision(): 75 | global food_pos 76 | if get_distance(snake[-1], food_pos) < 20: 77 | food_pos = get_random_food_pos() 78 | food.goto(food_pos) 79 | return True 80 | return False 81 | 82 | 83 | def get_random_food_pos(): 84 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 85 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 86 | return (x, y) 87 | 88 | 89 | def get_distance(pos1, pos2): 90 | x1, y1 = pos1 91 | x2, y2 = pos2 92 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 93 | return distance 94 | 95 | 96 | # Create a window where we will do our drawing. 97 | screen = turtle.Screen() 98 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 99 | screen.title("Snake") 100 | screen.bgcolor("pink") 101 | screen.tracer(0) # Turn off automatic animation. 102 | 103 | # Event handlers 104 | screen.listen() 105 | screen.onkey(go_up, "Up") 106 | screen.onkey(go_right, "Right") 107 | screen.onkey(go_down, "Down") 108 | screen.onkey(go_left, "Left") 109 | 110 | # Create a turtle to do your bidding 111 | stamper = turtle.Turtle() 112 | stamper.shape("square") 113 | stamper.penup() 114 | 115 | # Create snake as a list of coordinate pairs. 116 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 117 | snake_direction = "up" 118 | 119 | # Draw snake for the first time. 120 | for segment in snake: 121 | stamper.goto(segment[0], segment[1]) 122 | stamper.stamp() 123 | 124 | # Food 125 | food = turtle.Turtle() 126 | food.shape("circle") 127 | food.color("red") 128 | food.shapesize(FOOD_SIZE / 20) 129 | food.penup() 130 | food_pos = get_random_food_pos() 131 | food.goto(food_pos) 132 | 133 | # Set animation in motion 134 | game_loop() 135 | 136 | # Finish nicely 137 | turtle.done() 138 | -------------------------------------------------------------------------------- /02_06/keeping_score.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 500 7 | HEIGHT = 500 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 10 10 | 11 | offsets = { 12 | "up": (0, 20), 13 | "down": (0, -20), 14 | "left": (-20, 0), 15 | "right": (20, 0) 16 | } 17 | 18 | 19 | def go_up(): 20 | global snake_direction 21 | if snake_direction != "down": 22 | snake_direction = "up" 23 | 24 | 25 | def go_right(): 26 | global snake_direction 27 | if snake_direction != "left": 28 | snake_direction = "right" 29 | 30 | 31 | def go_down(): 32 | global snake_direction 33 | if snake_direction != "up": 34 | snake_direction = "down" 35 | 36 | 37 | def go_left(): 38 | global snake_direction 39 | if snake_direction != "right": 40 | snake_direction = "left" 41 | 42 | 43 | def game_loop(): 44 | stamper.clearstamps() # Remove existing stamps made by stamper. 45 | 46 | new_head = snake[-1].copy() 47 | new_head[0] += offsets[snake_direction][0] 48 | new_head[1] += offsets[snake_direction][1] 49 | 50 | # Check collisions 51 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 52 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 53 | turtle.bye() 54 | else: 55 | # Add new head to snake body. 56 | snake.append(new_head) 57 | 58 | # Check food collision 59 | if not food_collision(): 60 | snake.pop(0) # Keep the snake the same length unless fed. 61 | 62 | # Draw snake for the first time. 63 | for segment in snake: 64 | stamper.goto(segment[0], segment[1]) 65 | stamper.stamp() 66 | 67 | # Refresh screen 68 | screen.title(f"Snake Game. Score: {score}") 69 | screen.update() 70 | 71 | # Rinse and repeat 72 | turtle.ontimer(game_loop, DELAY) 73 | 74 | 75 | def food_collision(): 76 | global food_pos, score 77 | if get_distance(snake[-1], food_pos) < 20: 78 | score += 1 # score = score + 1 79 | food_pos = get_random_food_pos() 80 | food.goto(food_pos) 81 | return True 82 | return False 83 | 84 | 85 | def get_random_food_pos(): 86 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 87 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 88 | return (x, y) 89 | 90 | 91 | def get_distance(pos1, pos2): 92 | x1, y1 = pos1 93 | x2, y2 = pos2 94 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 95 | return distance 96 | 97 | 98 | # Create a window where we will do our drawing. 99 | screen = turtle.Screen() 100 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 101 | screen.title("Snake") 102 | screen.bgcolor("pink") 103 | screen.tracer(0) # Turn off automatic animation. 104 | 105 | # Event handlers 106 | screen.listen() 107 | screen.onkey(go_up, "Up") 108 | screen.onkey(go_right, "Right") 109 | screen.onkey(go_down, "Down") 110 | screen.onkey(go_left, "Left") 111 | 112 | # Create a turtle to do your bidding 113 | stamper = turtle.Turtle() 114 | stamper.shape("square") 115 | stamper.penup() 116 | 117 | # Create snake as a list of coordinate pairs. 118 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 119 | snake_direction = "up" 120 | score = 0 121 | 122 | # Draw snake for the first time. 123 | for segment in snake: 124 | stamper.goto(segment[0], segment[1]) 125 | stamper.stamp() 126 | 127 | # Food 128 | food = turtle.Turtle() 129 | food.shape("circle") 130 | food.color("red") 131 | food.shapesize(FOOD_SIZE / 20) 132 | food.penup() 133 | food_pos = get_random_food_pos() 134 | food.goto(food_pos) 135 | 136 | # Set animation in motion 137 | game_loop() 138 | 139 | # Finish nicely 140 | turtle.done() 141 | -------------------------------------------------------------------------------- /02_07/game_reset.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 500 7 | HEIGHT = 500 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 10 10 | 11 | offsets = { 12 | "up": (0, 20), 13 | "down": (0, -20), 14 | "left": (-20, 0), 15 | "right": (20, 0) 16 | } 17 | 18 | 19 | def go_up(): 20 | global snake_direction 21 | if snake_direction != "down": 22 | snake_direction = "up" 23 | 24 | 25 | def go_right(): 26 | global snake_direction 27 | if snake_direction != "left": 28 | snake_direction = "right" 29 | 30 | 31 | def go_down(): 32 | global snake_direction 33 | if snake_direction != "up": 34 | snake_direction = "down" 35 | 36 | 37 | def go_left(): 38 | global snake_direction 39 | if snake_direction != "right": 40 | snake_direction = "left" 41 | 42 | 43 | def game_loop(): 44 | stamper.clearstamps() # Remove existing stamps made by stamper. 45 | 46 | new_head = snake[-1].copy() 47 | new_head[0] += offsets[snake_direction][0] 48 | new_head[1] += offsets[snake_direction][1] 49 | 50 | # Check collisions 51 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 52 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 53 | reset() 54 | else: 55 | # Add new head to snake body. 56 | snake.append(new_head) 57 | 58 | # Check food collision 59 | if not food_collision(): 60 | snake.pop(0) # Keep the snake the same length unless fed. 61 | 62 | # Draw snake for the first time. 63 | for segment in snake: 64 | stamper.goto(segment[0], segment[1]) 65 | stamper.stamp() 66 | 67 | # Refresh screen 68 | screen.title(f"Snake Game. Score: {score}") 69 | screen.update() 70 | 71 | # Rinse and repeat 72 | turtle.ontimer(game_loop, DELAY) 73 | 74 | 75 | def food_collision(): 76 | global food_pos, score 77 | if get_distance(snake[-1], food_pos) < 20: 78 | score += 1 # score = score + 1 79 | food_pos = get_random_food_pos() 80 | food.goto(food_pos) 81 | return True 82 | return False 83 | 84 | 85 | def get_random_food_pos(): 86 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 87 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 88 | return (x, y) 89 | 90 | 91 | def get_distance(pos1, pos2): 92 | x1, y1 = pos1 93 | x2, y2 = pos2 94 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 95 | return distance 96 | 97 | 98 | def reset(): 99 | global score, snake, snake_direction, food_pos 100 | score = 0 101 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 102 | snake_direction = "up" 103 | food_pos = get_random_food_pos() 104 | food.goto(food_pos) 105 | game_loop() 106 | 107 | 108 | # Create a window where we will do our drawing. 109 | screen = turtle.Screen() 110 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 111 | screen.title("Snake") 112 | screen.bgcolor("pink") 113 | screen.tracer(0) # Turn off automatic animation. 114 | 115 | # Event handlers 116 | screen.listen() 117 | screen.onkey(go_up, "Up") 118 | screen.onkey(go_right, "Right") 119 | screen.onkey(go_down, "Down") 120 | screen.onkey(go_left, "Left") 121 | 122 | # Create a turtle to do your bidding 123 | stamper = turtle.Turtle() 124 | stamper.shape("square") 125 | stamper.penup() 126 | 127 | # Food 128 | food = turtle.Turtle() 129 | food.shape("circle") 130 | food.color("red") 131 | food.shapesize(FOOD_SIZE / 20) 132 | food.penup() 133 | 134 | # Set animation in motion 135 | reset() 136 | 137 | # Finish nicely 138 | turtle.done() 139 | -------------------------------------------------------------------------------- /03_01/lambda_callbacks.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 500 7 | HEIGHT = 500 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 10 10 | 11 | offsets = { 12 | "up": (0, 20), 13 | "down": (0, -20), 14 | "left": (-20, 0), 15 | "right": (20, 0) 16 | } 17 | 18 | 19 | def bind_direction_keys(): 20 | screen.onkey(lambda: set_snake_direction("up"), "Up") 21 | screen.onkey(lambda: set_snake_direction("down"), "Down") 22 | screen.onkey(lambda: set_snake_direction("left"), "Left") 23 | screen.onkey(lambda: set_snake_direction("right"), "Right") 24 | 25 | 26 | def set_snake_direction(direction): 27 | global snake_direction 28 | if direction == "up": 29 | if snake_direction != "down": # No self-collision simply by pressing wrong key. 30 | snake_direction = "up" 31 | elif direction == "down": 32 | if snake_direction != "up": 33 | snake_direction = "down" 34 | elif direction == "left": 35 | if snake_direction != "right": 36 | snake_direction = "left" 37 | elif direction == "right": 38 | if snake_direction != "left": 39 | snake_direction = "right" 40 | 41 | 42 | def game_loop(): 43 | stamper.clearstamps() # Remove existing stamps made by stamper. 44 | 45 | new_head = snake[-1].copy() 46 | new_head[0] += offsets[snake_direction][0] 47 | new_head[1] += offsets[snake_direction][1] 48 | 49 | # Check collisions 50 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 51 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 52 | reset() 53 | else: 54 | # Add new head to snake body. 55 | snake.append(new_head) 56 | 57 | # Check food collision 58 | if not food_collision(): 59 | snake.pop(0) # Keep the snake the same length unless fed. 60 | 61 | # Draw snake for the first time. 62 | for segment in snake: 63 | stamper.goto(segment[0], segment[1]) 64 | stamper.stamp() 65 | 66 | # Refresh screen 67 | screen.title(f"Snake Game. Score: {score}") 68 | screen.update() 69 | 70 | # Rinse and repeat 71 | turtle.ontimer(game_loop, DELAY) 72 | 73 | 74 | def food_collision(): 75 | global food_pos, score 76 | if get_distance(snake[-1], food_pos) < 20: 77 | score += 1 # score = score + 1 78 | food_pos = get_random_food_pos() 79 | food.goto(food_pos) 80 | return True 81 | return False 82 | 83 | 84 | def get_random_food_pos(): 85 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 86 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 87 | return (x, y) 88 | 89 | 90 | def get_distance(pos1, pos2): 91 | x1, y1 = pos1 92 | x2, y2 = pos2 93 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 94 | return distance 95 | 96 | 97 | def reset(): 98 | global score, snake, snake_direction, food_pos 99 | score = 0 100 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 101 | snake_direction = "up" 102 | food_pos = get_random_food_pos() 103 | food.goto(food_pos) 104 | game_loop() 105 | 106 | 107 | # Create a window where we will do our drawing. 108 | screen = turtle.Screen() 109 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 110 | screen.title("Snake") 111 | screen.bgcolor("pink") 112 | screen.tracer(0) # Turn off automatic animation. 113 | 114 | # Event handlers 115 | screen.listen() 116 | bind_direction_keys() 117 | 118 | # Create a turtle to do your bidding 119 | stamper = turtle.Turtle() 120 | stamper.shape("square") 121 | stamper.penup() 122 | 123 | # Food 124 | food = turtle.Turtle() 125 | food.shape("circle") 126 | food.color("red") 127 | food.shapesize(FOOD_SIZE / 20) 128 | food.penup() 129 | 130 | # Set animation in motion 131 | reset() 132 | 133 | # Finish nicely 134 | turtle.done() 135 | -------------------------------------------------------------------------------- /03_02/messing.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 800 7 | HEIGHT = 600 8 | DELAY = 200 # Milliseconds 9 | FOOD_SIZE = 30 10 | 11 | offsets = { 12 | "up": (0, 20), 13 | "down": (0, -20), 14 | "left": (-20, 0), 15 | "right": (20, 0) 16 | } 17 | 18 | 19 | def bind_direction_keys(): 20 | screen.onkey(lambda: set_snake_direction("up"), "Up") 21 | screen.onkey(lambda: set_snake_direction("down"), "Down") 22 | screen.onkey(lambda: set_snake_direction("left"), "Left") 23 | screen.onkey(lambda: set_snake_direction("right"), "Right") 24 | 25 | 26 | def set_snake_direction(direction): 27 | global snake_direction 28 | if direction == "up": 29 | if snake_direction != "down": # No self-collision simply by pressing wrong key. 30 | snake_direction = "up" 31 | elif direction == "down": 32 | if snake_direction != "up": 33 | snake_direction = "down" 34 | elif direction == "left": 35 | if snake_direction != "right": 36 | snake_direction = "left" 37 | elif direction == "right": 38 | if snake_direction != "left": 39 | snake_direction = "right" 40 | 41 | 42 | def game_loop(): 43 | stamper.clearstamps() # Remove existing stamps made by stamper. 44 | 45 | new_head = snake[-1].copy() 46 | new_head[0] += offsets[snake_direction][0] 47 | new_head[1] += offsets[snake_direction][1] 48 | 49 | # Check collisions 50 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 51 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 52 | reset() 53 | else: 54 | # Add new head to snake body. 55 | snake.append(new_head) 56 | 57 | # Check food collision 58 | if not food_collision(): 59 | snake.pop(0) # Keep the snake the same length unless fed. 60 | 61 | # Draw snake for the first time. 62 | for segment in snake: 63 | stamper.goto(segment[0], segment[1]) 64 | stamper.stamp() 65 | 66 | # Refresh screen 67 | screen.title(f"Snake Game. Score: {score}") 68 | screen.update() 69 | 70 | # Rinse and repeat 71 | turtle.ontimer(game_loop, DELAY) 72 | 73 | 74 | def food_collision(): 75 | global food_pos, score 76 | if get_distance(snake[-1], food_pos) < 20: 77 | score += 1 # score = score + 1 78 | food_pos = get_random_food_pos() 79 | food.goto(food_pos) 80 | return True 81 | return False 82 | 83 | 84 | def get_random_food_pos(): 85 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 86 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 87 | return (x, y) 88 | 89 | 90 | def get_distance(pos1, pos2): 91 | x1, y1 = pos1 92 | x2, y2 = pos2 93 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 94 | return distance 95 | 96 | 97 | def reset(): 98 | global score, snake, snake_direction, food_pos 99 | score = 0 100 | snake = [[0, 0], [20, 0], [40, 0], [60, 0]] 101 | snake_direction = "up" 102 | food_pos = get_random_food_pos() 103 | food.goto(food_pos) 104 | game_loop() 105 | 106 | 107 | # Create a window where we will do our drawing. 108 | screen = turtle.Screen() 109 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 110 | screen.title("Snake") 111 | screen.bgcolor("yellow") 112 | screen.tracer(0) # Turn off automatic animation. 113 | 114 | # Event handlers 115 | screen.listen() 116 | bind_direction_keys() 117 | 118 | # Create a turtle to do your bidding 119 | stamper = turtle.Turtle() 120 | stamper.shape("circle") 121 | stamper.color("green") 122 | stamper.penup() 123 | 124 | # Food 125 | food = turtle.Turtle() 126 | food.shape("triangle") 127 | food.color("red") 128 | food.shapesize(FOOD_SIZE / 20) 129 | food.penup() 130 | 131 | # Set animation in motion 132 | reset() 133 | 134 | # Finish nicely 135 | turtle.done() 136 | -------------------------------------------------------------------------------- /03_03/assets/bg2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_03/assets/bg2.gif -------------------------------------------------------------------------------- /03_03/assets/snake-food-32x32.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_03/assets/snake-food-32x32.gif -------------------------------------------------------------------------------- /03_03/assets/snake-head-20x20.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_03/assets/snake-head-20x20.gif -------------------------------------------------------------------------------- /03_03/snake_game_with_graphics.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 800 7 | HEIGHT = 600 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 32 10 | SNAKE_SIZE = 20 11 | 12 | offsets = { 13 | "up": (0, SNAKE_SIZE), 14 | "down": (0, -SNAKE_SIZE), 15 | "left": (-SNAKE_SIZE, 0), 16 | "right": (SNAKE_SIZE, 0) 17 | } 18 | 19 | 20 | def bind_direction_keys(): 21 | screen.onkey(lambda: set_snake_direction("up"), "Up") 22 | screen.onkey(lambda: set_snake_direction("down"), "Down") 23 | screen.onkey(lambda: set_snake_direction("left"), "Left") 24 | screen.onkey(lambda: set_snake_direction("right"), "Right") 25 | 26 | 27 | def set_snake_direction(direction): 28 | global snake_direction 29 | if direction == "up": 30 | if snake_direction != "down": # No self-collision simply by pressing wrong key. 31 | snake_direction = "up" 32 | elif direction == "down": 33 | if snake_direction != "up": 34 | snake_direction = "down" 35 | elif direction == "left": 36 | if snake_direction != "right": 37 | snake_direction = "left" 38 | elif direction == "right": 39 | if snake_direction != "left": 40 | snake_direction = "right" 41 | 42 | 43 | def game_loop(): 44 | stamper.clearstamps() # Remove existing stamps made by stamper. 45 | 46 | new_head = snake[-1].copy() 47 | new_head[0] += offsets[snake_direction][0] 48 | new_head[1] += offsets[snake_direction][1] 49 | 50 | # Check collisions 51 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 52 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 53 | reset() 54 | else: 55 | # Add new head to snake body. 56 | snake.append(new_head) 57 | 58 | # Check food collision 59 | if not food_collision(): 60 | snake.pop(0) # Keep the snake the same length unless fed. 61 | 62 | # Draw snake. 63 | stamper.shape("assets/snake-head-20x20.gif") 64 | stamper.goto(snake[-1][0], snake[-1][1]) 65 | stamper.stamp() 66 | stamper.shape("circle") 67 | for segment in snake[:-1]: 68 | stamper.goto(segment[0], segment[1]) 69 | stamper.stamp() 70 | 71 | # Refresh screen 72 | screen.title(f"Snake Game. Score: {score}") 73 | screen.update() 74 | 75 | # Rinse and repeat 76 | turtle.ontimer(game_loop, DELAY) 77 | 78 | 79 | def food_collision(): 80 | global food_pos, score 81 | if get_distance(snake[-1], food_pos) < 20: 82 | score += 1 # score = score + 1 83 | food_pos = get_random_food_pos() 84 | food.goto(food_pos) 85 | return True 86 | return False 87 | 88 | 89 | def get_random_food_pos(): 90 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 91 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 92 | return (x, y) 93 | 94 | 95 | def get_distance(pos1, pos2): 96 | x1, y1 = pos1 97 | x2, y2 = pos2 98 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 99 | return distance 100 | 101 | 102 | def reset(): 103 | global score, snake, snake_direction, food_pos 104 | score = 0 105 | snake = [[0, 0], [SNAKE_SIZE, 0], [SNAKE_SIZE * 2, 0], [SNAKE_SIZE * 3, 0]] 106 | snake_direction = "up" 107 | food_pos = get_random_food_pos() 108 | food.goto(food_pos) 109 | game_loop() 110 | 111 | 112 | # Create a window where we will do our drawing. 113 | screen = turtle.Screen() 114 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 115 | screen.title("Snake") 116 | screen.bgpic("assets/bg2.gif") 117 | screen.register_shape("assets/snake-food-32x32.gif") 118 | screen.register_shape("assets/snake-head-20x20.gif") 119 | screen.tracer(0) # Turn off automatic animation. 120 | 121 | # Event handlers 122 | screen.listen() 123 | bind_direction_keys() 124 | 125 | # Create a turtle to do your bidding 126 | stamper = turtle.Turtle() 127 | stamper.shape("circle") 128 | stamper.color("#009ef1") 129 | stamper.penup() 130 | 131 | # Food 132 | food = turtle.Turtle() 133 | food.shape("assets/snake-food-32x32.gif") 134 | food.shapesize(FOOD_SIZE / 20) 135 | food.penup() 136 | 137 | # Set animation in motion 138 | reset() 139 | 140 | # Finish nicely 141 | turtle.done() 142 | -------------------------------------------------------------------------------- /03_04/assets/bg2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_04/assets/bg2.gif -------------------------------------------------------------------------------- /03_04/assets/snake-food-32x32.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_04/assets/snake-food-32x32.gif -------------------------------------------------------------------------------- /03_04/assets/snake-head-20x20.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_04/assets/snake-head-20x20.gif -------------------------------------------------------------------------------- /03_04/snake_game_with_graphics.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 800 7 | HEIGHT = 600 8 | DELAY = 100 # Milliseconds 9 | FOOD_SIZE = 32 10 | SNAKE_SIZE = 20 11 | 12 | offsets = { 13 | "up": (0, SNAKE_SIZE), 14 | "down": (0, -SNAKE_SIZE), 15 | "left": (-SNAKE_SIZE, 0), 16 | "right": (SNAKE_SIZE, 0) 17 | } 18 | 19 | 20 | def bind_direction_keys(): 21 | screen.onkey(lambda: set_snake_direction("up"), "Up") 22 | screen.onkey(lambda: set_snake_direction("down"), "Down") 23 | screen.onkey(lambda: set_snake_direction("left"), "Left") 24 | screen.onkey(lambda: set_snake_direction("right"), "Right") 25 | 26 | 27 | def set_snake_direction(direction): 28 | global snake_direction 29 | if direction == "up": 30 | if snake_direction != "down": # No self-collision simply by pressing wrong key. 31 | snake_direction = "up" 32 | elif direction == "down": 33 | if snake_direction != "up": 34 | snake_direction = "down" 35 | elif direction == "left": 36 | if snake_direction != "right": 37 | snake_direction = "left" 38 | elif direction == "right": 39 | if snake_direction != "left": 40 | snake_direction = "right" 41 | 42 | 43 | def game_loop(): 44 | stamper.clearstamps() # Remove existing stamps made by stamper. 45 | 46 | new_head = snake[-1].copy() 47 | new_head[0] += offsets[snake_direction][0] 48 | new_head[1] += offsets[snake_direction][1] 49 | 50 | # Check collisions 51 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 52 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 53 | reset() 54 | else: 55 | # Add new head to snake body. 56 | snake.append(new_head) 57 | 58 | # Check food collision 59 | if not food_collision(): 60 | snake.pop(0) # Keep the snake the same length unless fed. 61 | 62 | # Draw snake. 63 | stamper.shape("assets/snake-head-20x20.gif") 64 | stamper.goto(snake[-1][0], snake[-1][1]) 65 | stamper.stamp() 66 | stamper.shape("circle") 67 | for segment in snake[:-1]: 68 | stamper.goto(segment[0], segment[1]) 69 | stamper.stamp() 70 | 71 | # Refresh screen 72 | screen.title(f"Snake Game. Score: {score}") 73 | screen.update() 74 | 75 | # Rinse and repeat 76 | turtle.ontimer(game_loop, DELAY) 77 | 78 | 79 | def food_collision(): 80 | global food_pos, score 81 | if get_distance(snake[-1], food_pos) < 20: 82 | score += 1 # score = score + 1 83 | food_pos = get_random_food_pos() 84 | food.goto(food_pos) 85 | return True 86 | return False 87 | 88 | 89 | def get_random_food_pos(): 90 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 91 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 92 | return (x, y) 93 | 94 | 95 | def get_distance(pos1, pos2): 96 | x1, y1 = pos1 97 | x2, y2 = pos2 98 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 99 | return distance 100 | 101 | 102 | def reset(): 103 | global score, snake, snake_direction, food_pos 104 | score = 0 105 | snake = [[0, 0], [SNAKE_SIZE, 0], [SNAKE_SIZE * 2, 0], [SNAKE_SIZE * 3, 0]] 106 | snake_direction = "up" 107 | food_pos = get_random_food_pos() 108 | food.goto(food_pos) 109 | game_loop() 110 | 111 | 112 | # Create a window where we will do our drawing. 113 | screen = turtle.Screen() 114 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 115 | screen.title("Snake") 116 | screen.bgpic("assets/bg2.gif") 117 | screen.register_shape("assets/snake-food-32x32.gif") 118 | screen.register_shape("assets/snake-head-20x20.gif") 119 | screen.tracer(0) # Turn off automatic animation. 120 | 121 | # Event handlers 122 | screen.listen() 123 | bind_direction_keys() 124 | 125 | # Create a turtle to do your bidding 126 | stamper = turtle.Turtle() 127 | stamper.shape("circle") 128 | stamper.color("#009ef1") 129 | stamper.penup() 130 | 131 | # Food 132 | food = turtle.Turtle() 133 | food.shape("assets/snake-food-32x32.gif") 134 | food.shapesize(FOOD_SIZE / 20) 135 | food.penup() 136 | 137 | # Set animation in motion 138 | reset() 139 | 140 | # Finish nicely 141 | turtle.done() 142 | -------------------------------------------------------------------------------- /03_05/assets/bg2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_05/assets/bg2.gif -------------------------------------------------------------------------------- /03_05/assets/snake-food-32x32.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_05/assets/snake-food-32x32.gif -------------------------------------------------------------------------------- /03_05/assets/snake-head-20x20.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/snake-game-python-2896343/7322eb02320a5344b944cd5833651b5a367ced47/03_05/assets/snake-head-20x20.gif -------------------------------------------------------------------------------- /03_05/high_score.txt: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /03_05/snake_game_with_graphics.py: -------------------------------------------------------------------------------- 1 | # Import the Turtle Graphics and random modules 2 | import turtle 3 | import random 4 | 5 | # Define program constants 6 | WIDTH = 800 7 | HEIGHT = 600 8 | DELAY = 75 # Milliseconds 9 | FOOD_SIZE = 32 10 | SNAKE_SIZE = 20 11 | 12 | offsets = { 13 | "up": (0, SNAKE_SIZE), 14 | "down": (0, -SNAKE_SIZE), 15 | "left": (-SNAKE_SIZE, 0), 16 | "right": (SNAKE_SIZE, 0) 17 | } 18 | 19 | # High score 20 | high_score = 0 21 | 22 | # Load the high score if it exists 23 | try: 24 | with open("high_score.txt", "r") as file: 25 | high_score = int(file.read()) 26 | except FileNotFoundError: 27 | pass 28 | 29 | def update_high_score(): 30 | global high_score 31 | if score > high_score: 32 | high_score = score 33 | with open("high_score.txt", "w") as file: 34 | file.write(str(high_score)) 35 | 36 | 37 | def bind_direction_keys(): 38 | screen.onkey(lambda: set_snake_direction("up"), "Up") 39 | screen.onkey(lambda: set_snake_direction("down"), "Down") 40 | screen.onkey(lambda: set_snake_direction("left"), "Left") 41 | screen.onkey(lambda: set_snake_direction("right"), "Right") 42 | 43 | 44 | def set_snake_direction(direction): 45 | global snake_direction 46 | if direction == "up": 47 | if snake_direction != "down": # No self-collision simply by pressing wrong key. 48 | snake_direction = "up" 49 | elif direction == "down": 50 | if snake_direction != "up": 51 | snake_direction = "down" 52 | elif direction == "left": 53 | if snake_direction != "right": 54 | snake_direction = "left" 55 | elif direction == "right": 56 | if snake_direction != "left": 57 | snake_direction = "right" 58 | 59 | 60 | def game_loop(): 61 | stamper.clearstamps() # Remove existing stamps made by stamper. 62 | 63 | new_head = snake[-1].copy() 64 | new_head[0] += offsets[snake_direction][0] 65 | new_head[1] += offsets[snake_direction][1] 66 | 67 | # Check collisions 68 | if new_head in snake or new_head[0] < - WIDTH / 2 or new_head[0] > WIDTH / 2 \ 69 | or new_head[1] < - HEIGHT / 2 or new_head[1] > HEIGHT / 2: 70 | reset() 71 | else: 72 | # Add new head to snake body. 73 | snake.append(new_head) 74 | 75 | # Check food collision 76 | if not food_collision(): 77 | snake.pop(0) # Keep the snake the same length unless fed. 78 | 79 | # Draw snake. 80 | stamper.shape("assets/snake-head-20x20.gif") 81 | stamper.goto(snake[-1][0], snake[-1][1]) 82 | stamper.stamp() 83 | stamper.shape("circle") 84 | for segment in snake[:-1]: 85 | stamper.goto(segment[0], segment[1]) 86 | stamper.stamp() 87 | 88 | # Refresh screen 89 | screen.title(f"Snake Game. Score: {score} High Score: {high_score}") 90 | screen.update() 91 | 92 | # Rinse and repeat 93 | turtle.ontimer(game_loop, DELAY) 94 | 95 | 96 | def food_collision(): 97 | global food_pos, score 98 | if get_distance(snake[-1], food_pos) < 20: 99 | score += 1 # score = score + 1 100 | update_high_score() 101 | food_pos = get_random_food_pos() 102 | food.goto(food_pos) 103 | return True 104 | return False 105 | 106 | 107 | def get_random_food_pos(): 108 | x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE) 109 | y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE) 110 | return (x, y) 111 | 112 | 113 | def get_distance(pos1, pos2): 114 | x1, y1 = pos1 115 | x2, y2 = pos2 116 | distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 # Pythagoras' Theorem 117 | return distance 118 | 119 | 120 | def reset(): 121 | global score, snake, snake_direction, food_pos 122 | score = 0 123 | snake = [[0, 0], [SNAKE_SIZE, 0], [SNAKE_SIZE * 2, 0], [SNAKE_SIZE * 3, 0]] 124 | snake_direction = "up" 125 | food_pos = get_random_food_pos() 126 | food.goto(food_pos) 127 | game_loop() 128 | 129 | 130 | # Create a window where we will do our drawing. 131 | screen = turtle.Screen() 132 | screen.setup(WIDTH, HEIGHT) # Set the dimensions of the Turtle Graphics window. 133 | screen.title("Snake") 134 | screen.bgpic("assets/bg2.gif") 135 | screen.register_shape("assets/snake-food-32x32.gif") 136 | screen.register_shape("assets/snake-head-20x20.gif") 137 | screen.tracer(0) # Turn off automatic animation. 138 | 139 | # Event handlers 140 | screen.listen() 141 | bind_direction_keys() 142 | 143 | # Create a turtle to do your bidding 144 | stamper = turtle.Turtle() 145 | stamper.shape("circle") 146 | stamper.color("#009ef1") 147 | stamper.penup() 148 | 149 | # Food 150 | food = turtle.Turtle() 151 | food.shape("assets/snake-food-32x32.gif") 152 | food.shapesize(FOOD_SIZE / 20) 153 | food.penup() 154 | 155 | # Set animation in motion 156 | reset() 157 | 158 | # Finish nicely 159 | turtle.done() 160 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2024 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | Please note, this project may automatically load third party code from external 8 | repositories (for example, NPM modules, Composer packages, or other dependencies). 9 | If so, such third party code may be subject to other license terms than as set 10 | forth above. In addition, such third party code may also depend on and load 11 | multiple tiers of dependencies. Please review the applicable licenses of the 12 | additional dependencies. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building the Classic Snake Game with Python 2 | This is the repository for the LinkedIn Learning course `Building the Classic Snake Game with Python`. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![lil-thumbnail-url] 5 | 6 | Are you looking for a fun, meaningful way to level up your Python programming skills? In this course, instructor Robin Andrews shows you how to put together what you need to know to build the Python version of a classic Snake game. Robin introduces you to turtle graphics and how you can use and control animation using Python turtle graphics. He explains global variables and shows you how to draw with turtle graphics by using stamps. With these pieces in place, it’s time to work on the game itself! Robin walks you through how to represent the snake, move it around the screen, and control the snake’s direction. He discusses the game loop that is used to control the game and also goes over how to add snake food to the game, implement a scoring system, and reset the game. Robin finishes up with advice on how to use Lambda expressions to avoid repetition in your game and some fun ways to personalize your game. 7 | 8 | _See the readme file in the main branch for updated instructions and information._ 9 | ## Instructions 10 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access. 11 | 12 | ## Branches 13 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter. 14 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course. 15 | 16 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this: 17 | 18 | error: Your local changes to the following files would be overwritten by checkout: [files] 19 | Please commit your changes or stash them before you switch branches. 20 | Aborting 21 | 22 | To resolve this issue: 23 | 24 | Add changes to git using this command: git add . 25 | Commit changes using this command: git commit -m "some message" 26 | 27 | ## Installing 28 | 1. To use these exercise files, you must have the following installed: 29 | - Python 3 30 | 2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree. 31 | 32 | 33 | [0]: # (Replace these placeholder URLs with actual course URLs) 34 | 35 | [lil-course-url]: https://www.linkedin.com/learning/building-the-classic-snake-game-with-python 36 | [lil-thumbnail-url]: https://cdn.lynda.com/course/2896343/2896343-1634664622455-16x9.jpg 37 | 38 | --------------------------------------------------------------------------------