【发布时间】:2020-01-11 05:10:25
【问题描述】:
我想专注于 print_shape() 函数。单元组无法更改,我创建了一个 for 循环来迭代列表“x_placement”中的每个元组,这意味着在范围(1,len(x_placement)+ 1)中。 但是,当我尝试运行该程序时,我收到下面的错误消息,当该功能被激活时显示“列表索引超出范围”。
我尝试使用 range(1, len(x_placement)) 代替(没有 + 1)。它有效,但只是创建了一个没有最后一点的形状(x_placement 列表中的最后一个元组)。 我该如何解决这个问题?
import sys
WIDTH = 300
HEIGHT = 300
turn = 1
DARK_BLUE = (0, 0, 200)
horizontal_top_line = [0, 85, 300, 20]
horizontal_bottom_line = (0, 195, 300, 20)
vertical_left_line = (85, 0, 20, 300)
vertical_right_line = (195, 0, 20, 300)
x_placement = [(20, 30), (30, 20), (45, 40), (60, 20), (70, 30), (50, 45), (70, 60), (60, 70), (45, 50), (30, 70),
(20, 60), (40, 45)]
def draw_board():
pg.draw.rect(screen, DARK_BLUE, horizontal_top_line)
pg.draw.rect(screen, DARK_BLUE, horizontal_bottom_line)
pg.draw.rect(screen, DARK_BLUE, vertical_right_line)
pg.draw.rect(screen, DARK_BLUE, vertical_left_line)
def check_square():
x = 0
y = 0
if mouse[0] <= 90:
x = 1
elif 110 <= mouse[0] <= 190:
x = 2
elif 210 <= mouse[0] <= 290:
x = 3
if mouse[1] <= 90:
y = 1
elif 110 <= mouse[1] <= 190:
y = 2
elif 210 <= mouse[1] <= 290:
y = 3
return x, y
def print_shape(square, turn):
if turn % 2 == 1:
specific_x = []
for n in range(1, len(x_placement) + 1):
specific_x.append((x_placement[n][0] + (square[0] - 1) * 100, x_placement[n][1] + (square[1] - 1) * 100))
pg.draw.polygon(screen, DARK_BLUE, specific_x)
elif turn % 2 == 0:
pass
else:
pass
turn += 1
screen = pg.display.set_mode((WIDTH, HEIGHT))
game_over = False
while not game_over:
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
if event.type == pg.MOUSEBUTTONDOWN:
current_square = check_square()
print_shape(current_square, turn)
mouse = pg.mouse.get_pos()
draw_board()
pg.display.update()```
File "C:/Users/idof/PycharmProjects/TickTacToe/game.py", line 73, in <module>
print_shape(current_square, turn)
File "C:/Users/idof/PycharmProjects/TickTacToe/game.py", line 51, in print_shape
specific_x.append((x_placement[n][0] + (square[0] - 1) * 100, x_placement[n][1] + (square[1] - 1) * 100))
IndexError: list index out of range
【问题讨论】:
-
从 0 开始,而不是 1。
-
索引以
0开头。不应该是for n in range(0, len(x_placement)):吗?您确定它缺少最后一个元素而不是第一个元素吗? -
你可以
for item in x_placement: apecific_x.append(item...,你不需要使用范围。
标签: python list indexing pygame tuples