Beispiel #1
0
 def __init__(self):
     self.world = World(GLOBAL_X, GLOBAL_Y)
     self.init_population()
     self.start_population = sum(list(self.count_humans().values()))
     self.humans_on_grid_vec = np.vectorize(self._update_humans_on_grid)
     self.update_human_vec = np.vectorize(self._update_human)
     self.day_counter = 0
Beispiel #2
0
def main():

    con, panel, mouse, key = Initializer.init_game()

    newgame = Menu.main_menu(con, key, mouse)

    if not newgame:
        sys.exit(0)

    race, prof = Menu.starting_menu(con, key, mouse)

    world = World(race, prof)

    # world.debug = True

    mapmaker = MapMaker()

    mapmaker.new_dungeon(world)

    world.fov_map = Initializer.init_fov_map(world.tilemap)

    DeathFunctions.world = world

    while not libtcod.console_is_window_closed():

        RenderFunctions.render_all(con, panel, world)
        libtcod.console_flush()

        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        action = Controls.handle_keys(key, world)

        world.update(action)
Beispiel #3
0
 def __init__(self):
     """
     Resets the Game
     """
     # variables
     self.world = World()
     self.n_players = 0
     self.start_troops = 0
     self.players = []
     self.owned_territories = []
Beispiel #4
0
 def generate_items():
     """generate items"""
     Items.list = []
     possible_position = []
     for i in range(Items.count):
         pos_x, pos_y = 0, 0
         for j in World.get_lvl():
             pos_x = 0
             for k in j:
                 if not World.is_solid(k):
                     possible_position.append((pos_x, pos_y))
                 pos_x += 1
             pos_y += 1
     for i in range(Items.count):
         rng = random.randrange(0, len(possible_position))
         Items.list.append(Items(possible_position[rng]))
         possible_position.pop(rng)
Beispiel #5
0
 def update(screen):
     """update"""
     World.update(screen)
     Items.update(screen)
     screen.blit(Game.player.sprite, Game.player.get_position())
     font = pygame.font.SysFont("comicsansms", 12)
     screen.blit(
         font.render(
             "{} Items sur {} .".format(Game.player.inventory, Items.count),
             True, (0, 0, 0)), (200, 1))
     if Items.pick_item_at(Game.player.get_position_case()):
         Game.player.pick_up_item()
     if World.get_sprite_at(Game.player.get_position_case()[0],
                            Game.player.get_position_case()[1]) == "G":
         if Items.count == Game.player.inventory:
             sm.SceneManager.load_scene(2)
             Over.set_text("Vous avez gagnez")
         else:
             sm.SceneManager.load_scene(2)
             Over.set_text("GameOver vous n'avez pas récupéré les Items")
Beispiel #6
0
        def wrapper(app, msg):
            user = msg.from_user
            username = user.first_name
            user_id = user.id
            if user_id not in db:
                db[user_id] = World(username)
            world = db[user_id]

            my_func(app, msg, world)

            db[user_id] = world
            db.sync()
            msg.continue_propagation()
Beispiel #7
0
 def set_position(self, direction):
     """change player position"""
     if direction == "DOWN":
         if not World.is_solid(
                 World.get_sprite_at(self.case_x, self.case_y + 1)):
             self.case_y += 1
             self.pos_y += 20
     elif direction == "UP":
         if not World.is_solid(
                 World.get_sprite_at(self.case_x, self.case_y - 1)):
             self.case_y -= 1
             self.pos_y -= 20
     elif direction == "LEFT":
         if not World.is_solid(
                 World.get_sprite_at(self.case_x - 1, self.case_y)):
             self.case_x -= 1
             self.pos_x -= 20
     elif direction == "RIGHT":
         if not World.is_solid(
                 World.get_sprite_at(self.case_x + 1, self.case_y)):
             self.case_x += 1
             self.pos_x += 20
Beispiel #8
0
def main():
    #world = World("vegetation_map_with_key.png", "elevation_map.png")

    st.title("CivSim")
    st.subheader("Simulation utilizing cellular automata")

    #slider for the number of steps
    st.sidebar.text(
        "In this simulation, the cells on the \nedges of civilizations have a chance to \ncolonize neighbors or go extinct based \nupon the vegatation, elevation, and a \nrandomized percent colonization. "
    )
    teams = st.sidebar.slider("Number of players",
                              min_value=5,
                              max_value=15,
                              step=1,
                              value=10)
    steps = st.sidebar.slider("Number of decade-long time steps",
                              min_value=100,
                              max_value=2200,
                              step=100,
                              value=800)
    image = Image.open("afroeurasia.png")
    st_image = st.image(image, use_column_width=True)
    age_text = st.sidebar.text("Current Time: 20000 BC")
    progress_bar = st.sidebar.progress(0)

    world = World(VEG_IM, ELV_IM, teams)
    ensemble = Ensemble(world, AFROEURASIA)
    age = -20000
    if st.sidebar.button("Run Simulation"):
        running = True
        while running:
            counter = 0
            while counter < steps:
                age = ensemble.run(age, counter, st_image, age_text,
                                   progress_bar, steps)
                counter += 1
            running = False
