底部最后一個問題的副本:“我不知道如何解決這個錯誤。一個動作依賴于時間,另一個動作依賴于玩家輸入。有人有想法嗎?python 中是否有處理可變資料的東西一個物件在不同時間從不同地方改變的情況?”
我在 Pygame 中撰寫了自己的俄羅斯方塊。目前我的目標是從這里重建游戲模式“生存”:
在這張圖片中,您可以看到原始游戲。那時,欄位中已經添加了 6 行。每一行都將在欄位底部生成,帶有一個自由隨機點的灰色。每次生成一行時,資訊都會添加到我的“鎖定”字典中( key = (x,y) : value = (153,153,153) )并且一個函式將每個鍵中的 y 值更改為 1 到頂部。同時,如果玩家清除一行(在這張圖片中是從底部開始計數的第 6 行),則有一個函式可以洗掉“鎖定”字典中的此清除行并更改所有大于該行的 y 值由 1 行到底部。
下面是兩個函式:
def clear_rows(grid, locked): # (0,0) is at the top left, x increases right, y increases down
i = len(grid) - 1 # last row
rows_cleared = 0
while i > -1:
row = grid[i]
if BLACK not in row: #which means the row is full and can be cleared
i_new = i rows_cleared
for j in range(len(row)):
del locked[(j, i_new)]
rows_cleared = 1
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x_coord, y_coord = key
if y_coord < i_new:
new_key = (x_coord, y_coord 1)
locked[new_key] = locked.pop(key)
i -= 1
else:
i -= 1
return rows_cleared
和
def survival_add_line(locked):
for key in sorted(list(locked)):
x, y = key
new_key = (x, y - 1)
locked[new_key] = locked.pop(key)
gap = random.randint(0,9)
for i in range(10):
if not i == gap:
locked[(i, 19)] = SURVIVAL_GRAY
這是我的主回圈中的代碼:
if level_time / 1000 >= 1:
survival_add_line(locked)
level_time = 0
if change_piece:
for pos in tetrimino_position:
locked[(pos[0], pos[1])] = current_piece.color
current_piece = next_pieces[0]
next_pieces.pop(0)
next_pieces.append(new_tetromino())
change_piece = False
cleared_lines = clear_rows(grid, locked)
I noticed the bug can only happen at the very bottom of the field. If I understand it right it happens when the player drops a piece in that exact moment when survival_add_line() is already called but before if change_piece. Survival_add_line() shifts every line one to the top, then the clear_row function wants to delete the last row (which is now the second last) and it can't find the key in the last row to delete --> KeyError.
I have no idea how to solve this bug. One action is time dependent and the other one is player input dependent. Someone with an idea? Is there something in python working with mutable data which handles cases where one object gets changed at different times from different places?
uj5u.com熱心網友回復:
不是用 if 呼叫這兩個陳述句,而是一個 if/elif 塊完成作業!(change_piece 現在可以延遲 1 幀,但這對玩家來說并不明顯)
代表提問者發布
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329507.html
標籤:python dictionary pygame mutable
