Exemple #1
0
        selection = 0

        print "\nHow much of the grid would you like to be filled with holes?\n\na) 1/8 of the grid\n\nb) 1/16 of the grid"
        while (selection < 'a' or selection > 'f'):
            selection = raw_input("\nYour Choice(lowercase only): ")

        if (selection == 'a'):
            holeRatio = 8
        elif (selection == 'b'):
            holeRatio = 16

        selection = 0

        while True:

            AIworld = world(size, holeRatio)

            agentLocation = AIworld.world.index(AGENT)

            status = 0

            #list of the threat level of each square on the grid
            threatList = []
            smellList = []
            breezeList = []
            holeList = []

            #Make list of visited or not visited squares, to
            #determine where in the indicators list can be looked at
            safeList = []
            agentVisited = []
Exemple #2
0
def main():
	pygame.init()
	clock = pygame.time.Clock()
	running = True
	
	root = Tkinter.Tk()
	TILE_WIDTH = 64
	TILE_HEIGHT = 64
	
	SCREEN_WIDTH, SCREEN_HEIGHT = (root.winfo_screenwidth(), root.winfo_screenheight())

	screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.FULLSCREEN)
	pygame.display.set_caption("S for Sabotage")
	#commandHandler = CommandHandler(fatguy)

	world_map = TileMapParser().parse_decode("fase3.tmx")
	world_map.load(ImageLoaderPygame())

	ww = world_map.pixel_width;
	wh = world_map.pixel_height;

	w0 = world(ww, wh, SCREEN_WIDTH, SCREEN_HEIGHT, TILE_WIDTH, TILE_HEIGHT)
	
	ground_objects = get_walk_objects(world_map)
	nonwalk_objects = get_nonwalk_objects(world_map)
	walk_enemy = get_walk_enemy(world_map, 0)
	
	pliers = get_activate_objects(world_map, 'pliers')
	c4 = get_activate_objects(world_map, 'c4')
	
	activate_list = []
	activate_list.append(pliers)
	activate_list.append(c4)
	
	enemies = []
	
	player_x, player_y = get_player(world_map, "player")
	player_x = (player_x / TILE_WIDTH) * TILE_WIDTH;
	player_y = (player_y / TILE_HEIGHT) * TILE_HEIGHT;
	
	enemy_x, enemy_y = get_player(world_map, "enemies")
	enemy_x = (enemy_x / TILE_WIDTH) * TILE_WIDTH;
	enemy_y = (enemy_y / TILE_HEIGHT) * TILE_HEIGHT;
	
	print 'ENEMY: ' + str(enemy_x) + ' ' + str(enemy_y)
	
	
	print 'PLAYER: ' + str(player_x) + ' ' + str(player_y)
	img_s = pygame.image.load(os.path.join('', 'art', 's.png'))
	img_enemy = pygame.image.load(os.path.join('', 'art', 'police.png'))
	
	
	h0 = hud(['pliers', 'c4'])
	
	s = Character(w0, "s", img_s, player_x, player_y, nonwalk_objects, activate_list, h0)
	
	enemy = Enemy(w0, 'enemy', img_enemy, enemy_x, enemy_y, walk_enemy, 0)
	
	npx = player_x + TILE_WIDTH
	npy = player_y + TILE_HEIGHT
	camera_x = npx - SCREEN_WIDTH / 2
	if camera_x < 0:
		camera_x = 0
	elif (camera_x + SCREEN_WIDTH) > ww:
		camera_x -= (camera_x + SCREEN_WIDTH) - ww

	camera_y = npy - SCREEN_HEIGHT / 2
	if camera_y < 0:
		camera_y = 0
	elif (camera_y + SCREEN_HEIGHT) > wh:
		camera_y -= (camera_y + SCREEN_HEIGHT) - wh

	print str(camera_x) + ' ' + str(camera_y)

	
	c0 = camera(camera_x, camera_y, w0, s)


	inputHandler = input_handler(w0, c0, s)

	print str(ww) + ' ' + str(wh)

	#key_timeout = -1

	#create sprites groups for collision detection
	#playerGroup = pygame.sprite.RenderUpdates()
	#playerGroup.add(fatguy)

	#objectGroup = pygame.sprite.Group()
	#enemyGroup = pygame.sprite.Group()
	#sceneGroup = pygame.sprite.Group()

	#pygame.key.set_repeat(REPEAT_DELAY, REPEAT_DELAY)
	
	world_surface = world_map.get_surface()
	while running:
		clock.tick(60)
		
		screen.blit(world_surface.subsurface(pygame.Rect(c0.x, c0.y, SCREEN_WIDTH, SCREEN_HEIGHT)), (0, 0))
		
		screen.blit(s.image, s.draw_pos(c0.x, c0.y))
		
		screen.blit(enemy.image, enemy.draw_pos(c0.x, c0.y))
		if enemy.sees(s.get_pos(), 30, 120, 240):
			print 'TE VEJO!'
		print (s.get_pos())
		#pygame.draw.line(screen, (225,0,0), s.draw_pos(c0.x, c0.y), enemy.draw_pos(c0.x, c0.y), 10)
		
		enemy.draw_sees(screen, c0.x, c0.y, 15, 128,256)
		
		h0.paint(w0, c0)
		#fatguy.update(pygame.time.get_ticks(), SCREEN_WIDTH, SCREEN_HEIGHT, cam_speed)
		
		#obj, col_type = fatguy.collides_with_objects(ground_objects)
		#if  col_type == 1:
		#	fatguy.put_on_ground_running(obj[1])
		#elif col_type ==  2:
		#	running = False
		
		#obj, col_type = fatguy.collides_with_objects(killer_objects)
		#if  col_type != -1:
		#	running = False

		running = inputHandler.handle()

