Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()  

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

location becomes None because move returns nothing (None) if there is no K_LEFTKEYDOWN 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading