WebSim Python Projects: AI-Driven NPC Behavior

Welcome to our cutting-edge project on AI-Driven NPC (Non-Player Character) Behavior! In this demonstration, we'll explore how to create more realistic and engaging NPCs using advanced AI techniques in Python.

Project Overview

Our AI-Driven NPC system uses a combination of machine learning models, decision trees, and natural language processing to create NPCs that can:

Key Components

1. Personality Generator


import random

class PersonalityGenerator:
    traits = ['friendly', 'hostile', 'mysterious', 'helpful', 'mischievous']
    backgrounds = ['noble', 'peasant', 'merchant', 'warrior', 'mage']
    goals = ['wealth', 'power', 'knowledge', 'revenge', 'peace']

    @staticmethod
    def generate():
        return {
            'trait': random.choice(PersonalityGenerator.traits),
            'background': random.choice(PersonalityGenerator.backgrounds),
            'goal': random.choice(PersonalityGenerator.goals)
        }

2. Dialogue System


import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

nltk.download('punkt')
nltk.download('stopwords')

class DialogueSystem:
    def __init__(self):
        self.stop_words = set(stopwords.words('english'))

    def generate_response(self, npc, player_input):
        tokens = word_tokenize(player_input.lower())
        tokens = [w for w in tokens if w not in self.stop_words]

        if npc['personality']['trait'] == 'friendly':
            if 'hello' in tokens or 'hi' in tokens:
                return f"Greetings, traveler! I'm a {npc['personality']['background']}. How can I assist you today?"
            elif 'quest' in tokens or 'mission' in tokens:
                return f"Ah, a quest! As a {npc['personality']['background']}, I'm always seeking {npc['personality']['goal']}. Perhaps we can help each other?"
        elif npc['personality']['trait'] == 'hostile':
            return f"Watch your step, outsider. A {npc['personality']['background']} like me doesn't take kindly to strangers."

        return "I'm not sure how to respond to that."

3. Behavior Decision Tree


class BehaviorTree:
    def make_decision(self, npc, game_state):
        if game_state['threat_level'] > 7:
            return 'flee'
        elif game_state['player_reputation'] < 3 and npc['personality']['trait'] != 'friendly':
            return 'attack'
        elif game_state['time_of_day'] == 'night' and npc['personality']['background'] == 'merchant':
            return 'close_shop'
        else:
            return 'engage_dialogue'

4. Learning Component


from sklearn.ensemble import RandomForestClassifier

class NPCLearning:
    def __init__(self):
        self.model = RandomForestClassifier()
        self.experiences = []

    def record_experience(self, state, action, reward):
        self.experiences.append((state, action, reward))

    def train(self):
        X = [e[0] for e in self.experiences]
        y = [e[1] for e in self.experiences]
        self.model.fit(X, y)

    def predict_best_action(self, state):
        return self.model.predict([state])[0]

Putting It All Together


class AINPC:
    def __init__(self, name):
        self.name = name
        self.personality = PersonalityGenerator.generate()
        self.dialogue_system = DialogueSystem()
        self.behavior_tree = BehaviorTree()
        self.learning = NPCLearning()

    def interact(self, player_input, game_state):
        action = self.behavior_tree.make_decision(self, game_state)

        if action == 'engage_dialogue':
            return self.dialogue_system.generate_response(self, player_input)
        elif action == 'flee':
            return f"{self.name} tries to flee from the threat!"
        elif action == 'attack':
            return f"{self.name} prepares to attack!"
        elif action == 'close_shop':
            return f"{self.name} is closing their shop for the night."

        # Record this interaction for learning
        self.learning.record_experience(game_state, action, game_state['player_satisfaction'])

    def evolve(self):
        self.learning.train()

Interactive NPC Demo

Experience our AI-driven NPC system in action! Interact with a dynamically generated NPC and see how they respond based on their personality and the game state.

Future Enhancements

We're constantly working to improve our AI-driven NPC system. Some planned enhancements include:

Explore More WebSim Python Projects