forked from gumbykid/Climbing-Games
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.py
More file actions
463 lines (361 loc) · 15.5 KB
/
Copy pathTimer.py
File metadata and controls
463 lines (361 loc) · 15.5 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
import random
from turtle import *
import time
from datetime import timedelta
import pygame
# import os
current_milli_time = lambda: int(round(time.time() * 1000))
class Timer(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
# False = timer deactivated
self.state = False
self.box_game = False
# Change to max resolution
root.minsize(1920, 1080)
root.maxsize(1920, 1080)
# Full screen
root.overrideredirect(1)
# Saves each climber's score
self.scores = {}
# Allows first score to become high score
self.last_score = 999
# Tracks the lowest time
self.highscore_var = StringVar()
self.highscore_var.set('No Highscore')
# Different pre-made dot arrangements, each time app is opened one will be chosen randomly
# Images are in same directory as code (GIF ONLY)
# directory = os.getcwd()
self.image_list = ['dots.gif', '4_up_left.gif', '5_up_left.gif', '6_up_left.gif']
# Set background image
self.this_image = random.choice(self.image_list)
self.background_image = PhotoImage(file=self.this_image)
self.background_label = Label(root, image=self.background_image)
self.background_label.photo = self.background_image
self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
# Time structure [min, sec, centsec]
self.timer = [0, 0, 0]
self.starttime = 0
# Minutes are not used, but available for longer games
self.pattern = '{1:02d}:{2:02d}'
# self.pattern = '{0:02d}:{1:02d}:{2:02d}'
# Display time
self.timeText = Label(root, text='00:00', font=('Evogria', 60), foreground='white', background='black')
self.timeText.pack(side='top', expand=False)
# Display high score
self.highscore = Label(root, textvariable=self.highscore_var, font=('Evogria', 20), foreground='yellow', background='black')
self.highscore.pack(side='top', expand=False)
# When space is pressed, timer starts/stops
root.bind('<Tab>', self.start)
root.bind('<Escape>', self.quit)
root.bind('<Right>', self.next)
root.bind('<Left>', self.next)
root.bind('<Down>', self.reset)
root.bind('<F1>', self.randomize)
root.bind('<F2>', self.box)
root.bind('<Return>', self.save)
# Initialize app
self.pack()
self.update_timeText()
# All widgets are deleted and re-made, used to keep formatting correct when displaying new info
def reset(self, event):
self.background_image = PhotoImage(file=self.this_image)
self.background_label = Label(root, image=self.background_image)
self.background_label.photo = self.background_image
self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
self.timeText.destroy()
self.highscore.destroy()
# If reset is used before timer has started, AttributeError will occur
try:
self.nameEntry.destroy()
except AttributeError:
pass
# If reset is used before a score is recorded, AttributeError will occur
try:
self.all_scores.forget()
except AttributeError:
pass
# Remake all the widgets)
self.starttime = current_milli_time()
self.pattern = '{:02d}:{:02d}'
self.timeText = Label(root, text='00:00', font=('Evogria', 60), foreground='white', background='black')
self.timeText.pack(side='top', expand=False)
self.highscore = Label(root, textvariable=self.highscore_var, font=('Evogria', 20), foreground='yellow', background='black')
self.highscore.pack(side='top', expand=False)
# Constantly running when self.state is true (timer is running)
def update_timeText(self):
if self.state:
#calculate milliseconds since start
#t = timedelta(milliseconds=current_milli_time()-self.starttime)
t = current_milli_time()-self.starttime
# Grab time
self.timeString = self.pattern.format(t/1000, (t/10)%100)
# Display current time
self.timeText.configure(text=self.timeString)
# Updates every 1 centisecond
root.after(10, self.update_timeText)
# Both starts and stops the timer
def start(self, event):
# New instance, reset variables and widgets
if not self.state:
self.reset(event='null')
# Begin
self.state = True
# End instance, display results
else:
self.state = False
self.enter()
# Save name and score
def enter(self):
try:
self.nameEntry.destroy()
except AttributeError:
pass
self.name = StringVar()
self.name.set('')
self.nameEntry = Entry(root, textvariable=self.name, background='black', foreground='white', font=('Evogria', 10), justify=CENTER)
self.nameEntry.pack(side='top', expand=False, pady=10)
self.nameEntry.focus()
def save(self, event):
try:
self.nameEntry.winfo_exists() # Enter screen is up
except AttributeError: # If name entry does NOT exist, then pressing enter should do nothing
return
# Gets name from previous function
try:
name = self.nameEntry.get()
if len(name) == 0: # If name is empty, let the user try again
self.enter()
return
except:
return
# Store name:score in dict
try:
self.scores[self.timeString].append(name.upper())
# Climber hasn't been entered yet
except KeyError:
try:
self.scores[self.timeString] = [name.upper()]
# Happens if time is empty (possibly only replicable when testing code)
except AttributeError:
pass
# Calculate score by total amount of seconds
temp_score = int(self.timeString[0])*10 + int(self.timeString[1]) + int(self.timeString[3])/10 + int(self.timeString[4])/100
# Lowest int becomes the new high score
if temp_score < self.last_score:
self.last_score = temp_score
# Climber is shown during game in yellow
self.highscore_var.set(name.upper() + '\n' + str(self.timeString))
# Clear widgets for next run
self.nameEntry.destroy()
self.display()
# Table of all scores
def display(self):
# Not using reset() because it remakes the widgets, we want a blank canvas
self.timeText.destroy()
self.highscore.destroy()
self.nameEntry.destroy()
self.background_image = PhotoImage(file='scores.gif') # Background for after the game
self.background_label = Label(root, image=self.background_image)
self.background_label.photo = self.background_image
self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
# Essential barebone widgets
self.all_scores = Label(root, text='Scores\n\n', background='black', foreground='white', font=('Evogria', 24))
# Display all scores
for score in sorted(self.scores.items()): # Sorts the dictionary lowest score to highest score
name = str(score[1])
self.all_scores['text'] += str(name[2:-2]) + ' ' + str(score[0]) + '\n\n'
# Position of the start of scores
self.all_scores.pack(side='top', pady=50, padx=30)
# Cycles through images
def next(self, event):
index = self.image_list.index(self.this_image)
if event.keysym == 'Right':
try:
self.this_image=self.image_list[index+1]
# IndexError when the end of the list is reached, simply reset it to the first index
except IndexError:
self.this_image=self.image_list[0]
if event.keysym == 'Left':
try:
self.this_image=self.image_list[index-1]
except IndexError:
self.this_image=self.image_list[-1]
self.reset(event='null')
# Necessary because of fullscreen
def quit(self, event):
root.destroy()
# Creates random dots
def randomize(self, event):
t = Pen()
t.speed(1) # Below .5 = normal speed - .6-1 is the slowest
win = Screen()
win.bgcolor('black')
win.setup(width=1920, height=1080, startx=0, starty=0) # CANNOT make full screen, need a different module called pygsear
#t.hideturtle() - Makes the cursor invisible (looks better), but will speed up the drawings too much
t.color('white')
for i in range(0, 1000):
t.begin_fill()
radius = random.randint(25, 40)
t.circle(radius)
t.end_fill()
t.up()
t._delay(20)
# Waits 5 seconds on first circle for climber to get to it
if i == 0:
time.sleep(5)
# Waits 1 second to slow the process
else:
time.sleep(1)
t.down() # Remove if you don't want the lines to be traced - it helps the climbers predict where it's going
t.goto(0, 0) # Go back to center to avoid going off screen
distance = random.randint(200, 500)
direction = random.randint(0, 360)
# If turtle is facing left or right, it can go a further distance and still stay on screen
# Left/Up or Left/Down
if 130 < direction < 220:
# Left
if 150 < direction < 210:
distance = random.randint(200, 875)
else:
distance = random.randint(200, 600)
# Right/Up or Right/Down
elif 300 < direction < 360 or 0 < direction < 50:
# Right
if 330 < direction < 360 or 0 < direction < 30:
distance = random.randint(200, 875)
else:
distance = random.randint(200, 600)
t.seth(direction)
t.forward(distance)
t.down()
# Climber stays within box, simple timer, no scores
def box(self, empty):
pygame.init()
# Change to max your display
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
# Full screen
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT], pygame.FULLSCREEN)
# Change to max slower or faster
FPS = 60
# Box image
wall_img = pygame.image.load('wall.png')
wall_list = pygame.sprite.Group()
BLACK = (0, 0, 0)
wall = Squeeze(wall_img)
# Change if you change resolution
wall.rect.x = 600 # Left pixel of image
wall.rect.y = 200 # Top pixel of image
wall_list.add(wall)
move = False
done = False
clock = pygame.time.Clock()
screen.fill(BLACK)
playtime = 0
# Timer font+text
font = pygame.font.SysFont('Evogria', 36)
text = font.render('Time: {0:.2f}'.format(playtime), 1, (250, 250, 250))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
screen.blit(text, textpos)
time = False
# Checks for key presses, updates timer and display
while not done:
milliseconds = clock.tick(FPS)
playtime += milliseconds / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and not move:
move = True
time = True
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and move:
move = False
time = False
playtime = 0
if time:
screen.fill(BLACK)
text = font.render('Time: {0:.2f}'.format(playtime), 1, (250, 250, 250))
screen.blit(text, textpos)
wall_list.draw(screen)
wall_list.update(move)
clock.tick(FPS)
pygame.display.flip()
pygame.quit()
# Main code for the box game
class Squeeze(pygame.sprite.Sprite):
def __init__(self, img):
pygame.sprite.Sprite.__init__(self)
self.img_load(img)
self.counter = 0
self.choice = random.choice(['left', 'right'])
self.choice2 = random.choice(['up', 'down'])
self.too_right = False
self.too_left = False
self.too_high = False
self.too_low = False
# Moves and checks boundaries of the box
def update(self, move):
if move: # Only starts when space is pressed
# Note: the image used will change all values here
# Pixels are based off of the left edge (x) and the top edge (y)
# In the future, there should be ratios implemented to work for all resolutions
# walls.png is currently 734x700 pixels
# scale it down, along with the right and bottom pixel values, to match other resolutions
###### CHECKS AND CORRECTS BOUNDARIES FOR X ######
if self.rect.x >= 1200: # Right side hits right edge
self.too_right = True
elif self.rect.x <= 0: # Left side hits left edge
self.too_left = True
if self.too_right:
self.rect.x += random.randint(-1, -1) # The amount of pixels the box will move per frame
if self.rect.x <= 650: # 650 = x center
self.too_right = False
self.choice = random.choice(['left', 'right'])
elif self.too_left:
self.rect.x += random.randint(1, 1)
if self.rect.x >= 650:
self.too_left = True
self.choice = random.choice(['left', 'right'])
# Move a random direction after returning to center
else:
if self.choice == 'left':
self.rect.x += random.randint(-1, -1)
elif self.choice == 'right':
self.rect.x += random.randint(1, 1)
###### CHECKS AND CORRECTS BOUNDARIES FOR Y ######
if self.rect.y <= 50: # Box stops before text
self.too_high = True
elif self.rect.y >= 385: # Bottom side hits bottom of screen
self.too_low = True
if self.too_high:
self.rect.y += random.randint(1, 1)
if self.rect.y <= 200:
self.too_high = False
self.choice2 = random.choice(['up', 'down'])
elif self.too_low:
self.rect.y += random.randint(-1, -1)
if self.rect.y >= 200:
self.too_low = False
self.choice2 = random.choice(['up', 'down'])
else:
if self.choice2 == 'up':
self.rect.y += random.randint(1, 1)
else:
self.rect.y += random.randint(-1, -1)
#################################################
# Could be put in constructor
def img_load(self, img):
self.image = img
self.rect = self.image.get_rect()
# Run class
root = Tk()
root.wm_title('Hit the Dots!')
app = Timer(master=root)
app.mainloop()