Beispiel #9
0
from classes.world import World, EnemyTile
from classes.player import Player
from collections import OrderedDict

import os
import pickle
world = World()


class Game:
    def __init__(self):
        self.name = "Player"
        self.game_active = False
        self.player_coordinates = -1, -1

    def New_Game(self):
        """
        Initialize a new game.
        - Chadwick
        """
        self.name = input("What is your characters name: ")
        self.Start_Game("level1")

        # Create a user file with information
        # instantiate inventory class

    def Start_Game(self, map_name):
        """
        Starts a playable game
        - Chadwick
        """
Beispiel #10
0
# this dictionary allows searching for the pertinent image by type
images = {Agent: AGENT, Food: FOOD, Goal: GOAL, Obstacle: OBSTACLE}

# draws a Border of Obstacles around the world to prevent agents from leaving it
# def drawBorder():
#     #top and bottom
#     for x in range(MAP_WIDTH):
#         world.spawn(EntityType.Obstacle, x, 0)
#         world.spawn(EntityType.Obstacle, x, MAP_HEIGHT-1)
#     #left and right
#     for y in range(1, MAP_HEIGHT - 1):
#         world.spawn(EntityType.Obstacle, 0, y)
#         world.spawn(EntityType.Obstacle, MAP_WIDTH - 1, y)

# initialize world
world = World()
world.loadMap('resources/maps/square25.txt')
world.spawn(EntityType.Agent, 17, 9)

# set up display
DISP_SURF = pygame.display.set_mode((world.width * TILESIZE, world.height * TILESIZE), pygame.NOFRAME)

def TimePastSinceStart():
    return (int(pygame.time.get_ticks()/1000))

# draws the entities onto the grid
def render():
    for line in world.entities:
        for entity in line:
            if isinstance(entity, Entity):
                DISP_SURF.blit(pygame.transform.scale(images[type(entity)], (TILESIZE, TILESIZE)), (entity.x * TILESIZE, entity.y * TILESIZE))
Beispiel #11
0
class Simulation:
    def __init__(self):
        self.world = World(GLOBAL_X, GLOBAL_Y)
        self.init_population()
        self.start_population = sum(list(self.count_humans().values()))
        self.humans_on_grid_vec = np.vectorize(self._update_humans_on_grid)
        self.update_human_vec = np.vectorize(self._update_human)
        self.day_counter = 0

    def init_population(self):

        current_grid = self.world.world_grid

        for _ in range(0, HUMANS):
            x = rnd.randint(0, GLOBAL_X - 1)
            y = rnd.randint(0, GLOBAL_Y - 1)
            is_sick = create_chance(0.01)
            if not current_grid[x, y]:
                current_grid[x, y] = Human(x, y, is_sick)

    def _update_human(self, val):
        if val:
            if val.is_sick:
                if val.sick_days >= TIME_UNTIL_CURED:
                    if create_chance(CHANCE_CURE):
                        val.cure()
                val.sick_days += 1
                if val.sick_days >= TIME_UNTIL_DEATH and val.is_sick:
                    if create_chance(CHANCE_DEATH):
                        val.die()

    def update_humans_vec(self):
        return self.update_human_vec(self.world.world_grid)

    def _get_random_humans(self, human_positions: List[List[str]]):
        positions = np.transpose((human_positions).nonzero()).tolist()
        random_humans = [rnd.choice(positions) for p in range(HUMAN_MOVEMENT)]

        return random_humans

    def _update_humans_on_grid(self, val):
        if val:
            if val.is_dead:
                self.world.world_grid[val.pos_x, val.pos_y] = None

    def update_humans_on_grid_vec(self):
        return self.humans_on_grid_vec(self.world.world_grid)

    def update(self):
        for human in self._get_random_humans(self.world.world_grid):
            x, y = human
            m_x = rnd.randint(-1, 1)
            m_y = rnd.randint(-1, 1)
            if self.world.world_grid[x, y]:
                self.world.world_grid[x, y].move(m_x, m_y,
                                                 self.world.world_grid)
        self.update_humans_vec()
        self.update_humans_on_grid_vec()
        self.day_counter += 1

    def count_humans(self, ignore_empty: int = 2):
        unique, counts = np.unique(self.world.translate_world(),
                                   return_counts=True)
        data = dict(zip(unique, counts))
        del data[ignore_empty]
        return data

    def check_all_alive(self):
        if not self.count_humans().get(1):
            print('All people are healthy')
            print(
                f'{(1-(self.count_humans().get(0)/self.start_population))*100} % died'
            )

            return True
        return False

    def check_all_dead(self):
        if not self.count_humans().get(0):
            print('All people are dead')

            return True

        return False
