Search code examples
pythonwhile-looppygamenonetype

NoneType is not subscriptible when running a while loop with pygame


I am writing a function to update the position of a particle along a straight line, when I run the function on its own I don't seem to get any errors but when I run the whole script I get

locationx = (location[0]-10)*np.cos(angle)
TypeError: 'NoneType' object is not subscriptable

Here is the simple reproducible code:

import numpy as np 
import pygame 
pygame.init()
location = (100 , 200)
manholes = [(50 , 100) , (60 , 20) , (320 , 200) , (400 , 500), (600 , 78) , (634 , 33) ,(500 , 67)  , (634 , 33) , (700 , 67)]
n = 1
def move(manholes , location,  n ):         
    if event.type == pygame.KEYDOWN: 
        if event.key == pygame.K_LEFT:  
            x = manholes[n][0] - manholes[n-1][0]
            y = manholes[n][1] - manholes[n-1][1] 
            angle = np.arctan(y/x)
            locationx = (location[0]-10)*np.cos(angle)
            locationy = (location[1]-10)*np.sin(angle)   
            location = (locationx , locationy)
            return location    
while True : 
    for event in pygame.event.get() : 
        if event.type == pygame.QUIT :               
            pygame.quit()
            quit()  
    location = move(manholes,location, n)    
    pygame.display.update()  

Solution

  • location becomes None because move returns nothing (None) if there is no K_LEFT-KEYDOWN event. Don't handle the event in the function move, only call move when the event is detected:

    def move(manholes, location, n):         
        x = manholes[n][0] - manholes[n-1][0]
        y = manholes[n][1] - manholes[n-1][1] 
        angle = np.arctan(y/x)
        locationx = (location[0]-10)*np.cos(angle)
        locationy = (location[1]-10)*np.sin(angle)   
        location = (locationx , locationy)
        return location    
    
    run = true
    while run: 
        for event in pygame.event.get() : 
            if event.type == pygame.QUIT :               
                run = False
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_LEFT:  
                    location = move(manholes, location, n)    
        
        pygame.display.update()  
    
    pygame.quit()