-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek15.py
More file actions
80 lines (64 loc) · 2.24 KB
/
week15.py
File metadata and controls
80 lines (64 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Week 15: Catch the Stars (Collision Detection + Score)
# Goal: Implement collision detection and scoring
# New concept: ERROR HANDLING with try/except
import random
WIDTH = 700
HEIGHT = 500
# Player position (using list for [x, y])
player = [WIDTH//2, HEIGHT//2]
speed = 5
# Star position
star = [random.randint(20, WIDTH-20), random.randint(20, HEIGHT-20)]
score = 0
def distance(a, b):
"""
Calculate distance between two points.
Uses Pythagorean theorem: √(dx² + dy²)
Args:
a: [x, y] position of first object
b: [x, y] position of second object
Returns:
Distance in pixels (float)
"""
dx = a[0] - b[0]
dy = a[1] - b[1]
return (dx*dx + dy*dy) ** 0.5 # ** 0.5 is square root
def respawn_star():
"""Move star to new random position"""
star[0] = random.randint(20, WIDTH-20)
star[1] = random.randint(20, HEIGHT-20)
def update():
global score
# Player movement
if keyboard.left: player[0] -= speed
if keyboard.right: player[0] += speed
if keyboard.up: player[1] -= speed
if keyboard.down: player[1] += speed
# Boundary checking
player[0] = max(10, min(WIDTH-10, player[0]))
player[1] = max(10, min(HEIGHT-10, player[1]))
# NEW CONCEPT: ERROR HANDLING
# Sometimes distance() might fail - let's handle it safely
try:
# Collision detection - check if player touches star
if distance(player, star) < 20:
score += 1
respawn_star()
except Exception as e:
# If something goes wrong, print error but keep game running
print(f"Collision check error: {e}")
def draw():
screen.clear()
screen.fill('darkblue')
# Display score
screen.draw.text(f"Score: {score}", (20, 20), color='white', fontsize=30)
# Draw player (white circle)
screen.draw.filled_circle(tuple(player), 10, "white")
# Draw star (yellow circle)
screen.draw.filled_circle(tuple(star), 8, "yellow")
# === KEY CONCEPTS ===
# 1. Lists for positions: player[0] = x, player[1] = y
# 2. Distance formula for collision detection
# 3. try/except for error handling (new!)
# 4. tuple() converts list [x,y] to tuple (x,y) for drawing
# 5. Collision threshold: distance < 20 means "touching"