Beispiel #12
0
import numpy as np
import random as rnd
import matplotlib.pyplot as plt
import seaborn as sns
import time
import pandas as pd
from typing import List

from utils.globals import *
from utils.randomizer import create_chance
from classes.human import Human
from classes.world import World


world = World(GLOBAL_X, GLOBAL_Y)
grid = world.world_grid


def _get_random_humans(human_positions: List[List[str]]):
    positions = np.transpose((human_positions).nonzero()).tolist()
    random_humans = [rnd.choice(positions) for p in range(HUMAN_MOVEMENT)]

    return random_humans


def update_human(val, TIME_RANGE: int):
    if val:
        if val.is_sick:
            if val.sick_days >= TIME_UNTIL_CURED:
                if create_chance(CHANCE_CURE):
                    val.cure()
Beispiel #13
0
class Game:
    def __init__(self):
        """
        Resets the Game
        """
        # variables
        self.world = World()
        self.n_players = 0
        self.start_troops = 0
        self.players = []
        self.owned_territories = []

    def start(self):
        """
        Starts the game loop
        """
        self.__init__()
        self.set_n_players()
        self.init_players()
        self.init_territory_selection_phase()
        self.init_troop_deployment_phase()
        # self.game_phase()

    def set_n_players(self):
        """
        Sets the number of players in the Game
        """
        complain = ""
        while True:
            clear_output()
            try:
                self.n_players = int(
                    input(
                        f"{complain}Please insert the number of players (between 2 to 6): \n"
                    ))
                if self.n_players >= 2 and self.n_players < 7:
                    self.start_troops = 120 / self.n_players
                    break
                elif self.n_players < 2:
                    complain = "Not enough players!\n"
                elif self.n_players >= 7:
                    complain = "Too many players!\n"
            except:
                complain = "Not a valid number!\n"
                pass

    def init_players(self):
        """
        initializes players and their attributes
        generates player's turn randomly
        """
        complain = ""
        players_turn = random.sample(range(self.n_players), self.n_players)
        players_created = {}
        picked_colors = []
        for x in range(self.n_players):
            while True:
                clear_output()
                try:
                    color = input(
                        f"{complain}Player {x+1}, please type in one of the following colors: ({', '.join([x.capitalize() for x in self.world.player_colors if x not in picked_colors])}):\n"
                    ).lower()
                    if color in self.world.player_colors and color not in picked_colors:
                        picked_colors.append(color)
                        players_created[players_turn[x]] = Player(
                            color.capitalize(), self.start_troops)
                        break
                    else:
                        complain = "Please enter a valid color\n"
                except:
                    pass

        self.players = [
            players_created[y] for x in range(self.n_players)
            for y in players_created.keys() if int(y) == x
        ]

    def init_territory_selection_phase(self):
        """
        Initializes territory selection phase
        runs until all of the territories in the game world are selected
        """
        phase_name = "Territory Selection Phase!\n\n"
        selected_territories = 0
        while selected_territories < len(self.world.territories):
            for i, player in enumerate(self.players):
                complain = ""
                selected_territory = None
                while True:
                    clear_output()
                    self.world.show_territories()
                    try:
                        selected_territory = ' '.join([
                            x.capitalize() for x in input(
                                f"{phase_name}{complain}{player.color} player's Turn\nType in the name of one of the territories displayed, choose wisely!:\n"
                            ).split()
                        ])
                        # updates territory owner
                        # updates player's owned territories and troops
                        if next(x["Owner"] for x in self.world.territories
                                if x["Name"] == selected_territory) == None:
                            self.world.update_territory_data(
                                selected_territory, player.color)
                            self.players[i].add_territory(selected_territory)
                            self.players[i].remove_troops(1)
                            break
                        else:
                            complain = "Territory has an owner already!\n"
                    except:
                        complain = "Not a valid territory!\n"
                        pass
                selected_territories += 1

    def init_troop_deployment_phase(self):
        phase_name = "Troop Deployment Phase!"
        # while any player has more than 0 troops
        while any(x for x in self.players if x.troops > 0):
            for i, player in enumerate(self.players):
                complain = ""
                troops_to_assign = 3  # shoud be 3
                if player.troops < 3:
                    troops_to_assign = player.troops
                while player.troops > 0:
                    clear_output()
                    self.world.show_territories()
                    try:
                        print(f"{phase_name}\n")
                        print(f"You have {int(player.troops)} Troops left.\n")
                        selected_territory = ' '.join([
                            x.capitalize() for x in input(
                                f"{complain}{player.color} player's Turn\nType in the name of one of your territories:\n"
                            ).split()
                        ])
                        if next(x["Owner"] for x in self.world.territories
                                if x["Name"] ==
                                selected_territory) == player.color:
                            self.world.update_territory_data(
                                selected_territory, player.color,
                                troops_to_assign)
                            self.players[i].remove_troops(troops_to_assign)
                            break
                        else:
                            complain = "This territory does not belong to you!\n"
                    except:
                        complain = "Not a valid territory!\n"
                        pass

    def game_phase(self):
        while any(player for player in self.players
                  if len(player.territories) <= len(self.world.territories)):
            # turn start
            for i, player in enumerate(self.players):
                complain = ""
                # adds the turn troops to the player
                troops = 1 + int(len(player.territories) / 3)
                player.add_troops(troops)
                # deploying phase
                while len(player.territories) > 0:
                    try:
                        clear_output()
                        print(
                            f"{'Troop Deployment Phase! Type in Next to skip.'}\n\n"
                        )
                        print(f"{complain}\n")
                        self.world.show_territories()
                        # ask the player for a territory, or to skip
                        action = ' '.join([
                            x.capitalize() for x in input(
                                f"{player.color} player's Turn\n You have {player.troops} Troops.\nType in the territory you want to assign troops to:\n"
                            ).split()
                        ])
                        # break if next
                        if action == "Next":
                            break
                        # ask for the number of troops to deploy
                        troops_to_assign = int(
                            input(
                                f"{complain}Please insert the number of Troops you want to assign: \n"
                            ))
                        if player.troops < troops_to_assign:
                            complain = "Not enough Troops!\n"
                            break
                        if next(x["Owner"] for x in self.world.territories
                                if x["Name"] == action) == player.color:
                            self.world.update_territory_data(
                                action, player.color, troops_to_assign)
                            self.players[i].remove_troops(troops_to_assign)
                        else:
                            complain = "This territory does not belong to you!\n"
                    except:
                        complain = "Not a valid territory!\n"
                        pass

                complain = ""
                # attacking phase
                while True:
                    clear_output()
                    # set territories to use
                    player_territories = [
                        z for x in player.territories
                        for z in self.world.territories if x in z["Name"]
                    ]
                    enemy_territories = [
                        y for x in player_territories
                        for y in self.world.territories
                        if x["Name"] in y["Borders"]
                        and x["Owner"] not in y["Owner"]
                    ]
                    available_territories = {
                        x["Name"]: x["Troops"]
                        for x in player_territories for y in enemy_territories
                        if x["Name"] in y["Borders"]
                    }
                    # select own territory for attack
                    print(
                        f"{'Attacking Phase'}\n\n{complain}{player.color} player's Turn\nType in the name of the territory you want to use! type in 'end' to end your turn:\n"
                    )
                    selected_territory = ' '.join([
                        x.capitalize() for x in input(
                            f"{available_territories} troops\n").split()
                    ])
                    if selected_territory == "End":
                        break
                    # select enemy territory to attack
                    print(
                        f"{pandas.DataFrame([x for x in enemy_territories if selected_territory in x['Borders']])}"
                    )
                    territory_to_attack = ' '.join([
                        x.capitalize() for x in input(
                            f"Type in a territory to attack:\n").split()
                    ])
                    # calculate the battle
                    ally = next(x["Troops"] for x in self.world.territories
                                if x["Name"] == selected_territory)
                    enemy = next(x["Troops"] for x in self.world.territories
                                 if x["Name"] == territory_to_attack)
                    while True:
                        result = random.choice([0, 1])
                        if result == 0:
                            ally -= 1
                            self.world.update_territory_data(
                                selected_territory, player.color, -1)
                        elif result == 1:
                            enemy -= 1
                        if ally <= 1:
                            self.world.update_territory_data(
                                selected_territory, player.color, -(ally - 1))
                            print("Ally Lost!")
                            break
                        elif enemy < 1:
                            self.world.update_territory_data(
                                territory_to_attack, player.color, ally - 1)
                            print("Ally Won!")
                            break

        return f"{''.join([player.color for player in self.players if len(player.territories) >= len(self.world.territories)])} won!"
Beispiel #14
0
 def init():
     """init"""
     Game.player = Player()
     World.load()
     Items.init()