从列表中获取int(pygame)

2024-03-29 08:08:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python做一个类似蛇的游戏。 我现在的问题是,我不能在for循环中使用“coinlist”中定义的值。这是执行时收到的错误:TypeError:'int'对象不可下标。谢谢你的帮助。你知道吗

import pygame
import random

pygame.init()

rot = (255,0,0)
grün = (0,255,0)
blau = (0,0,255)
gelb = (255,255,0)
schwarz = (0,0,0)
weiß = (255,255,255)

uhr = pygame.time.Clock()

display = pygame.display.set_mode((800, 600))
pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake')
display.fill(weiß)


def arialmsg(msg, color, x, y, s):
  header = pygame.font.SysFont("Arial", s)
  text = header.render(msg, True, color)
  display.blit(text, [x, y])

def mainloop():
    gameExit = False
    start = False
    movex = 400
    movey = 300
    changex = 0
    changey = -2
    rx = random.randrange(10, 790)
    ry = random.randrange(10, 590)
    snakelist = []
    snakelenght = 20

    #coinlist defined here:
    coinlist = []

    while start == False:
        display.fill(schwarz)
        arialmsg('Snake', grün, 350, 200, 25)

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    start = True

        pygame.display.flip()

    #gameloop:

    while gameExit == False:

      for event in pygame.event.get():
          if event.type == pygame.QUIT:
              pygame.quit()
          elif event.type == pygame.KEYDOWN:
              if event.key == pygame.K_DOWN:
                  changey = 2
                  changex = 0
              elif event.key == pygame.K_UP:
                  changey = -2
                  changex = 0
              elif event.key == pygame.K_RIGHT:
                  changex = 2
                  changey = 0
              elif event.key == pygame.K_LEFT:
                  changex = -2
                  changey = 0

      movex += changex
      movey += changey
      snakehead = []
      snakehead.append(movex)
      snakehead.append(movey)
      snakelist.append(snakehead)

      display.fill(schwarz)

      if len(coinlist) < 1:
          rx = random.randrange(10, 790)
          ry = random.randrange(10, 590)
          coinlist.append(rx)
          coinlist.append(ry)

      for XY in snakelist:
        pygame.draw.circle(display, grün, (XY[0], XY[1]), 10, 10)



for-loop for the coinlist:

      for coin in coinlist:
        pygame.draw.rect(display, grün, (coin[0], coin[1], 10, 10))

      pygame.display.flip()

      if snakelenght < len(snakelist):
          del snakelist[:1]

      if movex >= rx - 19 and movex <= rx + 19 and movey >= ry - 19 and movey <= ry + 19:
          del coinlist[:1]
          snakelenght += 10

      uhr.tick(15)
mainloop()

pygame.quit()
quit()

Tags: keyeventforifdisplayrandomrxpygame
1条回答
网友
1楼 · 发布于 2024-03-29 08:08:38

您将int附加到coinlist(rx和ry是从10到790/590的随机int),稍后您将尝试访问coinlist中的元素,就像它们是数组一样。你知道吗

考虑做一些类似替换的事情

coinlist.append(rx)
coinlist.append(ry)

coinlist.append([rx,ry])

相关问题 更多 >