#		pygame.display.update()
		pygame.display.flip()
Exemple #3
0
from world import *
import hexcontrol
from hexagon import *
import myalgorithms
import cProfile

##import matplotlib.pyplot as plt
##from matplotlib.path import Path
##import matplotlib.patches as patches

from pylab import *

import path_calculator

# initialize world
my_world = world()
print('Type of world is ', my_world.type_world)

#test_hex = hexagon(0,0,1,90,my_world)
#print ('test_hex is ',test_hex)
#print ('location is ',test_hex.location.x1, test_hex.location.x2)
#print ('outside diameter is ',test_hex.outside_diameter)
#print ('the vertices of test_hex are located at ')
#for i in test_hex.vertices(): print ('        x=',i.x1,' y=',i.x2)

#p0 = location(0,0)
#print ('x=',p0.x1,'y=',p0.x2,'is_interior to test_hex is',test_hex.is_interior(p0))
#p0 = location(-5,0)
#print ('x=',p0.x1,'y=',p0.x2,'is_interior to test_hex is',test_hex.is_interior(p0))
#p0 = location(5,0)
#print ('x=',p0.x1,'y=',p0.x2,'is_interior to test_hex is',test_hex.is_interior(p0))
Exemple #4
0
class simulation:

	simworld = world(1)
	creatures = []
	maxfood = 0 


	def __init__(self,simworld,creature):
		self.simworld = simworld
		self.creature = creature


	def newrandomworld(numderps,mapsize,startsize):
		# (self,foodlevel,xco,yco,newspeed,species_id,childSize,healthySize,worldsize)
		creatures = []

		for i in range (numderps):
			x = random.randint(0,mapsize-1);
			y = random.randint(0,mapsize-1);
			creatures.append(herbivore(10,x,y,1,0,10,20,mapsize))
		simworld = randomworld(mapsize)
		simworld.addamountfood(int(startsize/100),startsize)
		a = simulation(simworld,creatures)
		a.maxfood = startsize
		return a

	def printsim (self):
		length = len(self.creature)
		cfood = 0 
		printer =  [[ "" for i in range(self.simworld.getSize())] for j in range(self.simworld.getSize())] 
		for i in range(length):
			printer[int(self.creature[i].y_co)][int(self.creature[i].x_co)] = "deer"
			self.creature[i].printcre()
			cfood = cfood + self.creature[i].food

		for i in range(self.simworld.getSize()):
			for j in range(self.simworld.getSize()):
				if(printer[i][j]!="deer"):
					printer[i][j] = self.simworld.getfood(i,j)

		for i in range(self.simworld.getSize()):
			for j in range(self.simworld.getSize()):
				
				sys.stdout.write(('%5s ' % (str(printer[i][j])) ))
			sys.stdout.write('\n')

		print ("the world contains "+str(self.simworld.totalfood)+"food")
		print ("the cretures have  "+str(cfood)+"food")
		sys.stdout.flush()

	def creaturefood(self):
		cfood = 0
		for i in range(len(self.creature)):
			cfood = cfood + self.creature[i].food
		return cfood
								
	def stepsim(self):
		leng = len(self.creature)
		newfood = int(0)
		births = int(0)
		deaths = int(0)
		deathlist = []
		deathlist.append(int(-1))
		babylist = []
		for i in range(leng):
			# i.printcre()
			newfood = newfood + self.creature[i].nextmove();

			foodtoadd = self.simworld.removefood(int(self.creature[i].x_co),int(self.creature[i].y_co))
			# print(foodtoadd)
			# newfood = newfood + foodtoadd
			self.creature[i].food = self.creature[i].food + foodtoadd
			currentfood = self.creature[i].getFood()
			# print(currentfood)
			if(currentfood <= 0):
				# print ("a critter is dead !!"+str(len(self.creature)))
				deaths = deaths + 1
				deathlist.append(i)
				# print ("!!"+str(len(self.creature)))
			elif(currentfood > (self.creature[i].healthySize+self.creature[i].childSize)):
				births = births+1
				# print("was of size "+str(self.creature[i].food ))
				babylist.append(herbivore(self.creature[i].childSize,self.creature[i].x_co,self.creature[i].y_co,self.creature[i].speed,self.creature[i].species_id,self.creature[i].childSize,self.creature[i].healthySize,self.creature[i].worldsize))
				self.creature[i].food = self.creature[i].food - self.creature[i].childSize
				# print("now of size "+str(self.creature[i].food ))
		# print ("adding food in the amount of "+str(newfood))
		
		# print (str(self.maxfood) +"     "+str(self.creaturefood())+"     "+str(self.simworld.totalfood))
		if(self.maxfood>=newfood+self.creaturefood()+self.simworld.totalfood):
			# print ("feed the derps"+str(newfood))
			self.simworld.addfood(int(newfood))
		elif (self.maxfood > self.creaturefood()+self.simworld.totalfood):
			# print ("feed the derps"+str(self.maxfood-self.creaturefood()-self.simworld.totalfood))
			self.simworld.addfood(int(self.maxfood-self.creaturefood()-self.simworld.totalfood))
		#TODO Hiss de shush
		# print(str(len(deathlist)))
		if(deaths>0):
			for i in reversed(deathlist):
				if(i>=0):
					del self.creature[i]
		for i in babylist:
			self.creature.append(i)

		return (str(len(self.creature))+","+str(births)+","+str(deaths))
    larg = os.path.splitext(a)
    if (larg[1] == ".jpg"): argoutput = a
    if (larg[1] == ".ini"): argconfig = a
    if (larg[1] == ".json"): argscene = a
    if (larg[1] == ".py"): argprog = a

