Advertisement

Battle: AI - Python

Started by October 15, 2008 03:14 PM
2 comments, last by Hollower 16 years, 3 months ago
Hey everyone. You might notice that I'm new, and I hope that this doesn't effect the way I'm treated here. But... I've made several attempts at an artificial intelligence game in the past, using a few different 'easy' languages like QBASIC 1 and others. Python, being considerably more complex, has taken quite a while for me to get the hang of. Well, I've finally worked up the courage to try to build the sucessful Battle: AI game... And I'm already stuck on an error. I'm not sure what I'm doing wrong, but I found out that one of the important variables that needed to be called was returning None. The whole game is a pretty thick syrup, so I'll only post the called functions. Any and all help is welcome. Insults are ok too, if you can show me how to correct myself. Thank you!

#! /usr/bin/env python

####################################################################
#                          Battle: AI                              #
####################################################################

# Remove class G() and all G variables
# Tuesday, October 14 2008
# Reformatted loadFile and got ALL of the opening prompt working
# Wednesday, October 15 2008

from random import randint

def getInt(prompt='Integer: ',complaint='Integers only, stupid.'):
    "Requests an integer from the user"
    try:
        num=int(raw_input(prompt))
    except:
        print complaint
        num=getInt(prompt,complaint)
    return num

def loadFile(prompt,complaint="File does not exist, stupid."):
    "returns lines of a file as a list"
    location=raw_input(prompt).strip()
    try:
        fil=open(location,'r')
        text=fil.readlines()
        fil.close()
        out=text
        for f in range(len(text)):
            thisLine=text[f]
            out[f]=thisLine.strip()
        return out
    except IOError:
        print 'Error loading file', location
    return -1

def checkRel(botNum,relx=0,rely=0):
    "Bot scan at position relative to it's self"
    x=bots[botNum]['x']+relx
    y=bots[botNum]['y']+rely
    if arena[x][y]=='#':return 1#       Wall
    if arena[x][y]=='*':return 2#       Mine
    if arena[x][y]=='$':return 3#       Powerup
    if arena[x][y]=='%':return 4#       Health
    for f in range(len(bots)):#         Enemy{
        if bots[f]['x']==x:
            if bots[f]['y']==y:
                return 5#               }
    return 0

def move(botNum,nsew):
    "Move bot relative nsew"
    if nsew=='n':
        posScan=checkRel(botNum,0,-1)
    elif nsew=='s':
        posScan=checkRel(botNum,0,1)
    elif nsew=='e':
        posScan=checkRel(botNum,1,0)
    elif nsew=='w':
        posScan=checkRel(botNum,-1,0)
    else:
        print 'Error: nsew not provided within move(), stupid! botNum:', botNum
    if posScan<>1 and posScan<>5:
        if nsew=='n':
            boty=bots[botNum]['y']-1
            botx=bots[botNum]['x']
        if nsew=='s':
            boty=bots[botNum]['y']+1
            botx=bots[botNum]['x']
        if nsew=='e':
            botx=bots[botNum]['x']+1
            boty=bots[botNum]['y']
        if nsew=='w':
            botx=bots[botNum]['x']-1
            boty=bots[botNum]['y']
    else:
        if posScan==1:
            botl=bots[botNum]['life']-wallDmg
        if posScan==5:
            botl=bots[botNum]['life']-crashDmg
    posScan=checkRel(botNum)
    if posScan==2:
        botl=bots[botNum]['life']-mineDmg
    if posScan==3:
        botp=bots[botNum]['power']+powerUp#           # the mine isn't currently being deleted from the arena
    if posScan==4:#                                   # program that in the main loop, later
        botl=bots[botNum]['life']+healthKit
    return {'x':botx,
            'y':boty,
            'life':botl,
            'power':botp,
            'face':bots[botNum['face']],
            'script':bots[botNum['script']],
            'index':bots[botNum['index']]}

def turn(botNum,lr):
    "turn bot left or right"
    if lr=='l':
        if bots[botNum]['face']>1:
            botf=bots[botNum]['face']-1
        else:
            botf=4
    if lr=='r':
        if bots[botNum]['face']<4:
            botf=bots[botNum]['face']+1
        else:
            botf=1
    return {'x':bots[botNum['x']],
            'y':bots[botNum['y']],
            'life':bots[botNum['life']],
            'power':bots[botNum['power']],
            'face':botf,
            'script':bots[botNum['script']],
            'index':bots[botNum['index']]}

