Python → Processing → Pong Level 2
Pong Level 2 — score, game over i restart
U prethodnoj lekciji napravili smo osnovnu verziju igre: Mini projekat: Pong . Sada dodajemo:
- Brojanje poena
- Game over stanje
- Restart igre
1. Dodavanje promenljivih
# Lopta
ball_x = 300
ball_y = 200
dx = 4
dy = 3
ball_size = 20
# Palica
paddle_width = 100
paddle_height = 15
# Score i stanje igre
score = 0
game_over = False
2. Funkcija resetGame()
def resetGame():
global ball_x, ball_y, dx, dy, score, game_over
ball_x = width / 2
ball_y = height / 2
dx = 4
dy = 3
score = 0
game_over = False
□ Objašnjenje reset funkcije
Kratak opis: Resetuje sve promenljive na početne vrednosti kada igra završi ili igrač želi restart.
Proširenja: Možeš dodati animaciju ili efekat zvuka pri restartu.
3. Glavna logika igre
def setup():
size(600, 400)
textSize(20)
def draw():
global ball_x, ball_y, dx, dy, score, game_over
background(30)
if game_over:
fill(255)
textAlign(CENTER)
text("GAME OVER", width/2, height/2)
text("Pritisni R za restart", width/2, height/2 + 40)
return
# Lopta
fill(255)
ellipse(ball_x, ball_y, ball_size, ball_size)
# Palica
rect(mouseX - paddle_width/2, height - 40,
paddle_width, paddle_height)
# Pomeranje
ball_x += dx
ball_y += dy
# Zidovi
if ball_x < ball_size/2 or ball_x > width - ball_size/2:
dx = -dx
if ball_y < ball_size/2:
dy = -dy
# Sudar sa palicom
if (ball_y > height - 50 and
mouseX - paddle_width/2 < ball_x < mouseX + paddle_width/2):
dy = -dy
score += 1
# Pad lopte (game over)
if ball_y > height:
game_over = True
# Prikaz score-a
fill(255)
textAlign(LEFT)
text("Score: " + str(score), 20, 30)
□ Objašnjenje logike draw()
Kratak opis: Draw funkcija crta sve elemente, pomera loptu, detektuje sudare i prikazuje score.
Proširenja: Dodaj promenljivu brzinu ili boje koje se menjaju sa score-om.
4. Restart igre
def keyPressed():
if key == 'r' or key == 'R':
resetGame()
□ Objašnjenje keyPressed()
Kratak opis: Omogućava restart igre pritiskom na taster R.
Šta smo dodali?
- Stanje igre (game_over)
- Brojač poena
- Funkciju za reset
- Prikaz teksta na ekranu
Tip: Eksperimentiši sa veličinom lopte i palice, dodaj više boja ili promeni brzinu lopte kako bi povećao izazov.
Izazov (Level 3 ideja)
- Povećavaj brzinu lopte sa score-om
- Dodaj zvuk pri sudaru
- Dodaj dva igrača (multi-player)
- Dodaj meni i opcije pauze