Step 4: Only When Sure چالش 4 از جلسهی 32، سخت
قدم ۴. knn حالا دو چیز برگرداند: return best, votes[best]. در update(): label, sure = knn(photo)؛ اگر sure >= 4 بود guess = label، وگرنه guess = "not sure" (و سبد تکان نمیخورد). آخر، چراغ را کم کن، بازی کن و بالای update یک خط توضیح بنویس که با # low light: شروع شود و بگوید چه دیدی.
import pgzrun
import cam
WIDTH = 400
HEIGHT = 300
TITLE = "Play with Your Hand"
basket = Rect(170, 270, 60, 16)
fruit = [200, 0]
score = 0
guess = "none"
memory = cam.photos(size=8, labels=["left", "right", "none"])
counts = {}
for label, photo in memory:
counts[label] = counts.get(label, 0) + 1
info = "photos:"
for label in counts:
info = info + " " + label + " " + str(counts[label])
def drop_new():
fruit[0] = (fruit[0] * 7 + 90) % 360 + 20
fruit[1] = 0
def fall():
global score
fruit[1] += 3
if fruit[1] > 300:
drop_new()
if basket.colliderect(Rect(fruit[0] - 8, fruit[1] - 8, 16, 16)):
score += 1
drop_new()
def distance(a, b):
total = 0
for r in range(8):
for c in range(8):
total += abs(a[r][c] - b[r][c])
return total
def knn(photo):
pairs = []
for label, ex in memory:
pairs.append((distance(photo, ex), label))
pairs.sort()
votes = {}
for d, label in pairs[:5]:
votes[label] = votes.get(label, 0) + 1
best = pairs[0][1]
for label in votes:
if votes[label] > votes[best]:
best = label
return best
def update():
global guess
fall()
photo = cam.live(size=8)
guess = knn(photo)
if guess == "left":
basket.x -= 5
elif guess == "right":
basket.x += 5
if basket.x < 0:
basket.x = 0
if basket.x > 340:
basket.x = 340
def draw():
screen.fill("black")
screen.draw.filled_rect(basket, "orange")
screen.draw.filled_circle((fruit[0], fruit[1]), 8, "red")
screen.draw.text("score: " + str(score), (10, 10), fontsize=28, color="white")
screen.draw.text("I see: " + guess, (10, 40), fontsize=28, color="yellow")
screen.draw.text(info, (10, 70), fontsize=20, color="gray")
pgzrun.go()
راهنما و جواب این چالش · برگشت به درس جلسهی 32: پروژه: بازی با دست
بیشتر بخوان: بازیسازی با پایتون و Pygame Zero