GeorgeDavidKing
GeorgeDavidKing

Reputation: 149

'pygame' is not defined

I've already installed the pygame(1.9.1 v). Here is my code:

# 1 - Import library
import pygame
from pygame.locals import *
import math
import random

# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]

# 3 - Load images
player = pygame.image.load("resources/images/messi.jpg")
podo = pygame.image.load("resources/images/podo3.png")
podo1 = pygame.image.load("resources/images/podo1.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    for x in range(width/podo.get_width()+1):
        for y in range(height/podo.get_height()+1):
            screen.blit(podo,(x*0,y*0))
    screen.blit(podo1,(0,345))   
    screen.blit(player, playerpos)
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit()
            exit(0)
        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                keys[0]=True
            elif event.key==K_a:
                keys[1]=True
            elif event.key==K_s:
                keys[2]=True
            elif event.key==K_d:
                keys[3]=True
        if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                keys[0]=False
            elif event.key==pygame.K_a:
                keys[1]=False
            elif event.key==pygame.K_s:
                keys[2]=False
            elif event.key==pygame.K_d:
                keys[3]=False
    # 9 - Move player
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    if keys[1]:
        playerpos[0]-=5
    elif keys[3]:
        playerpos[0]+=5

However it keeps showming me the message:

Traceback (most recent call last):
  File "C:\Users\George\Desktop\game.py", line 2, in <module>
    import pygame
  File "C:\Users\George\Desktop\pygame.py", line 6, in <module>
    pygame.init()
NameError: name 'pygame' is not defined

I removed the library and installed it again but it didn't change anything. What should I do?

Upvotes: 1

Views: 14230

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

You have a file named pygame.py in your Desktop folder and it is masking the pygame library:

  import pygame
File "C:\Users\George\Desktop\pygame.py", line 6, in <module>

Note that the line import pygame imported the file C:\Users\George\Desktop\pygame.py.

Rename that file to something else or remove it altogether.

Upvotes: 7

Related Questions