-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
597 lines (462 loc) · 19.6 KB
/
main.py
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from pygame import sprite
from overlapping import Actor
import pygame
from pygame import display
from pygame.draw import rect
# from pygame import examples
# import os
# import sys
# import time
from pygame.locals import *
# from datetime import datetime
import json
from pygame.surface import Surface
from libs.pygamextras import *
from libs.player import Player
# from libs.stores import Stores, StoreBg
from libs.bg_ui_elements import Background, Stats, UserInterface
from libs.menus import Menu
from libs.particles import ParticlesPrinciple
# from libs.dialogues import DialogueBox
import pprint
# from libs.items import Items
# Meter el sistema de botones y menus a una clase por favor :)
def options_menu():
"""Meca Menu inventario
TODO
Crear un rectangulo HW al 75%
Transparentar el rectangulo
Dibujar barra superior con titulo
distinguir con otro color
Dibujar pestanias
Inventario personaje | opciones
"""
global click
click = False
audio_effect('menu')
while True:
screen.fill(('black'))
active_stats()
draw_text('Menu Options', font, (255, 255, 255), screen, 20, 20)
button_1 = pygame.Rect(50, 100, 190, 45)
button_2 = pygame.Rect(50, 150, 190, 45)
button_back = pygame.Rect(50, 200, 190, 45)
if button_1.collidepoint((mx, my)):
if click:
audio_effect('menu')
options_menu()
if button_2.collidepoint((mx, my)):
if click:
audio_effect('menu', False, 0.1)
options_menu()
if button_back.collidepoint((mx, my)):
if click:
main_menu()
# coloreando al pasar
point = pygame.mouse.get_pos()
# print(point)
btn_draw(button_1, point, ('blueviolet'), (255, 100, 100))
btn_draw(button_2, point, (100, 100, 100), (255, 100, 100))
btn_draw(button_back, point, (100, 0, 100), (255, 100, 100))
# all_sprites = pygame.sprite.Group()
# player_one = Player()
# all_sprites.add(player_one)
click = False
for event in pygame.event.get():
if event.type == QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
main_game()
# pygame.quit()
# sys.exit(0)
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
# 3.- Se actualiza la pantalla
pygame.display.update()
# time_show()
pygame.display.set_caption("Local Market » " + str(fps))
# pygame.display.update()
# ############################################################################
# Inicio del juego
# ############################################################################
def main_menu():
main_game()
"""Meca Menu inventario.
TODO.
Crear un rectangulo HW al 75%.
Transparentar el rectangulo.
Dibujar barra superior con titulo.
distinguir con otro color.
Dibujar pestanias.
Inventario personaje | opciones.
"""
global mx, my, tnow, click
click = False
while True:
screen.fill('lightgray')
# Estadisticas de casi todo...
active_stats()
# ####################################################################
# Range colitions
# ####################################################################
# pygame.draw.rect(screen, 'blue', (350, 20, 120, 100), 1)
# pygame.draw.rect(screen, 'green', (400, 60, 120, 100), 4)
# pygame.draw.rect(screen, 'red', (450, 100, 120, 100), 8)
# ####################################################################
draw_text('Menu MK2', font, (255, 255, 255), screen, 20, 20)
button_1 = pygame.Rect(50, 100, 190, 45)
button_2 = pygame.Rect(50, 150, 190, 45)
button_exit = pygame.Rect(50, 200, 190, 45)
for event in pygame.event.get():
if event.type == QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
main_game()
# pygame.quit()
# sys.exit(0)
if event.key == K_r:
tnow = 0
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
if button_1.collidepoint((mx, my)):
if click:
main_game()
if button_2.collidepoint((mx, my)):
if click:
options_menu()
if button_exit.collidepoint((mx, my)):
if click:
exit()
# coloreando al pasar
point = pygame.mouse.get_pos()
btn_draw(button_1, point, ('blueviolet'), (255, 100, 100))
btn_draw(button_2, point, (100, 100, 100), (255, 100, 100))
btn_draw(button_exit, point, (100, 0, 100), (255, 100, 100))
click = False
# 3.- Se actualiza la pantalla
pygame.display.update()
pygame.display.set_caption("Local Market » " + str(tnow[0]))
# pygame.display.update()
clock.tick(fps)
# ############################################################################
# Loop Principal
# ############################################################################
"""Caracteristicas por agregar
CONTINUA CON OTRA COSA CUANDO NO PUEDAS CON ALGO BASTANTE COMPLEJO
USA DE TODO.
NO CAMBIAR LO QUE YA FUNCIONA!
AUN MÍNIMO QUE PAREZCA CADA DETALLE ES MUY IMPORTANTE!
NO TE CASES CON LAS COSAS!
# Ten cuidado de usar la linea 1 incorrectamente, en linux causa conflicto el interprete
✔ Colisiones
Sistema de dialogos GUI ya esta realizada por la mitad
Sistema de logros!!!
✔ Sistema de movimiento 🏃♂️
✔ Sistema de efectos - particulas
Quiza lo tenga cada objeto...
✔ Mostrar menu items jugador
» Menus: Pestanias
Estadisticas del personaje
Caracteristicas fisicas
Salud
Hambre
Resistencias
calor, frio, agua, fuego, electricidad, amor, aburrimiento,
tristeza, veneno, rechazo, friendzone :V, asfixia
Economia (Dinero, propiedades, negocios)
Dinero total
Capacidad de almacenamiento
items
propiedades
Propiedades / Negocios
Establecer Reloj. ✔
✔ time_control()
✔ Mostrar informacion de los tiempos.
Mostrar reloj real. hh:ms:ss, dd/mm/yy
Mostrar hora virtual del juego. hh:mm:ss, 1er dia (1 sem, 1 mes, etc.)
Bucle dia noche en juego.
Establecido 10 mins y reinicia el tiempo.
Crear un sistema de consola de comandos
listar fuentes tipograficas
tamanio de pantalla
colores
dimensiones
tiempos reloj
Fuentes propuestas:
Nokia
Comicoro
pf tempesta seven
retroville
retrogaming
Usare PyGameGUI
minijuegos
alebrije
ladron
politico
luchador
familia
Temporada de carteles y anuncios
"""
def main_game():
"""Función principal del juego"""
# Guardar posicion
global tnow, mx, my, t0, str_time, stats, badge, time_delta
contador = 0
moving = False
running = True # Activador del menu
der = 0 # Restableciendo el movimiento.
player = Player(pygame.image.load(asset('assets/img', 'player-anim.png')), (W//2,H//2))
sprites = YAwareGroup(
player,
Actor(pygame.image.load(asset('assets/img', 'player-anim.png')), (W//2,H//2))
)
# player_collider = pygame.sprite.Group(player.collide_rect)
player_group = pygame.sprite.Group(player)
#Cargando sistema de dialogos?
while running:
screen.fill('black')
# Renderizar el piso
bg.update(screen, (player.bg[0], player.bg[1]))
# Moviendo tiendas Loop Gral
for id2, imp in enumerate(bg.list_imp):
store_pos = (imp[0]+player.bg[0], imp[1]+player.bg[1])
tot_price = []
tot_items = []
for id, store in enumerate(bg.list_store):
if id == id2:
store.movement(store_pos)
#costo total de la tienda
tot_price.append(store.vars['total_store'])
tot_items.append(store.vars['total_items'])
# print(f'Tienda: {id} - {tot_items}')
# print(f'player {tot_price}')
for id3, store_bg in enumerate(bg.list_store_bg):
if id2 == id3:
store_bg.movement(store_pos)
time_delta = clock.tick(60)/1000.0
# dialogue = DialogueBox()
stats['frame_counter'] += 1
# Estadisticas
active_stats()
#posicion global del mouse
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
# Enviando eventos a dialogue
# Creando loop de mapa stores
player.get_event(event)
for store in bg.list_store:
store.get_event(event)
# store2.get_event(event)
if event.type == QUIT:
quit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE and key_press['F4_key'] == True:
# stores_vars = []
# for i in len(store_group.spritedict):
# stores_vars.append(store_group.spritedict[i])
# with open('storevars.json',"w") as f:
# json.dump(stores_vars, f, indent=4, sort_keys=True)
print('Guardando el juego!!! Savegame!!! ;)')
print('####################################\n')
with open('/home/restor/Documents/game-develop/mk2/savegame.json', "w") as f:
game_dump = []
game_dump.append('Player vars')
game_dump.append(player.vars)
game_dump.append('Player items')
game_dump.append(player.items.list)
for store in bg.list_store:
# game_dump.append(player.exis)
game_dump.append(f'Store {(store)} vars')
# game_dump.append(store2.vars)
# game_dump.append('Store 2 vars')
game_dump.append(store.vars)
game_dump.append(store.items.list)
json.dump(game_dump, f, indent=4, sort_keys=True)
if event.key == K_ESCAPE:
key_press["TAB_key"] = False
audio_effect('menu')
quit()
main_menu()
# Movimiento del personaje.
if event.key in (K_UP, K_w):
player.vars['up'] = True
key_press["TAB_key"] = False
if event.key in (K_DOWN, K_s):
player.vars['down'] = True
key_press["TAB_key"] = False
if event.key in (K_LEFT, K_a):
player.vars['left'] = True
key_press["TAB_key"] = False
if event.key in (K_RIGHT, K_d):
player.vars['right'] = True
key_press["TAB_key"] = False
elif event.type == KEYUP:
if event.key in (K_UP, K_w):
player.vars['up'] = False
if event.key in (K_DOWN, K_s):
player.vars['down'] = False
if event.key in (K_LEFT, K_a):
player.vars['left'] = False
if event.key in (K_RIGHT, K_d):
player.vars['right'] = False
# resetear el tiempo
if event.key == K_F5: # Reset Time
key_press["F5_key"] = True
tnow[1] = False
# Abrir el menu transparente, crear un evento de menus....
if event.key == K_TAB and key_press["TAB_key"] == False:
key_press["TAB_key"] = True
elif event.key == K_TAB and key_press["TAB_key"]:
key_press["TAB_key"] = False
# Abctivar-Descartivar estadisticas
if event.key == K_F4 and key_press["F4_key"] == False:
key_press["F4_key"] = True
elif event.key == K_F4 and key_press["F4_key"]:
key_press["F4_key"] = False
# # Moviendo la rueda del raton
# if event.type == MOUSEBUTTONDOWN:
# if event.button == 4:
# contador += 1
# print('adelante'+ str(contador))
# elif event.button == 5:
# contador += 1
# print('atras' + str(contador))
if event.type == MOUSEBUTTONDOWN and key_press["F4_key"]:
if player.rect.collidepoint(event.pos):
print('player')
moving = True
for id, store in enumerate(bg.list_store):
if store.rect.collidepoint(event.pos):
moving = True
print('shop', id)
# if store2.rect.collidepoint(event.pos):
# moving = True
# print('shop2')
if event.type == MOUSEBUTTONUP and key_press["F4_key"]:
moving = False
elif event.type == MOUSEMOTION and moving and key_press["F4_key"]:
#Moviendo direccion del personaje con el mouse
if player.rect.collidepoint(event.pos):
player.control(event.rel[0],event.rel[1])
if event.rel[0] > 0:
player.vars['last_dir'] = 'right'
if event.rel[0] < 0:
player.vars['last_dir'] = 'left'
if event.rel[1] > 0:
player.vars['last_dir'] = 'down'
if event.rel[1] < 0:
player.vars['last_dir'] = 'up'
# interaction(player.rect)
for store in bg.list_store:
if store.rect.collidepoint(event.pos):
store.control(event.rel[0],event.rel[1])
for store_bg in bg.list_store_bg:
if store.rect.collidepoint(event.pos):
store_bg.control(event.rel[0],event.rel[1])
# elif store2.rect.collidepoint(event.pos):
# store2.control(event.rel[0],event.rel[1])
# store_bg2.control(event.rel[0],event.rel[1])
# print(event.rel)
# Iniciando el evento particulas
if event.type == PARTICLE_EVENT:
particle1.add_particles([player.rect.x, player.rect.y])
#Eventos de gui
ui_manager.process_events(event)
if key_press['F4_key']:
for store in bg.list_store:
store.interaction()
for store_bg in bg.list_store_bg:
store_bg.interaction()
player.interaction()
# Desactivar particulas
# particle1.emit()
run_time()
# Checar posision y desplazamiento...
# for x, store in enumerate(bg.list_store):
# for y, imp in enumerate(bg.list_imp):
# store.rect.x = (x*128)+imp[0]
# store.rect.y = (y*128)+imp[1]
# print(imp, store.rect)
# store.update(store.control(player.bg[0], player.bg[1]))
# store2.update(store2.control(player.bg[0], player.bg[1]))
# renderizar las tiendas
bg.store_group.update()
bg.store_group.draw(screen)
# renderizar jugador
player_group.update()
player_group.draw(screen)
# sprites.update()
# sprites.draw(screen)
# def movement():
# movex = store.rect.x + player.bg[0]
# movey = store.rect.y + player.bg[1]
# pos = [movex, movey]
# store.rect.move_ip(movex, movey)
# return pos
# print(player.bg)
for id, store_bg in enumerate(bg.list_store_bg):
colliderect = pygame.Rect.colliderect(player.collide_rect, store_bg.rect)
if colliderect:
for id2, store in enumerate(bg.list_store):
if id == id2:
store.dialogue_box()
# Haz tu magia... ;)
player.dialogue_box()
elif not colliderect:
# Reiniciando el contador aleatorio de badges.
badge = ActionBadges()
# audio_effect('menu', 0.5)
# #crear efecto dia noche...
# daynight = pygame.Surface([W, H], pygame.SRCALPHA, 32)
# daynight.set_colorkey('white')
# daynight = daynight.convert_alpha()
# Abrir menu items
if key_press["TAB_key"]:
menu.show()
# number = 3
# for x in range(number):
# for y in range(number):
# pygame.draw.rect(screen, 'orange', ((x*256),(y*256), 128, 128), 1)
# Renderizando la interfaz de usuario
statistic=Stats()
# Agregando items del jugador a las tiendas
tot_price.append(player.vars['total_store'])
tot_items.append(player.vars['total_items'])
player_tot = player.vars['total_items']
print(f'Player {player_tot}')
ui.gui(sum_totals(tot_price), sum_totals(tot_items))
#Renderizar particulas
time_control()
pygame.display.update()
if __name__ == '__main__':
# ############################################################################
# Loading Starting System...
# ############################################################################
# pygame.mixer.pre_init(44100, 16, 2, 4096) #frequency, size, channels, buffersize
# pygame.init()
# screen = pygame.display.set_mode((W, H), pygame.RESIZABLE)
pygame.display.set_caption("Local Market ")
app_icon = pygame.image.load(asset('assets/img', 'icon-32.png'))
pygame.display.set_icon(app_icon)
fps = 60.0
font = pygame.font.SysFont('comicoro', 12)
count = None # Global
playtime_total = None # Global
#Carga los tile con anterioridad...
bg = Background()
bg.tiles()
menu = Menu()
# Cargando la interfaza de usuario
ui = UserInterface()
# Particulas effects, efectos
particle1 = ParticlesPrinciple()
PARTICLE_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(PARTICLE_EVENT, 25)
audio_effect('start')
main_menu()