def botStep(botNum):
    "Cycle through a line of script"
    command=bots[botNum]['script'][bots[botNum]['index']]
    if command=='n' or command=='s' or command=='e' or command=='w':bot=move(botNum,command)
    if command=='l' or command=='r':bot=turn(botNum,command)
    pass #                                  <<<<<< -- <<<<<< -- <<<<<< -- <-- add more command checking
    print bot
    bot['index']=bot['index']+1
    return bot

######################### Opening Prompt ########################
print '        BattleAI: Making programming slightly less painful!'
print
if getInt('Would you like to do a \'quick run\'? (yes = 1) ')==1:
    bots=[{'face':randint(1,4),                         # __________Pre made game________
           'x':4,
           'y':5,
           'script':['n','n','n','e','e','e'],
           'life':10,
           'power':10,
           'index':0}]
    arena=['#######',
           '#     #',
           '#     #',
           '#     #',
           '####  #',
           '   #0 #',
           '   ####']
    startingHealth=10
    startingPower=10
    wallDmg=1
    crashDmg=3
    healthKit=7
    mineDmg=5
    powerUp=7
else:
    print
    config=loadFile('Configuration file: ')#             # __________Configuration_________
    print config # ******************************* DEBUG OUTPUT
    try:
        startingHealth=int(config[0])# Setting config vars
        print 'startingHealth =',startingHealth
        startingPower=int(config[1])
        print 'startingPower =',startingPower
        wallDmg=int(config[2])
        print 'wallDmg =',wallDmg
        crashDmg=int(config[3])
        print 'crashDmg =',crashDmg
        healthKit=int(config[4])
        print 'healthKit =',healthKit
        mineDmg=int(config[5])
        print 'mineDmg =',mineDmg
        powerUp=int(config[6])
        print 'powerUp =',powerUp
    except:
        print 'Error in configuration file, stupid.'
        print '    startingHealth'
        print '    startingPower'
        print '    wallDmg'
        print '    crashDmg'
        print '    healthKit'
        print '    mineDmg'
        print '    powerUp'
        print
        print 'Make sure that all lines are integer values... stupid.'
        raw_input()
        from sys import exit
        exit()
    numBots=getInt('Number of bots in this game: ')#       # __________Getting bots_________
    bots=[]
    for f in range(numBots):
        bots.append({'script':loadFile('Bot script: '),
                       'power':startingPower,
                       'health':startingHealth,
                       'index':0})
    arena=loadFile('Arena: ')#                             # __________Getting arena _______
    for f in range(len(arena)):#                           # get bot start locations
        for g in range(len(arena[f])):
            a=arena[f][g]
            try:
                a=int(a)
                aim=randint(1,4)
                print 'bot',a,'is at',f,g,'facing',aim
                bots[a]['x']=f
                bots[a]['y']=g
                bots[a]['face']=aim
            except:
                pass


[Edited by - Ansgar on October 20, 2008 11:59:31 AM]
for? while/when? case/switch? GOTO is so much cooler.
Quote:
Original post by Ansgar
Sorry about the ugly format. I'll fix this ASAP.

We're still waiting. Hint - use the source tags to format it. Without the formatting it's pretty much impossible to debug a Python program since the behaviour depends on the whitespace.

Quote:
And I'm already stuck on an error. I'm not sure what I'm doing wrong, but I found out that one of the important variables that needed to be called was returning None. The whole game is a pretty thick syrup, so I'll only post the called functions.

More detail is needed, because:
- variables don't return values such as None, functions do;
- which variable and/or function were you referring to?
- and what did you expect to see rather than None?
Advertisement
Ok. I've got the format fixed, but I've gotta run right now: The magical world of college requires mucho cappuchino.
for? while/when? case/switch? GOTO is so much cooler.

I have no hope of finding your bug without more specific information as Kylotan said. But I will say one thing contributing to you code being "thick syrup", as you put it, is the way you are using nested dictionaries to represent your objects. You are essentially reinventing classes, without the convenient syntax.

This topic is closed to new replies.

Advertisement