YA.showArgInfo(argconfig, argscene, argoutput)
if (argscene == ""): YA.showHelp(argprog)

YA.loadconfig(argconfig)
if (argoutput != ""): YA.OUTPUT = argoutput

YA.printRenderInfo()
YA.clear_directory()
image = YA.getImagePixels()
world = world(argscene)
world.print_scene_info()

loop_time = time.time()
for f in range(YA.FRAMES):
    world.update_world(f)
    for y in range(YA.HEIGHT):
        for x in range(YA.WIDTH):
            c = color((0, 0, 0))
            for s in range(YA.SAMPLING):
                if (YA.SAMPLING == 1):
                    xr = 0.0
                    yr = 0.0
                else:
                    xr = random()
                    yr = random()
# This file calls the relevant classes and makes a simulation
#

from world import *
from robot import *

# here are some walls
w1 = wall((10,10),(490,10))
w2 = wall((490,10),(490,450))
w3 = yellowWall((490,450),(450,490))
w4 = wall((450,490),(10,490))
w5 = wall((10,490),(10,10))

# here is a ball
b = ball((100,100), "red")

# here is a robot
r = robot((250,200))

# simulate a world with them in it
w = world((500,500),[w1,w2,w3,w4,w5],[b],r)
win = Window("Team 666 MASLab Simulation")

