2012-01-15 66 views
0

當我嘗試運行這個簡單的遊戲。它說:我在哪裏添加鍵盤控件到pygame中的精靈?

screen.blit(plumbers,(50 + M ,337 + N)) 
UnboundLocalError: local variable 'M' referenced before assignment 

這是來自婁代碼:

import pygame 
import os, sys 
import itertools 
import pygame 
from pygame.sprite import Sprite 

cloud_background = pygame.image.load('clouds.bmp') 
brick_tile = pygame.image.load('brick_tile.png') 
plumbers = pygame.image.load('Mario_sideways_sprite_2xL.png') 

pink = (255, 64, 64) 
w = 640 
h = 480 
screen = pygame.display.set_mode((w, h)) 
running = 1 

def setup_background(): 
    screen.fill((pink)) 
    screen.blit(cloud_background,(0,0)) 
    brick_width, brick_height = brick_tile.get_width(), brick_tile.get_height() 
    for x,y in itertools.product(range(0,640,brick_width), 
           range(390,480,brick_height)): 
     # print(x,y) 
     screen.blit(brick_tile, (x,y)) 


def show_sprites(): 
    screen.blit(plumbers,(50 + M ,337 + N)) 
    if event.key == pygame.K_UP: 
     M = 1 
     N = 0 

while running: 
    setup_background() 
    show_sprites() 
    move() 
    event = pygame.event.poll() 
    if event.type == pygame.QUIT: sys.exit() 

但是,當我加入上述 「screen.blit」 變量,所以它看起來是這樣的:

def show_sprites(): 
    if event.key == pygame.K_UP: 
     M = 1 
     N = 0 
    screen.blit(plumbers,(50 + M ,337 + N)) 

我得到這個錯誤:

Traceback (most recent call last): 
    File "C:\Users\Enrique\Dropbox\GAMEZ_PYGAME\gamez.py", line 36, in <module> 
    show_sprites() 
    File "C:\Users\Enrique\Dropbox\GAMEZ_PYGAME\gamez.py", line 28, in show_sprites 
    if event.key == pygame.K_UP: 
NameError: global name 'event' is not defined 

我該怎麼做必須添加/更改才能使這些簡單的控件起作用?

回答

1

這意味着你有兩個問題。 Python會看到第一個並停止併發生異常。

在:

def show_sprites(): 
    screen.blit(plumbers,(50 + M ,337 + N)) 
    ....... 

M和N還是不調用時存在。
嘗試例如:

def show_sprites(): 
    print M, N 
    screen.blit(plumbers,(50 + M ,337 + N)) 
    ....... 

def show_sprites(): 
    if event.key == pygame.K_UP: 

既不event已被定義。

你應該檢查一個關於函數參數/參數和局部變量的教程。

你的函數應該是這樣的(例如):

def show_sprites(M, N, event): 

或最有可能的:

def show_sprites(event): 
    if event.key == pygame.K_UP: 
     M = 1 
     N = 0 
    else: 
     M = 0 # ? up to you 
     N = 0 # ? 
    screen.blit(plumbers,(50 + M ,337 + N)) 

有:

while running: 
    setup_background() 
    event = pygame.event.poll() 
    if event.type == pygame.QUIT: sys.exit() 
    show_sprites(event) 
    move() 

最後,該代碼將發送所有類型事件到你的功能,所以你應該過濾它們:

if event.type == pygame.QUIT: 
    sys.exit() 
elif event.type == pygame.KEYDOWN: 
    show_sprites(event) 
    move() 

檢查this例如

+0

我想你的建議,我得到了錯誤:回溯(最近通話最後一個): 文件 「C:\用戶\恩裏克\ Dropbox的\ GAMEZ_PYGAME \ gamez.py」,行41,在 show_sprites(事件) 文件 「C:\用戶\恩裏克\收存箱\ GAMEZ_PYGAME \ gamez.py」,第28行,在show_sprites 如果event.key == pygame.K_UP: AttributeError的: '事件'對象有沒有屬性「鍵」 @joaquin – enrique2334 2012-01-15 17:22:36

+0

這是什麼意思是「事件對象有沒有屬性關鍵@joaquin – enrique2334 2012-01-15 17:29:43

+0

@ enrique2334看版它 – joaquin 2012-01-15 18:45:21