【发布时间】:2017-11-20 18:19:39
【问题描述】:
我正在尝试为 pvp 战舰游戏编写代码,但我有点卡住了。
我会先给你看代码,然后解释它们是如何工作的。
这是第一个代码。此函数用于在网格上定位每艘船:
def ship_builder(name):
# client ship value = 6, server ship value = 7
v_or_h = randrange(2)
if v_or_h == 0:
vertical = True
else:
vertical = False
if name == 'destroyer':
print('Click a cell to build a destroyer.')
if vertical == True:
print('Vertical')
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = (pos[0] // (cell_side + margin)) + 1
row = (pos[1] // (cell_side + margin)) + 1
grid[row][col] = 7
for i in range(3):
row += 1
grid[row][col] = 7
elif vertical == False:
print('Horizontal')
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = (pos[0] // (cell_side + margin)) + 1
row = (pos[1] // (cell_side + margin)) + 1
grid[row][col] = 7
for i in range(3):
col += 1
grid[row][col] = 7
elif name == 'frigate':
print('Click a cell to build a frigate')
if vertical == True:
print('Vertical')
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = (pos[0] // (cell_side + margin)) + 1
row = (pos[1] // (cell_side + margin)) + 1
grid[row][col] = 7
for i in range(2):
row += 1
grid[row][col] = 7
elif vertical == False:
print('Horizontal')
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = (pos[0] // (cell_side + margin)) + 1
row = (pos[1] // (cell_side + margin)) + 1
grid[row][col] = 7
for i in range(2):
col += 1
grid[row][col] = 7
第二个是上面函数的for循环:
for ship in ['destroyer','frigate']:
ship_builder(ship)
color_change()
#color_change() is a function that colors the responding cells for the ships.
这是他们应该如何工作的。首先,ship_builder 被称为船名(例如,“战舰”)。代码做的第一件事是检查船是垂直放置还是水平放置。根据它的值,用户可以点击一个单元格来确定位置。这是我遇到问题的地方;代码只是跳过该部分并继续进行而不做任何事情。
我的问题是:为什么会跳过鼠标点击部分? pygame.event.get() 不应该让 Python “等待”一个动作吗?
我不确定我是否解释得很详细。如果我需要提供更多信息,请给我留言。我真的需要帮助!
谢谢!
【问题讨论】: