MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Perché PyGame si blocca se utilizzato in combinazione con PyMongo?

L'eccezione specifica che stai riscontrando sembra essere relativa alla tua connessione mongo. Riesci a connetterti al tuo database in MongDB Compass?

In ogni caso, la tua attuale architettura renderà il tuo ciclo di gioco dipendente dalle scritture del database, il che potrebbe richiedere molto tempo.

Ho creato un esempio che utilizza un thread separato per gestire la connessione MongoDB e comunica con il thread principale utilizzando una coda. Questo esempio include anche il frame rate nella barra del titolo e limita il loop di gioco a sessanta FPS. Se lo aggiungi al tuo script esistente, dovresti vedere la frequenza dei fotogrammi diminuire ogni volta che si verifica un inserimento nel database.

import time
import threading
import queue
import pygame
import pymongo

# Thread for Database storage
class MongoThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.daemon = True

    def run(self):
        t_running = True
        client = pymongo.MongoClient("mongodb+srv://<insert-your-connection-string-here>")
        db = client.test
        c = db.scores
        while t_running:
            if self.queue.empty():
                time.sleep(0.1)
                pass
            else:
                data = self.queue.get()
                if data == "exit":
                    t_running = False
                else:
                    # do something with the queud data
                    c.insert_one(data)
                    print(c.count_documents({}))  # for debugging


WIDTH, HEIGHT = 1000, 400
FPS = 60

# create a queue to send commands from the main thread
q = queue.Queue()
# create and then start the thread
mongo_thread = MongoThread(q) 
mongo_thread.start()

pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
run = True
score = 0
while run:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
            q.put("exit")
        if e.type == pygame.KEYDOWN:
            # c.insert_one({"Score": score})
            q.put({"Score": score})

    score += 1
    win.fill((0, 0, 0))
    pygame.display.update()
    pygame.display.set_caption(f"FPS: {clock.get_fps():.1f}")
    clock.tick(FPS)
pygame.quit()