簡體   English   中英

更新后立即將對象值重置回 _init_() 值

[英]Object value resetting back to _init_() value immediately after updating

我正在嘗試制作乒乓球多人游戲。 游戲可以運行,但分數更新不會。

我在服務器文件中創建並運行了Ball類,並在那里調用score()函數來更新並傳遞給客戶端。 如果滿足這些條件,它會起作用並增加 1 分,但在下一次迭代中,分數將設置回 0。

Ball類的得分檢查函數( p是一個球員對象):

def score(self, p):
    if self.x <= 10:  
        print('true')
        p.score += 1
    elif self.x >= 890:
        print('true')
        p.score += 1

Player等級:

class Player:
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = (x, y, width, height)
        self.vel = 7
        self.score = 0

調用函數的服務器文件:

while True:
    if current_player > 0:
        clock = pygame.time.Clock()
        clock.tick(60)
        print(players[current_player].score)
        ball.score(players[current_player])
        print(players[current_player].score)
        ball_data = ball.move(players[0], players[1]

ball_data()用於存儲要傳遞給客戶端的Ball對象。 print()調用用於調試目的。

players = [
    Player(10, 300 - PLAYER_HEIGHT/2, PLAYER_WIDTH, PLAYER_HEIGHT, WHITE), 
    Player(880, 300 - PLAYER_HEIGHT/2, PLAYER_WIDTH, PLAYER_HEIGHT, WHITE)
    ]

ball = Ball(WIDTH, HEIGHT, 10, WHITE)

def handle_client(conn, current_player):
    print(f'[NEW CONNECTION] {addr} connected')
    conn.send(pickle.dumps([players[current_player], ball])) # 0 is player and 1 is ball
    reply = ''
    ball_data = ball

    while True:
        if current_player > 0:
            clock = pygame.time.Clock()
            clock.tick(60)
            print(players[current_player].score)
            ball.score(players[current_player])
            print(players[current_player].score)
            ball_data = ball.move(players[0], players[1])

        try:
            data = pickle.loads(conn.recv(2048))
            players[current_player] = data

            if not data:
                print('DISCONNETED')
                break
            else:
                if current_player == 0:
                    reply = [players[1], ball_data]
                else:
                    reply = [players[0], ball_data]

            conn.sendall(pickle.dumps(reply))
        except:
            remove_player()
            player_reset()
            ball_reset()
            break
        
    print('Lost connection')
    conn.close()

輸出:

輸出

問題可能發生在球員名單上。 如果分數重置為 0,則意味着玩家列表可能已被重置(重新初始化)。

data = pickle.loads(conn.recv(2048))
print("tracking:", data)
players[current_player] = data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM