Python:未定义函数名

2024-10-02 10:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我在做一个人工智能项目,我试图做一个循环,只要一个坐标是<;=我定义了一个函数,但当我试图调用它时,它有这个错误

Traceback (most recent call last):

File "not important", line 66, in

A()

NameError: name 'A' is not defined

如果我试图重新安排定义,它会遇到一个变量问题,通过将它放在原来的位置来解决

这是我的代码(注意我使用pygame作为实际的接口)

import pygame as pg
import math
import time
import random


#starts pygame/create window
pg.init()
screen = pg.display.set_mode((800,600))
pg.display.set_caption("AI ALG")
clock = pg.time.Clock()

#Presets
KillerX = 50
KillerY = 50
EnemyX = 375
EnemyY = 275
gray = (255,255,255)
font = pg.font.Font(None, 32)
TICKSPASSED = 0
font_color = (100, 200, 150)
killertexture = pg.Surface((25,25))
killertexture.fill((0, 255, 0))
enemytexture = pg.Surface((25,25))
enemytexture.fill((255, 0, 0))
startAI = False





#main loop
runing = True
while runing:



    ticktxt = font.render(str(TICKSPASSED), True, font_color)
    activetxt = font.render(str(startAI), True, font_color)
    COO1 = font.render(str(KillerX), True, font_color)
    clock.tick(60)
    keys = pg.key.get_pressed()
    #events
    if keys[pg.K_SPACE]:
        startAI = True
        TICKSPASSED += 1



    for event in pg.event.get():

        #if event.type == pg.QUIT:
            #runing = False

        if event.type == pg.QUIT:
            runing = False

    #update
    #render
    screen.fill(gray)
    screen.blit(ticktxt, ((8,8), (8,8)))
    screen.blit(activetxt, ((730,8), (792,8)))
    screen.blit(COO1, ((730,8), (792,8)))
    screen.blit(killertexture, (KillerX,KillerY))
    screen.blit(enemytexture, (EnemyX,EnemyY))
    A()
    pg.display.flip()


def A():
    if not KillerX <= EnemyX:
        KillerX =- .5

pg.quit()

任何帮助都会很棒的,谢谢

如果我的代码很乱,也很抱歉:)


Tags: importeventtrueifdisplaynotrenderscreen
2条回答

您正在运行的代码是内联的,而不是在函数中,因此一旦在文件中遇到它,即在看到函数A的定义之前运行。您可以将A的定义移动到引用它之前的某个点,也可以将主代码放在文件末尾调用的函数中。A的定义只需要在您尝试调用它之前查看一下

应该在引用A之前定义它。将A的定义移到while循环之前,在该循环中调用A,错误就会消失

注意,您还应该将KillerXEnemyX声明为函数A中的全局变量,或者将它们设置为A的参数,并使A返回更改的KillerX

相关问题 更多 >

    热门问题