-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfruitGame.py
More file actions
289 lines (254 loc) · 9.3 KB
/
fruitGame.py
File metadata and controls
289 lines (254 loc) · 9.3 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import cv2
import mediapipe as mp
import random
import pygame
import numpy as np
import os
# --- Pygame başlat ---
pygame.mixer.init()
slice_sound = pygame.mixer.Sound('slice_sound.wav')
pygame.mixer.music.load('Eggy Toast - Fun.mp3')
pygame.mixer.music.play(-1)
# --- Meyve görsellerini yükle ---
def load_fruit_images():
fruits_imgs = []
folder = os.path.join(os.path.dirname(__file__), 'fruits')
for file in os.listdir(folder):
if file.lower().endswith('.png'):
path = os.path.join(folder, file)
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
if img is not None:
if img.shape[2] == 3:
alpha_channel = np.ones((img.shape[0], img.shape[1], 1), dtype=img.dtype) * 255
img = np.concatenate((img, alpha_channel), axis=2)
img = cv2.resize(img, (100, 100), interpolation=cv2.INTER_AREA)
fruits_imgs.append(img)
return fruits_imgs
fruit_images = load_fruit_images()
# --- Kalp görseli yükle ---
life_img_path = os.path.join(os.path.dirname(__file__), 'life.png')
life_img = cv2.imread(life_img_path, cv2.IMREAD_UNCHANGED)
if life_img is not None:
if life_img.shape[2] == 3:
alpha_channel = np.ones((life_img.shape[0], life_img.shape[1], 1), dtype=life_img.dtype) * 255
life_img = np.concatenate((life_img, alpha_channel), axis=2)
life_img = cv2.resize(life_img, (100, 100), interpolation=cv2.INTER_AREA)
else:
print("Life görseli yüklenemedi!")
# --- Overlay fonksiyonu ---
def overlay_image(background, overlay, pos):
if overlay.shape[2] != 4:
return
x, y = pos
h, w = overlay.shape[:2]
if x < 0 or y < 0 or x + w > background.shape[1] or y + h > background.shape[0]:
return
overlay_img = overlay[:, :, :3]
mask = overlay[:, :, 3]
alpha = mask / 255.0
roi = background[y:y+h, x:x+w]
for c in range(3):
roi[:, :, c] = (alpha * overlay_img[:, :, c] + (1 - alpha) * roi[:, :, c])
background[y:y+h, x:x+w] = roi
# --- Fruit sınıfı ---
class Fruit:
def __init__(self, w, h):
self.gravity = 0.1
self.radius = 50
self.x = random.randint(self.radius, w - self.radius)
self.y = 0
self.speed_y = random.uniform(4, 6)
self.speed_x = random.uniform(-3, 3)
self.sliced = False
self.img = random.choice(fruit_images) if fruit_images else None
def move(self):
self.speed_y += self.gravity
self.y += self.speed_y
self.x += self.speed_x
# Kenarlardan seker
if self.x - self.radius < 0:
self.x = self.radius
self.speed_x = abs(self.speed_x)
elif self.x + self.radius > 960:
self.x = 960 - self.radius
self.speed_x = -abs(self.speed_x)
# Taşmayı önle
self.x = np.clip(self.x, self.radius, 960 - self.radius)
def draw(self, frame):
if not self.sliced and self.img is not None:
overlay_image(frame, self.img, (int(self.x - self.radius), int(self.y - self.radius)))
def check_collision(self, hand_pos):
if self.sliced:
return False
hx, hy = hand_pos
distance = ((self.x - hx) ** 2 + (self.y - hy) ** 2) ** 0.5
if distance < self.radius + 25:
self.sliced = True
pygame.mixer.Sound.play(slice_sound)
return True
return False
# --- Life sınıfı ---
class Life:
def __init__(self, w, h):
self.radius = 50
self.x = random.randint(self.radius, w - self.radius)
self.y = 0
self.gravity = 0.1
self.speed_y = random.uniform(4, 6)
self.speed_x = random.uniform(-1, 1)
self.caught = False
self.img = life_img
def move(self):
self.speed_y += self.gravity
self.y += self.speed_y
self.x += self.speed_x
if self.x - self.radius < 0:
self.x = self.radius
self.speed_x = abs(self.speed_x)
elif self.x + self.radius > 960:
self.x = 960 - self.radius
self.speed_x = -abs(self.speed_x)
self.x = np.clip(self.x, self.radius, 960 - self.radius)
def draw(self, frame):
if not self.caught and self.img is not None:
overlay_image(frame, self.img, (int(self.x - self.radius), int(self.y - self.radius)))
def check_collision(self, hand_pos):
if self.caught:
return False
hx, hy = hand_pos
distance = ((self.x - hx) ** 2 + (self.y - hy) ** 2) ** 0.5
if distance < self.radius + 25:
self.caught = True
pygame.mixer.Sound.play(slice_sound)
return True
return False
# --- El takibi başlat ---
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(max_num_hands=1, min_detection_confidence=0.6)
cap = cv2.VideoCapture(0)
cv2.namedWindow("Fruit Game", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Fruit Game", 960, 720)
screen_w, screen_h = 1080, 1080
cv2.moveWindow("Fruit Game", (screen_w - 960) // 2, (screen_h - 720) // 2)
fruits = []
life = None
life_dropped = False
score = 0
max_score = 100
spawn_timer = 0
trail_points = []
max_trail_length = 20
game_started = False
game_over = False
colors = [(255, 0, 0), (255, 165, 0), (255, 255, 0),
(0, 255, 0), (0, 127, 255), (0, 0, 255), (139, 0, 255)]
lives = 2
max_lives = 3
missed_in_a_row = 0
# --- Ana döngü ---
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1)
h, w, _ = frame.shape
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
result = hands.process(rgb_frame)
hand_pos = None
if result.multi_hand_landmarks and game_started and not game_over:
for handLms in result.multi_hand_landmarks:
lm = handLms.landmark[8]
cx, cy = int(lm.x * w), int(lm.y * h)
hand_pos = (cx, cy)
trail_points.append(hand_pos)
if len(trail_points) > max_trail_length:
trail_points.pop(0)
else:
trail_points = []
for i in range(1, len(trail_points)):
thickness = int(10 * (1 - i / max_trail_length)) + 2
color = colors[i % len(colors)]
p1, p2 = trail_points[i-1], trail_points[i]
cv2.line(frame, p1, p2, color, thickness=thickness, lineType=cv2.LINE_AA)
if not game_started:
text = "Press SPACE to Start"
size = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 1.2, 2)[0]
text_x = (w - size[0]) // 2
text_y = (h + size[1]) // 2
cv2.putText(frame, text, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)
elif game_over:
cv2.putText(frame, 'Game Over' if lives <= 0 else 'You Win!', (w // 6, h // 2 - 40), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
(0, 0, 255) if lives <= 0 else (0, 255, 0), 4)
cv2.putText(frame, f'Final Score: {score}', (w // 3, h // 2 + 20), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 3)
cv2.putText(frame, "Press R to Restart or Q to Quit", (w // 6, h - 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
else:
# Life düşür
if not life_dropped and random.random() < 0.002:
life = Life(w, h)
life_dropped = True
if spawn_timer <= 0:
fruits.append(Fruit(w, h))
spawn_timer = random.randint(10, 30)
spawn_timer -= 1
fruits_to_remove = []
missed_this_frame = 0
for fruit in fruits:
fruit.move()
fruit.draw(frame)
if hand_pos and fruit.check_collision(hand_pos):
score += 1
missed_in_a_row = 0
elif fruit.y > h and not fruit.sliced:
fruits_to_remove.append(fruit)
missed_this_frame += 1
for f in fruits_to_remove:
fruits.remove(f)
if missed_this_frame > 0:
missed_in_a_row += missed_this_frame
if missed_in_a_row >= 3:
lives -= 1
missed_in_a_row = 0
if lives <= 0:
game_over = True
if life is not None:
life.move()
life.draw(frame)
if hand_pos and life.check_collision(hand_pos):
if lives < max_lives:
lives += 1
life = None
elif life.y > h:
life = None
cv2.putText(frame, f'Score: {score}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 0), 3)
cv2.putText(frame, f'Lives: {lives}', (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)
if score >= max_score:
game_over = True
cv2.imshow("Fruit Game", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord(' '):
if not game_started:
game_started = True
score = 0
fruits = []
life = None
life_dropped = False
spawn_timer = 0
lives = 2
missed_in_a_row = 0
game_over = False
elif key == ord('r'):
if game_over:
game_started = True
score = 0
fruits = []
life = None
life_dropped = False
spawn_timer = 0
lives = 2
missed_in_a_row = 0
game_over = False
cap.release()
cv2.destroyAllWindows()
pygame.mixer.music.stop()