# start the display, start the world running, and run the display
w.initializeDisplay(win)
w.run()
w.win.mainloop()
    def __init__(self, root):
        '''
        Begins the simulation and shows the UI to the user.

        Args:
            root (widget): The widget in which to generate the view and UI.
        '''
        sys = system(root, 0.1)
        self.sys = sys
        #sys.worlds = [world(sys, 333000, 0, 0, 0, 0.262, 0.5),
        #              world(sys, 318, 1.3, 0, 0, 5.5, 0.075),
        #              world(sys, 31800, 5.2, 0, 0, -2.75, 0.15),
        #              world(sys, 0.025, 5.2+0.7155, 0, 0, -2.75+2.294, 0.05)]
        sys.worlds = [world(sys, 333000, 0, 0, 0, 0, 0.2)]
        for i in range(600):
            rand = random.uniform(0, 2 * math.pi)
            rand2 = random.uniform(-0.01, 0.01)
            rand3 = random.uniform(-0.01, 0.01)
            rand4 = random.uniform(-2, 2)
            rand5 = random.uniform(-2, 2)
            sys.worlds += [
                world(sys, 1, 8 * math.sin(rand) + rand4,
                      8 * math.cos(rand) + rand5,
                      0.5 * math.pi * math.cos(rand) + rand2,
                      -0.5 * math.pi * math.sin(rand) + rand3, 0.03)
            ]
        sys.cameraPos = (-0.0, -0.0)
        sys.scale = 25.0
        sys.initialize()

        frame = Frame(root)
        frame.pack()

        moveFrame = Frame(frame)
        moveFrame.grid(row=0, column=0)

        bufferFrame = Frame(frame, width=initWidth - buttonSize * 5)
        bufferFrame.grid(row=0, column=1)

        zoomFrame = Frame(frame)
        zoomFrame.grid(row=0, column=2)

        leftButton = Button(moveFrame,
                            height=buttonSize,
                            width=2 * buttonSize,
                            text="<",
                            command=lambda: sys.moveLeft(moveAmount))
        leftButton.grid(row=1, column=0)

        rightButton = Button(moveFrame,
                             height=buttonSize,
                             width=2 * buttonSize,
                             text=">",
                             command=lambda: sys.moveRight(moveAmount))
        rightButton.grid(row=1, column=2)

        upButton = Button(moveFrame,
                          height=buttonSize,
                          width=2 * buttonSize,
                          text="^",
                          command=lambda: sys.moveUp(moveAmount))
        upButton.grid(row=0, column=1)

        downButton = Button(moveFrame,
                            height=buttonSize,
                            width=2 * buttonSize,
                            text="v",
                            command=lambda: sys.moveDown(moveAmount))
        downButton.grid(row=2, column=1)

        inButton = Button(zoomFrame,
                          height=buttonSize,
                          width=2 * buttonSize,
                          text="+",
                          command=lambda: sys.zoomIn())
        inButton.grid(row=0, column=4)

        outButton = Button(zoomFrame,
                           height=buttonSize,
                           width=2 * buttonSize,
                           text="-",
                           command=lambda: sys.zoomOut())
        outButton.grid(row=2, column=4)

        fasterButton = Button(zoomFrame,
                              height=buttonSize,
                              width=2 * buttonSize,
                              text=">>",
                              command=lambda: sys.speedUp(speedChangeAmount))
        fasterButton.grid(row=0, column=0)

        pauseButton = Button(zoomFrame,
                             height=buttonSize,
                             width=2 * buttonSize,
                             text="||",
                             command=lambda: sys.pause(pauseButton))
        pauseButton.grid(row=1, column=0)

        slowerButton = Button(zoomFrame,
                              height=buttonSize,
                              width=2 * buttonSize,
                              text="<<",
                              command=lambda: sys.slowDown(speedChangeAmount))
        slowerButton.grid(row=2, column=0)

        root.bind('<Key>', self.handleKeys)

        sys.pause(pauseButton)

        sys.updateWorlds()
        sys.updateDraw()
Exemple #8
0
from bot import *
from world import *

NUM_OF_ITERATIONS = 10000000

if __name__ == '__main__':

    tinnyT = bot()
    basement = world()

    # Initialize random position for bot
    while True:
        xPos = random.randint(0, 9)
        yPos = random.randint(0, 9)
        if basement.map[yPos][xPos] != "W":
            tinnyT.updatePos(xPos, yPos)
            break

    # Run for the number of iterations desired
    for i in range(NUM_OF_ITERATIONS):
        # Find the direction tinny wants to move
        direction = tinnyT.getDirection()

        # Find the reward and new position
        # The position could not change if a wall collision occurs
        reward, xPos, yPos = basement.timeStep(tinnyT.xPos, tinnyT.yPos, direction)

        # Update rewards and position
        tinnyT.updateReward(xPos, yPos, direction, reward)
        tinnyT.updatePos(xPos, yPos)
Exemple #9
0
import pygame
import sys
from pygame.locals import *
from data import *
from world import *


xy = (800, 600)
Surface = pygame.display.set_mode(xy)
pygame.display.set_caption("xAiJ :: Version beta")
background = (50,50,50)
worldgame = world(Surface)

def main():
    pygame.init()
    
    while(True):
        Draw()
        getInput()
        
    
def getInput():
    key = pygame.key.get_pressed()
    for event in pygame.event.get():
        worldgame.KeyEvent(key, event)
        if event.type == QUIT:
            pygame.quit(); sys.exit()

            
def Draw():
    Surface.fill(background)
Exemple #10
0
def start_game():
    global game
    global game_world
    game = 1

    game_world = world(screen, (75, 50), 1)