01/10/2018, 16:43

Hỏi về code snake trong pygame và giúp sửa code

Em mới tập tành viết game snake bằng pygame, code em viết như sau:

import pygame,sys,random
from pygame.locals import *

winwidth = 500
winheight = 500
FPS = 30
clock = pygame.time.Clock()

pygame.init()
win = pygame.display.set_mode((winwidth,winheight))
pygame.display.set_caption("Snake_Game")

block_size = 25
assert winwidth%block_size == 0 and winheight%block_size == 0,"AttentionError"

Loserfont = pygame.font.SysFont("c",100)
Loserfont = Loserfont.render("You have run out of the edge",1,(192,192,192))
Loserfont_x = winwidth //4
Loserfont_y = winheight//4

food_x = random.randint(1,(winwidth-block_size)//block_size+1)
food_y = random.randint(1,(winheight-block_size)//block_size+1)

def food(food_x,food_y):
       return food_x == random.randint(1,(winwidth-block_size)//block_size+1) and food_y == random.randint(1,(winheight-block_size)//block_size+1)

def Grid():
    for x in range(winwindth):
         for y in range(winheight):
               pygame.draw.rect(win,(255,0,0),(x*block_size,y*block_size,block_size,block_size),2)

class Snake():
    def __init__(self):
        self.width = block_size
        self.height = block_size
        self.body = [[winwidth//2,winheight//2],[winwidth//2+block_size,winheight//2], 
                                                   [winwidth//2+2*block_size,winheight//2]]
        self.new_head = []
         self.tail = []
     def draw(self):
    
            HEAD = 0
            x = 0
            y = 1
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                        pygame.quit()
                if event.type == K_UP and self.direction != "DOWN":
                        self.direction == "UP"
                elif event.type == K_DOWN and self.direction != "UP":
                        self.direction == "DOWN"
                elif event.type == K_RIGHT and self.direction != "LEFT":
                        self.direction == "RIGHT"
               elif event.type == K_LEFT and self.direction != "RIGHT":
                        self.direction == "LEFT"
     
        #If the snake touch the edge
           if self.body[HEAD][x] < 0 or self.body[HEAD][x] > winwidth or self.body[HEAD][y]< 0 or self.body[HEAD][y] > winheight:
                   return

        #If the snake touch his self's body
           for body in self.body[1:]:
                if body[x] == self.body[HEAD][x] and body[y] == self.body[HEAD][y]:
                     return     

        #If the snake eat the food
             if self.body[HEAD][x] == food_x and self.body[HEAD][y] == food_y:
                 food(food_x,food_y)

          pygame.draw.rect(win,(255,0,0),(food_x*block_size,food_y*block_size,block_size,block_size))
        
           self.direction = ""
            if self.direction == "UP":
                    self.new_head = [self.body[HEAD][x],self.body[HEAD][y] - block_size]
            elif self.direction == "DOWN":
                    self.new_head = [self.body[HEAD][x],self.body[HEAD][y] + block_size]
            elif self.direction == "LEFT":
                    self.new_head = [self.body[HEAD][x] - block_size, self.body[HEAD][y]]
            elif self.direction == "RIGHT":
                    self.new_head = [self.body[HEAD][x] + block_size,  self.body[HEAD][y]]

             self.body.insert(0,self.new_head)
             self.body.pop()

              body = 0
             while body<len(self.body):
                 pygame.draw.rect(win,(255,0,0),(self.body[body][x],self.body[body][y],block_size,block_size))
                 pygame.draw.rect(win,(0,0,0),(self.body[body][x]+5,self.body[body][y]+5,block_size,block_size),2)
                 body += 1

              Grid()
              pygame.display.update()
       
        snake = Snake()

 if __name__ == "__main__":
         while True:
              snake.draw()
              grid()

Cũng loay hoai mãi mà chẳng hiểu sao nó cứ hiện ra lỗi như này:
Traceback (most recent call last):
File “C:Program FilesPython37-32Pygame.py”, line 98, in
snake.draw()
File “C:Program FilesPython37-32Pygame.py”, line 87, in draw
pygame.draw.rect(win,(255,0,0),(self.body[body][x],self.body[body][y],block_size,block_size))
IndexError: list index out of range

Ae giải thích giúp em giờ em phải khắc phục lỗi bằng cách nào ạ?

Trương Tấn Phát viết 18:46 ngày 01/10/2018

Vượt quá chỉ số của mảng.
Vd: mảng chỉ có 12 phần tử (0-11) nhưng lại gọi đến phần tử số 13, hoặc 100 thì nó không có.

Lỗi này hay xảy ra khi gọi các phần tử trong mảng bằng biến số tăng dần hoặc giảm dần.

Bài liên quan
0