From ec7064ef7b2825b79e4919462fea4d4426dd5051 Mon Sep 17 00:00:00 2001 From: "Alejandro U. Alvarez" Date: Wed, 11 May 2022 05:35:04 +0100 Subject: [PATCH] Initial commit --- .gitignore | 25 +++ .idea/evolving-beings.iml | 8 + .idea/modules.xml | 8 + Readme.md | 22 +++ environment.yml | 140 +++++++++++++++ run.py | 52 ++++++ src/being.py | 61 +++++++ src/cell.py | 17 ++ src/playground.ipynb | 367 ++++++++++++++++++++++++++++++++++++++ src/world.py | 62 +++++++ 10 files changed, 762 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/evolving-beings.iml create mode 100644 .idea/modules.xml create mode 100644 Readme.md create mode 100644 environment.yml create mode 100644 run.py create mode 100644 src/being.py create mode 100644 src/cell.py create mode 100644 src/playground.ipynb create mode 100644 src/world.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bdba10d --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries \ No newline at end of file diff --git a/.idea/evolving-beings.iml b/.idea/evolving-beings.iml new file mode 100644 index 0000000..d0876a7 --- /dev/null +++ b/.idea/evolving-beings.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..f2f8c3a --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..df08ae4 --- /dev/null +++ b/Readme.md @@ -0,0 +1,22 @@ +# Evolving Beings + +## Conda environment + +### Create environment + +```bash +conda env create -f environment.yml +``` + +### Update environment after pulling new changes + +```bash +conda env update --file environment.yml --prune +``` + +### Update env file after dependencies: + +```bash +conda env export > environment.yml +``` + diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000..60bf4b8 --- /dev/null +++ b/environment.yml @@ -0,0 +1,140 @@ +name: evolving +channels: + - conda-forge +dependencies: + - appnope=0.1.3=pyhd8ed1ab_0 + - argon2-cffi=21.3.0=pyhd8ed1ab_0 + - argon2-cffi-bindings=21.2.0=py38h33210d7_2 + - asttokens=2.0.5=pyhd8ed1ab_0 + - attrs=21.4.0=pyhd8ed1ab_0 + - backcall=0.2.0=pyh9f0ad1d_0 + - backports=1.0=py_2 + - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 + - beautifulsoup4=4.11.1=pyha770c72_0 + - bleach=5.0.0=pyhd8ed1ab_0 + - brotli=1.0.9=h1c322ee_7 + - brotli-bin=1.0.9=h1c322ee_7 + - bzip2=1.0.8=h3422bc3_4 + - ca-certificates=2021.10.8=h4653dfc_0 + - certifi=2021.10.8=py38h10201cd_2 + - cffi=1.15.0=py38hc67bbb8_0 + - cycler=0.11.0=pyhd8ed1ab_0 + - debugpy=1.6.0=py38hea55cf5_0 + - decorator=5.1.1=pyhd8ed1ab_0 + - defusedxml=0.7.1=pyhd8ed1ab_0 + - entrypoints=0.4=pyhd8ed1ab_0 + - executing=0.8.3=pyhd8ed1ab_0 + - flit-core=3.7.1=pyhd8ed1ab_0 + - fonttools=4.33.3=py38he5c2ac2_0 + - freetype=2.10.4=h17b34a0_1 + - giflib=5.2.1=h27ca646_2 + - importlib-metadata=4.11.3=py38h10201cd_1 + - importlib_resources=5.7.1=pyhd8ed1ab_0 + - ipykernel=6.13.0=py38h2cb4d76_0 + - ipython=8.3.0=py38h10201cd_0 + - ipython_genutils=0.2.0=py_1 + - ipywidgets=7.7.0=pyhd8ed1ab_0 + - jbig=2.1=h3422bc3_2003 + - jedi=0.18.1=py38h10201cd_1 + - jinja2=3.1.2=pyhd8ed1ab_0 + - jpeg=9e=h1c322ee_1 + - jsonschema=4.5.1=pyhd8ed1ab_0 + - jupyter=1.0.0=py38h10201cd_7 + - jupyter_client=7.3.1=pyhd8ed1ab_0 + - jupyter_console=6.4.3=pyhd8ed1ab_0 + - jupyter_core=4.9.2=py38h10201cd_0 + - jupyterlab_pygments=0.2.2=pyhd8ed1ab_0 + - jupyterlab_widgets=1.1.0=pyhd8ed1ab_0 + - kiwisolver=1.4.2=py38h0f71543_1 + - lcms2=2.12=had6a04f_0 + - lerc=3.0=hbdafb3b_0 + - libblas=3.9.0=14_osxarm64_openblas + - libbrotlicommon=1.0.9=h1c322ee_7 + - libbrotlidec=1.0.9=h1c322ee_7 + - libbrotlienc=1.0.9=h1c322ee_7 + - libcblas=3.9.0=14_osxarm64_openblas + - libcxx=14.0.3=h6a5c8ee_0 + - libdeflate=1.10=h3422bc3_0 + - libffi=3.4.2=h3422bc3_5 + - libgfortran=5.0.0.dev0=11_0_1_hf114ba7_23 + - libgfortran5=11.0.1.dev0=hf114ba7_23 + - liblapack=3.9.0=14_osxarm64_openblas + - libopenblas=0.3.20=openmp_h2209c59_0 + - libpng=1.6.37=hf7e6567_2 + - libsodium=1.0.18=h27ca646_1 + - libtiff=4.3.0=h77dc3b6_3 + - libwebp=1.2.2=h0d20362_0 + - libwebp-base=1.2.2=h3422bc3_1 + - libxcb=1.13=h9b22ae9_1004 + - libzlib=1.2.11=h90dfc92_1014 + - llvm-openmp=14.0.3=hd125106_0 + - lz4-c=1.9.3=hbdafb3b_1 + - markupsafe=2.1.1=py38h33210d7_1 + - matplotlib=3.5.2=py38h150bfb4_0 + - matplotlib-base=3.5.2=py38hd7f6e49_0 + - matplotlib-inline=0.1.3=pyhd8ed1ab_0 + - mistune=0.8.4=py38hea4295b_1005 + - munkres=1.1.4=pyh9f0ad1d_0 + - nbclient=0.5.13=pyhd8ed1ab_0 + - nbconvert=6.4.5=py38h10201cd_0 + - nbformat=5.4.0=pyhd8ed1ab_0 + - ncurses=6.3=h07bb92c_1 + - nest-asyncio=1.5.5=pyhd8ed1ab_0 + - notebook=6.4.11=pyha770c72_0 + - numpy=1.22.3=py38h4084d66_2 + - openjpeg=2.4.0=h062765e_1 + - openssl=3.0.3=ha287fd2_0 + - packaging=21.3=pyhd8ed1ab_0 + - pandocfilters=1.5.0=pyhd8ed1ab_0 + - parso=0.8.3=pyhd8ed1ab_0 + - pexpect=4.8.0=pyh9f0ad1d_2 + - pickleshare=0.7.5=py_1003 + - pip=22.0.4=pyhd8ed1ab_0 + - prometheus_client=0.14.1=pyhd8ed1ab_0 + - prompt-toolkit=3.0.29=pyha770c72_0 + - prompt_toolkit=3.0.29=hd8ed1ab_0 + - psutil=5.9.0=py38h33210d7_1 + - pthread-stubs=0.4=h27ca646_1001 + - ptyprocess=0.7.0=pyhd3deb0d_0 + - pure_eval=0.2.2=pyhd8ed1ab_0 + - pycparser=2.21=pyhd8ed1ab_0 + - pygments=2.12.0=pyhd8ed1ab_0 + - pyparsing=3.0.8=pyhd8ed1ab_0 + - pyrsistent=0.18.1=py38h33210d7_1 + - python=3.8.13=hd3575e6_0_cpython + - python-dateutil=2.8.2=pyhd8ed1ab_0 + - python-fastjsonschema=2.15.3=pyhd8ed1ab_0 + - python_abi=3.8=2_cp38 + - pyzmq=22.3.0=py38h5f86631_2 + - readline=8.1=hedafd6a_0 + - send2trash=1.8.0=pyhd8ed1ab_0 + - setuptools=62.2.0=py38h10201cd_0 + - six=1.16.0=pyh6c4a22f_0 + - soupsieve=2.3.1=pyhd8ed1ab_0 + - sqlite=3.38.5=h40dfcc0_0 + - stack_data=0.2.0=pyhd8ed1ab_0 + - terminado=0.13.3=py38h10201cd_1 + - testpath=0.6.0=pyhd8ed1ab_0 + - tk=8.6.12=he1e0b03_0 + - tornado=6.1=py38h33210d7_3 + - traitlets=5.2.0=pyhd8ed1ab_0 + - unicodedata2=14.0.0=py38h33210d7_1 + - wcwidth=0.2.5=pyh9f0ad1d_2 + - webencodings=0.5.1=py_1 + - wheel=0.37.1=pyhd8ed1ab_0 + - widgetsnbextension=3.6.0=py38h10201cd_0 + - xorg-libxau=1.0.9=h27ca646_0 + - xorg-libxdmcp=1.1.3=h27ca646_0 + - xz=5.2.5=h642e427_1 + - zeromq=4.3.4=hbdafb3b_1 + - zipp=3.8.0=pyhd8ed1ab_0 + - zlib=1.2.11=h90dfc92_1014 + - zstd=1.5.2=h861e0a7_0 + - pip: + - arcade==2.6.13 + - pillow==9.0.1 + - pyglet==2.0a2 + - pymunk==6.2.1 + - pytiled-parser==2.0.1 + - typing-extensions==4.2.0 +prefix: /opt/homebrew/Caskroom/miniforge/base/envs/evolving diff --git a/run.py b/run.py new file mode 100644 index 0000000..68c7f1e --- /dev/null +++ b/run.py @@ -0,0 +1,52 @@ +import arcade + +from src.world import World + +SCREEN_WIDTH = 500 +SCREEN_HEIGHT = 500 +SCREEN_TITLE = "Evolving Beings" + + +class EvolvingBeings(arcade.Window): + def __init__(self): + super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) + + self.world = World(250, 250) + self.world.spawn(10) + + def setup(self): + """Sets up the world for the current simulation""" + pass + + def on_key_press(self, key: int, modifiers: int): + """Processes key presses + + Arguments: + key {int} -- Which key was pressed + modifiers {int} -- Which modifiers were down at the time + """ + + def on_key_release(self, key: int, modifiers: int): + """Processes key releases + + Arguments: + key {int} -- Which key was released + modifiers {int} -- Which modifiers were down at the time + """ + + def on_update(self, delta_time: float): + """Updates the position of all game objects + + Arguments: + delta_time {float} -- How much time since the last call + """ + pass + + def on_draw(self): + pass + + +if __name__ == "__main__": + window = EvolvingBeings() + window.setup() + arcade.run() diff --git a/src/being.py b/src/being.py new file mode 100644 index 0000000..9dbb3af --- /dev/null +++ b/src/being.py @@ -0,0 +1,61 @@ +import numpy as np +from math import cos, sin +import random + +# Hyper-parameters +ENERGY_LOSS_GENERAL = 0.1 +ENERGY_LOSS_ACTIONS = 0.2 + +FOOD_TO_ENERGY = 0.1 +WATER_TO_ENERGY = 0.1 + +# Rotation vectors for movement +theta = np.deg2rad(45) +rot_right = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]]) +rot_left = np.array([[cos(-theta), -sin(-theta)], [sin(-theta), cos(-theta)]]) + + +class Being: + """ + Living being representation. If energy reaches 0 it will be dead + + Energy goes down when performing actions, low energy leads to lower happiness. + """ + # Subjective states (things the "brain" feels) + happiness = 1 + hunger = 0 + thirst = 0 + + # Objective states (hidden from the "brain") + food = 1 + water = 1 + energy = 1 + + direction = [1, 0] # vector from (0,0) (the being) to the direction its facing + action_space = ['NOOP', 'TURN_LEFT', 'TURN_RIGHT', 'MOVE', 'EAT', 'DRINK'] + + def choose_action(self): + action = random.choice(self.action_space) + + if action != 'NOOP': + self.energy -= ENERGY_LOSS_ACTIONS + + if action == 'TURN_LEFT' or action == 'TURN_RIGHT': + rot = rot_left if action == 'TURN_LEFT' else rot_right + self.direction = np.round(np.dot(rot, self.direction), 0).astype(int) + + return action + + def step(self): + self.energy -= ENERGY_LOSS_GENERAL + + if self.food > 0: + self.food -= FOOD_TO_ENERGY + self.energy += FOOD_TO_ENERGY + + if self.water > 0: + self.water -= WATER_TO_ENERGY + self.energy += WATER_TO_ENERGY + + def color(self): + return 155 + self.energy * 100 \ No newline at end of file diff --git a/src/cell.py b/src/cell.py new file mode 100644 index 0000000..0446671 --- /dev/null +++ b/src/cell.py @@ -0,0 +1,17 @@ +class Cell: + def __init__(self, x, y): + self.x = x + self.y = y + self.type = 'NONE' + self.content = None + + def update(self, type, content=None): + self.type = type + self.content = content + + def color(self): + if self.type == 'NONE': + return 0 + + if self.type == 'BEING': + return self.content.color() \ No newline at end of file diff --git a/src/playground.ipynb b/src/playground.ipynb new file mode 100644 index 0000000..e30c7ee --- /dev/null +++ b/src/playground.ipynb @@ -0,0 +1,367 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import random\n", + "from math import cos, sin\n", + "import matplotlib.animation as animation\n", + "\n", + "random.seed(1)\n", + "\n", + "plt.rcParams[\"figure.figsize\"] = (10, 10)\n", + "\n", + "%matplotlib notebook" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "outputs": [ + { + "data": { + "text/plain": "", + "application/javascript": "/* Put everything inside the global mpl namespace */\n/* global mpl */\nwindow.mpl = {};\n\nmpl.get_websocket_type = function () {\n if (typeof WebSocket !== 'undefined') {\n return WebSocket;\n } else if (typeof MozWebSocket !== 'undefined') {\n return MozWebSocket;\n } else {\n alert(\n 'Your browser does not have WebSocket support. ' +\n 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n 'Firefox 4 and 5 are also supported but you ' +\n 'have to enable WebSockets in about:config.'\n );\n }\n};\n\nmpl.figure = function (figure_id, websocket, ondownload, parent_element) {\n this.id = figure_id;\n\n this.ws = websocket;\n\n this.supports_binary = this.ws.binaryType !== undefined;\n\n if (!this.supports_binary) {\n var warnings = document.getElementById('mpl-warnings');\n if (warnings) {\n warnings.style.display = 'block';\n warnings.textContent =\n 'This browser does not support binary websocket messages. ' +\n 'Performance may be slow.';\n }\n }\n\n this.imageObj = new Image();\n\n this.context = undefined;\n this.message = undefined;\n this.canvas = undefined;\n this.rubberband_canvas = undefined;\n this.rubberband_context = undefined;\n this.format_dropdown = undefined;\n\n this.image_mode = 'full';\n\n this.root = document.createElement('div');\n this.root.setAttribute('style', 'display: inline-block');\n this._root_extra_style(this.root);\n\n parent_element.appendChild(this.root);\n\n this._init_header(this);\n this._init_canvas(this);\n this._init_toolbar(this);\n\n var fig = this;\n\n this.waiting = false;\n\n this.ws.onopen = function () {\n fig.send_message('supports_binary', { value: fig.supports_binary });\n fig.send_message('send_image_mode', {});\n if (fig.ratio !== 1) {\n fig.send_message('set_device_pixel_ratio', {\n device_pixel_ratio: fig.ratio,\n });\n }\n fig.send_message('refresh', {});\n };\n\n this.imageObj.onload = function () {\n if (fig.image_mode === 'full') {\n // Full images could contain transparency (where diff images\n // almost always do), so we need to clear the canvas so that\n // there is no ghosting.\n fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n }\n fig.context.drawImage(fig.imageObj, 0, 0);\n };\n\n this.imageObj.onunload = function () {\n fig.ws.close();\n };\n\n this.ws.onmessage = this._make_on_message_function(this);\n\n this.ondownload = ondownload;\n};\n\nmpl.figure.prototype._init_header = function () {\n var titlebar = document.createElement('div');\n titlebar.classList =\n 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';\n var titletext = document.createElement('div');\n titletext.classList = 'ui-dialog-title';\n titletext.setAttribute(\n 'style',\n 'width: 100%; text-align: center; padding: 3px;'\n );\n titlebar.appendChild(titletext);\n this.root.appendChild(titlebar);\n this.header = titletext;\n};\n\nmpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};\n\nmpl.figure.prototype._root_extra_style = function (_canvas_div) {};\n\nmpl.figure.prototype._init_canvas = function () {\n var fig = this;\n\n var canvas_div = (this.canvas_div = document.createElement('div'));\n canvas_div.setAttribute(\n 'style',\n 'border: 1px solid #ddd;' +\n 'box-sizing: content-box;' +\n 'clear: both;' +\n 'min-height: 1px;' +\n 'min-width: 1px;' +\n 'outline: 0;' +\n 'overflow: hidden;' +\n 'position: relative;' +\n 'resize: both;'\n );\n\n function on_keyboard_event_closure(name) {\n return function (event) {\n return fig.key_event(event, name);\n };\n }\n\n canvas_div.addEventListener(\n 'keydown',\n on_keyboard_event_closure('key_press')\n );\n canvas_div.addEventListener(\n 'keyup',\n on_keyboard_event_closure('key_release')\n );\n\n this._canvas_extra_style(canvas_div);\n this.root.appendChild(canvas_div);\n\n var canvas = (this.canvas = document.createElement('canvas'));\n canvas.classList.add('mpl-canvas');\n canvas.setAttribute('style', 'box-sizing: content-box;');\n\n this.context = canvas.getContext('2d');\n\n var backingStore =\n this.context.backingStorePixelRatio ||\n this.context.webkitBackingStorePixelRatio ||\n this.context.mozBackingStorePixelRatio ||\n this.context.msBackingStorePixelRatio ||\n this.context.oBackingStorePixelRatio ||\n this.context.backingStorePixelRatio ||\n 1;\n\n this.ratio = (window.devicePixelRatio || 1) / backingStore;\n\n var rubberband_canvas = (this.rubberband_canvas = document.createElement(\n 'canvas'\n ));\n rubberband_canvas.setAttribute(\n 'style',\n 'box-sizing: content-box; position: absolute; left: 0; top: 0; z-index: 1;'\n );\n\n // Apply a ponyfill if ResizeObserver is not implemented by browser.\n if (this.ResizeObserver === undefined) {\n if (window.ResizeObserver !== undefined) {\n this.ResizeObserver = window.ResizeObserver;\n } else {\n var obs = _JSXTOOLS_RESIZE_OBSERVER({});\n this.ResizeObserver = obs.ResizeObserver;\n }\n }\n\n this.resizeObserverInstance = new this.ResizeObserver(function (entries) {\n var nentries = entries.length;\n for (var i = 0; i < nentries; i++) {\n var entry = entries[i];\n var width, height;\n if (entry.contentBoxSize) {\n if (entry.contentBoxSize instanceof Array) {\n // Chrome 84 implements new version of spec.\n width = entry.contentBoxSize[0].inlineSize;\n height = entry.contentBoxSize[0].blockSize;\n } else {\n // Firefox implements old version of spec.\n width = entry.contentBoxSize.inlineSize;\n height = entry.contentBoxSize.blockSize;\n }\n } else {\n // Chrome <84 implements even older version of spec.\n width = entry.contentRect.width;\n height = entry.contentRect.height;\n }\n\n // Keep the size of the canvas and rubber band canvas in sync with\n // the canvas container.\n if (entry.devicePixelContentBoxSize) {\n // Chrome 84 implements new version of spec.\n canvas.setAttribute(\n 'width',\n entry.devicePixelContentBoxSize[0].inlineSize\n );\n canvas.setAttribute(\n 'height',\n entry.devicePixelContentBoxSize[0].blockSize\n );\n } else {\n canvas.setAttribute('width', width * fig.ratio);\n canvas.setAttribute('height', height * fig.ratio);\n }\n canvas.setAttribute(\n 'style',\n 'width: ' + width + 'px; height: ' + height + 'px;'\n );\n\n rubberband_canvas.setAttribute('width', width);\n rubberband_canvas.setAttribute('height', height);\n\n // And update the size in Python. We ignore the initial 0/0 size\n // that occurs as the element is placed into the DOM, which should\n // otherwise not happen due to the minimum size styling.\n if (fig.ws.readyState == 1 && width != 0 && height != 0) {\n fig.request_resize(width, height);\n }\n }\n });\n this.resizeObserverInstance.observe(canvas_div);\n\n function on_mouse_event_closure(name) {\n return function (event) {\n return fig.mouse_event(event, name);\n };\n }\n\n rubberband_canvas.addEventListener(\n 'mousedown',\n on_mouse_event_closure('button_press')\n );\n rubberband_canvas.addEventListener(\n 'mouseup',\n on_mouse_event_closure('button_release')\n );\n rubberband_canvas.addEventListener(\n 'dblclick',\n on_mouse_event_closure('dblclick')\n );\n // Throttle sequential mouse events to 1 every 20ms.\n rubberband_canvas.addEventListener(\n 'mousemove',\n on_mouse_event_closure('motion_notify')\n );\n\n rubberband_canvas.addEventListener(\n 'mouseenter',\n on_mouse_event_closure('figure_enter')\n );\n rubberband_canvas.addEventListener(\n 'mouseleave',\n on_mouse_event_closure('figure_leave')\n );\n\n canvas_div.addEventListener('wheel', function (event) {\n if (event.deltaY < 0) {\n event.step = 1;\n } else {\n event.step = -1;\n }\n on_mouse_event_closure('scroll')(event);\n });\n\n canvas_div.appendChild(canvas);\n canvas_div.appendChild(rubberband_canvas);\n\n this.rubberband_context = rubberband_canvas.getContext('2d');\n this.rubberband_context.strokeStyle = '#000000';\n\n this._resize_canvas = function (width, height, forward) {\n if (forward) {\n canvas_div.style.width = width + 'px';\n canvas_div.style.height = height + 'px';\n }\n };\n\n // Disable right mouse context menu.\n this.rubberband_canvas.addEventListener('contextmenu', function (_e) {\n event.preventDefault();\n return false;\n });\n\n function set_focus() {\n canvas.focus();\n canvas_div.focus();\n }\n\n window.setTimeout(set_focus, 100);\n};\n\nmpl.figure.prototype._init_toolbar = function () {\n var fig = this;\n\n var toolbar = document.createElement('div');\n toolbar.classList = 'mpl-toolbar';\n this.root.appendChild(toolbar);\n\n function on_click_closure(name) {\n return function (_event) {\n return fig.toolbar_button_onclick(name);\n };\n }\n\n function on_mouseover_closure(tooltip) {\n return function (event) {\n if (!event.currentTarget.disabled) {\n return fig.toolbar_button_onmouseover(tooltip);\n }\n };\n }\n\n fig.buttons = {};\n var buttonGroup = document.createElement('div');\n buttonGroup.classList = 'mpl-button-group';\n for (var toolbar_ind in mpl.toolbar_items) {\n var name = mpl.toolbar_items[toolbar_ind][0];\n var tooltip = mpl.toolbar_items[toolbar_ind][1];\n var image = mpl.toolbar_items[toolbar_ind][2];\n var method_name = mpl.toolbar_items[toolbar_ind][3];\n\n if (!name) {\n /* Instead of a spacer, we start a new button group. */\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n buttonGroup = document.createElement('div');\n buttonGroup.classList = 'mpl-button-group';\n continue;\n }\n\n var button = (fig.buttons[name] = document.createElement('button'));\n button.classList = 'mpl-widget';\n button.setAttribute('role', 'button');\n button.setAttribute('aria-disabled', 'false');\n button.addEventListener('click', on_click_closure(method_name));\n button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n\n var icon_img = document.createElement('img');\n icon_img.src = '_images/' + image + '.png';\n icon_img.srcset = '_images/' + image + '_large.png 2x';\n icon_img.alt = tooltip;\n button.appendChild(icon_img);\n\n buttonGroup.appendChild(button);\n }\n\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n\n var fmt_picker = document.createElement('select');\n fmt_picker.classList = 'mpl-widget';\n toolbar.appendChild(fmt_picker);\n this.format_dropdown = fmt_picker;\n\n for (var ind in mpl.extensions) {\n var fmt = mpl.extensions[ind];\n var option = document.createElement('option');\n option.selected = fmt === mpl.default_extension;\n option.innerHTML = fmt;\n fmt_picker.appendChild(option);\n }\n\n var status_bar = document.createElement('span');\n status_bar.classList = 'mpl-message';\n toolbar.appendChild(status_bar);\n this.message = status_bar;\n};\n\nmpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {\n // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n // which will in turn request a refresh of the image.\n this.send_message('resize', { width: x_pixels, height: y_pixels });\n};\n\nmpl.figure.prototype.send_message = function (type, properties) {\n properties['type'] = type;\n properties['figure_id'] = this.id;\n this.ws.send(JSON.stringify(properties));\n};\n\nmpl.figure.prototype.send_draw_message = function () {\n if (!this.waiting) {\n this.waiting = true;\n this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));\n }\n};\n\nmpl.figure.prototype.handle_save = function (fig, _msg) {\n var format_dropdown = fig.format_dropdown;\n var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n fig.ondownload(fig, format);\n};\n\nmpl.figure.prototype.handle_resize = function (fig, msg) {\n var size = msg['size'];\n if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {\n fig._resize_canvas(size[0], size[1], msg['forward']);\n fig.send_message('refresh', {});\n }\n};\n\nmpl.figure.prototype.handle_rubberband = function (fig, msg) {\n var x0 = msg['x0'] / fig.ratio;\n var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;\n var x1 = msg['x1'] / fig.ratio;\n var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;\n x0 = Math.floor(x0) + 0.5;\n y0 = Math.floor(y0) + 0.5;\n x1 = Math.floor(x1) + 0.5;\n y1 = Math.floor(y1) + 0.5;\n var min_x = Math.min(x0, x1);\n var min_y = Math.min(y0, y1);\n var width = Math.abs(x1 - x0);\n var height = Math.abs(y1 - y0);\n\n fig.rubberband_context.clearRect(\n 0,\n 0,\n fig.canvas.width / fig.ratio,\n fig.canvas.height / fig.ratio\n );\n\n fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n};\n\nmpl.figure.prototype.handle_figure_label = function (fig, msg) {\n // Updates the figure title.\n fig.header.textContent = msg['label'];\n};\n\nmpl.figure.prototype.handle_cursor = function (fig, msg) {\n fig.rubberband_canvas.style.cursor = msg['cursor'];\n};\n\nmpl.figure.prototype.handle_message = function (fig, msg) {\n fig.message.textContent = msg['message'];\n};\n\nmpl.figure.prototype.handle_draw = function (fig, _msg) {\n // Request the server to send over a new figure.\n fig.send_draw_message();\n};\n\nmpl.figure.prototype.handle_image_mode = function (fig, msg) {\n fig.image_mode = msg['mode'];\n};\n\nmpl.figure.prototype.handle_history_buttons = function (fig, msg) {\n for (var key in msg) {\n if (!(key in fig.buttons)) {\n continue;\n }\n fig.buttons[key].disabled = !msg[key];\n fig.buttons[key].setAttribute('aria-disabled', !msg[key]);\n }\n};\n\nmpl.figure.prototype.handle_navigate_mode = function (fig, msg) {\n if (msg['mode'] === 'PAN') {\n fig.buttons['Pan'].classList.add('active');\n fig.buttons['Zoom'].classList.remove('active');\n } else if (msg['mode'] === 'ZOOM') {\n fig.buttons['Pan'].classList.remove('active');\n fig.buttons['Zoom'].classList.add('active');\n } else {\n fig.buttons['Pan'].classList.remove('active');\n fig.buttons['Zoom'].classList.remove('active');\n }\n};\n\nmpl.figure.prototype.updated_canvas_event = function () {\n // Called whenever the canvas gets updated.\n this.send_message('ack', {});\n};\n\n// A function to construct a web socket function for onmessage handling.\n// Called in the figure constructor.\nmpl.figure.prototype._make_on_message_function = function (fig) {\n return function socket_on_message(evt) {\n if (evt.data instanceof Blob) {\n var img = evt.data;\n if (img.type !== 'image/png') {\n /* FIXME: We get \"Resource interpreted as Image but\n * transferred with MIME type text/plain:\" errors on\n * Chrome. But how to set the MIME type? It doesn't seem\n * to be part of the websocket stream */\n img.type = 'image/png';\n }\n\n /* Free the memory for the previous frames */\n if (fig.imageObj.src) {\n (window.URL || window.webkitURL).revokeObjectURL(\n fig.imageObj.src\n );\n }\n\n fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n img\n );\n fig.updated_canvas_event();\n fig.waiting = false;\n return;\n } else if (\n typeof evt.data === 'string' &&\n evt.data.slice(0, 21) === 'data:image/png;base64'\n ) {\n fig.imageObj.src = evt.data;\n fig.updated_canvas_event();\n fig.waiting = false;\n return;\n }\n\n var msg = JSON.parse(evt.data);\n var msg_type = msg['type'];\n\n // Call the \"handle_{type}\" callback, which takes\n // the figure and JSON message as its only arguments.\n try {\n var callback = fig['handle_' + msg_type];\n } catch (e) {\n console.log(\n \"No handler for the '\" + msg_type + \"' message type: \",\n msg\n );\n return;\n }\n\n if (callback) {\n try {\n // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n callback(fig, msg);\n } catch (e) {\n console.log(\n \"Exception inside the 'handler_\" + msg_type + \"' callback:\",\n e,\n e.stack,\n msg\n );\n }\n }\n };\n};\n\n// from https://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\nmpl.findpos = function (e) {\n //this section is from http://www.quirksmode.org/js/events_properties.html\n var targ;\n if (!e) {\n e = window.event;\n }\n if (e.target) {\n targ = e.target;\n } else if (e.srcElement) {\n targ = e.srcElement;\n }\n if (targ.nodeType === 3) {\n // defeat Safari bug\n targ = targ.parentNode;\n }\n\n // pageX,Y are the mouse positions relative to the document\n var boundingRect = targ.getBoundingClientRect();\n var x = e.pageX - (boundingRect.left + document.body.scrollLeft);\n var y = e.pageY - (boundingRect.top + document.body.scrollTop);\n\n return { x: x, y: y };\n};\n\n/*\n * return a copy of an object with only non-object keys\n * we need this to avoid circular references\n * https://stackoverflow.com/a/24161582/3208463\n */\nfunction simpleKeys(original) {\n return Object.keys(original).reduce(function (obj, key) {\n if (typeof original[key] !== 'object') {\n obj[key] = original[key];\n }\n return obj;\n }, {});\n}\n\nmpl.figure.prototype.mouse_event = function (event, name) {\n var canvas_pos = mpl.findpos(event);\n\n if (name === 'button_press') {\n this.canvas.focus();\n this.canvas_div.focus();\n }\n\n var x = canvas_pos.x * this.ratio;\n var y = canvas_pos.y * this.ratio;\n\n this.send_message(name, {\n x: x,\n y: y,\n button: event.button,\n step: event.step,\n guiEvent: simpleKeys(event),\n });\n\n /* This prevents the web browser from automatically changing to\n * the text insertion cursor when the button is pressed. We want\n * to control all of the cursor setting manually through the\n * 'cursor' event from matplotlib */\n event.preventDefault();\n return false;\n};\n\nmpl.figure.prototype._key_event_extra = function (_event, _name) {\n // Handle any extra behaviour associated with a key event\n};\n\nmpl.figure.prototype.key_event = function (event, name) {\n // Prevent repeat events\n if (name === 'key_press') {\n if (event.key === this._key) {\n return;\n } else {\n this._key = event.key;\n }\n }\n if (name === 'key_release') {\n this._key = null;\n }\n\n var value = '';\n if (event.ctrlKey && event.key !== 'Control') {\n value += 'ctrl+';\n }\n else if (event.altKey && event.key !== 'Alt') {\n value += 'alt+';\n }\n else if (event.shiftKey && event.key !== 'Shift') {\n value += 'shift+';\n }\n\n value += 'k' + event.key;\n\n this._key_event_extra(event, name);\n\n this.send_message(name, { key: value, guiEvent: simpleKeys(event) });\n return false;\n};\n\nmpl.figure.prototype.toolbar_button_onclick = function (name) {\n if (name === 'download') {\n this.handle_save(this, null);\n } else {\n this.send_message('toolbar_button', { name: name });\n }\n};\n\nmpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {\n this.message.textContent = tooltip;\n};\n\n///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n// prettier-ignore\nvar _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError(\"Constructor requires 'new' operator\");i.set(this,e)}function h(){throw new TypeError(\"Function is not a constructor\")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line\nmpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Left button pans, Right button zooms\\nx/y fixes axis, CTRL fixes aspect\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\\nx/y fixes axis\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n\nmpl.extensions = [\"eps\", \"jpeg\", \"pgf\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\", \"tif\"];\n\nmpl.default_extension = \"png\";/* global mpl */\n\nvar comm_websocket_adapter = function (comm) {\n // Create a \"websocket\"-like object which calls the given IPython comm\n // object with the appropriate methods. Currently this is a non binary\n // socket, so there is still some room for performance tuning.\n var ws = {};\n\n ws.binaryType = comm.kernel.ws.binaryType;\n ws.readyState = comm.kernel.ws.readyState;\n function updateReadyState(_event) {\n if (comm.kernel.ws) {\n ws.readyState = comm.kernel.ws.readyState;\n } else {\n ws.readyState = 3; // Closed state.\n }\n }\n comm.kernel.ws.addEventListener('open', updateReadyState);\n comm.kernel.ws.addEventListener('close', updateReadyState);\n comm.kernel.ws.addEventListener('error', updateReadyState);\n\n ws.close = function () {\n comm.close();\n };\n ws.send = function (m) {\n //console.log('sending', m);\n comm.send(m);\n };\n // Register the callback with on_msg.\n comm.on_msg(function (msg) {\n //console.log('receiving', msg['content']['data'], msg);\n var data = msg['content']['data'];\n if (data['blob'] !== undefined) {\n data = {\n data: new Blob(msg['buffers'], { type: data['blob'] }),\n };\n }\n // Pass the mpl event to the overridden (by mpl) onmessage function.\n ws.onmessage(data);\n });\n return ws;\n};\n\nmpl.mpl_figure_comm = function (comm, msg) {\n // This is the function which gets called when the mpl process\n // starts-up an IPython Comm through the \"matplotlib\" channel.\n\n var id = msg.content.data.id;\n // Get hold of the div created by the display call when the Comm\n // socket was opened in Python.\n var element = document.getElementById(id);\n var ws_proxy = comm_websocket_adapter(comm);\n\n function ondownload(figure, _format) {\n window.open(figure.canvas.toDataURL());\n }\n\n var fig = new mpl.figure(id, ws_proxy, ondownload, element);\n\n // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n // web socket which is closed, not our websocket->open comm proxy.\n ws_proxy.onopen();\n\n fig.parent_element = element;\n fig.cell_info = mpl.find_output_cell(\"
\");\n if (!fig.cell_info) {\n console.error('Failed to find cell for figure', id, fig);\n return;\n }\n fig.cell_info[0].output_area.element.on(\n 'cleared',\n { fig: fig },\n fig._remove_fig_handler\n );\n};\n\nmpl.figure.prototype.handle_close = function (fig, msg) {\n var width = fig.canvas.width / fig.ratio;\n fig.cell_info[0].output_area.element.off(\n 'cleared',\n fig._remove_fig_handler\n );\n fig.resizeObserverInstance.unobserve(fig.canvas_div);\n\n // Update the output cell to use the data from the current canvas.\n fig.push_to_output();\n var dataURL = fig.canvas.toDataURL();\n // Re-enable the keyboard manager in IPython - without this line, in FF,\n // the notebook keyboard shortcuts fail.\n IPython.keyboard_manager.enable();\n fig.parent_element.innerHTML =\n '';\n fig.close_ws(fig, msg);\n};\n\nmpl.figure.prototype.close_ws = function (fig, msg) {\n fig.send_message('closing', msg);\n // fig.ws.close()\n};\n\nmpl.figure.prototype.push_to_output = function (_remove_interactive) {\n // Turn the data on the canvas into data in the output cell.\n var width = this.canvas.width / this.ratio;\n var dataURL = this.canvas.toDataURL();\n this.cell_info[1]['text/html'] =\n '';\n};\n\nmpl.figure.prototype.updated_canvas_event = function () {\n // Tell IPython that the notebook contents must change.\n IPython.notebook.set_dirty(true);\n this.send_message('ack', {});\n var fig = this;\n // Wait a second, then push the new image to the DOM so\n // that it is saved nicely (might be nice to debounce this).\n setTimeout(function () {\n fig.push_to_output();\n }, 1000);\n};\n\nmpl.figure.prototype._init_toolbar = function () {\n var fig = this;\n\n var toolbar = document.createElement('div');\n toolbar.classList = 'btn-toolbar';\n this.root.appendChild(toolbar);\n\n function on_click_closure(name) {\n return function (_event) {\n return fig.toolbar_button_onclick(name);\n };\n }\n\n function on_mouseover_closure(tooltip) {\n return function (event) {\n if (!event.currentTarget.disabled) {\n return fig.toolbar_button_onmouseover(tooltip);\n }\n };\n }\n\n fig.buttons = {};\n var buttonGroup = document.createElement('div');\n buttonGroup.classList = 'btn-group';\n var button;\n for (var toolbar_ind in mpl.toolbar_items) {\n var name = mpl.toolbar_items[toolbar_ind][0];\n var tooltip = mpl.toolbar_items[toolbar_ind][1];\n var image = mpl.toolbar_items[toolbar_ind][2];\n var method_name = mpl.toolbar_items[toolbar_ind][3];\n\n if (!name) {\n /* Instead of a spacer, we start a new button group. */\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n buttonGroup = document.createElement('div');\n buttonGroup.classList = 'btn-group';\n continue;\n }\n\n button = fig.buttons[name] = document.createElement('button');\n button.classList = 'btn btn-default';\n button.href = '#';\n button.title = name;\n button.innerHTML = '';\n button.addEventListener('click', on_click_closure(method_name));\n button.addEventListener('mouseover', on_mouseover_closure(tooltip));\n buttonGroup.appendChild(button);\n }\n\n if (buttonGroup.hasChildNodes()) {\n toolbar.appendChild(buttonGroup);\n }\n\n // Add the status bar.\n var status_bar = document.createElement('span');\n status_bar.classList = 'mpl-message pull-right';\n toolbar.appendChild(status_bar);\n this.message = status_bar;\n\n // Add the close button to the window.\n var buttongrp = document.createElement('div');\n buttongrp.classList = 'btn-group inline pull-right';\n button = document.createElement('button');\n button.classList = 'btn btn-mini btn-primary';\n button.href = '#';\n button.title = 'Stop Interaction';\n button.innerHTML = '';\n button.addEventListener('click', function (_evt) {\n fig.handle_close(fig, {});\n });\n button.addEventListener(\n 'mouseover',\n on_mouseover_closure('Stop Interaction')\n );\n buttongrp.appendChild(button);\n var titlebar = this.root.querySelector('.ui-dialog-titlebar');\n titlebar.insertBefore(buttongrp, titlebar.firstChild);\n};\n\nmpl.figure.prototype._remove_fig_handler = function (event) {\n var fig = event.data.fig;\n if (event.target !== this) {\n // Ignore bubbled events from children.\n return;\n }\n fig.close_ws(fig, {});\n};\n\nmpl.figure.prototype._root_extra_style = function (el) {\n el.style.boxSizing = 'content-box'; // override notebook setting of border-box.\n};\n\nmpl.figure.prototype._canvas_extra_style = function (el) {\n // this is important to make the div 'focusable\n el.setAttribute('tabindex', 0);\n // reach out to IPython and tell the keyboard manager to turn it's self\n // off when our div gets focus\n\n // location in version 3\n if (IPython.notebook.keyboard_manager) {\n IPython.notebook.keyboard_manager.register_events(el);\n } else {\n // location in version 2\n IPython.keyboard_manager.register_events(el);\n }\n};\n\nmpl.figure.prototype._key_event_extra = function (event, _name) {\n // Check for shift+enter\n if (event.shiftKey && event.which === 13) {\n this.canvas_div.blur();\n // select the cell after this one\n var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n IPython.notebook.select(index + 1);\n }\n};\n\nmpl.figure.prototype.handle_save = function (fig, _msg) {\n fig.ondownload(fig, null);\n};\n\nmpl.find_output_cell = function (html_output) {\n // Return the cell and output element which can be found *uniquely* in the notebook.\n // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n // IPython event is triggered only after the cells have been serialised, which for\n // our purposes (turning an active figure into a static one), is too late.\n var cells = IPython.notebook.get_cells();\n var ncells = cells.length;\n for (var i = 0; i < ncells; i++) {\n var cell = cells[i];\n if (cell.cell_type === 'code') {\n for (var j = 0; j < cell.output_area.outputs.length; j++) {\n var data = cell.output_area.outputs[j];\n if (data.data) {\n // IPython >= 3 moved mimebundle to data attribute of output\n data = data.data;\n }\n if (data['text/html'] === html_output) {\n return [cell, data, j];\n }\n }\n }\n }\n};\n\n// Register the function which deals with the matplotlib target/channel.\n// The kernel may be null if the page has been refreshed.\nif (IPython.notebook.kernel !== null) {\n IPython.notebook.kernel.comm_manager.register_target(\n 'matplotlib',\n mpl.mpl_figure_comm\n );\n}\n" + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": "", + "text/html": "
" + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/matplotlib/animation.py:887: UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you have outputted the Animation using `plt.show()` or `anim.save()`.\n", + " warnings.warn(\n" + ] + } + ], + "source": [ + "# Hyper-parameters\n", + "ENERGY_LOSS_GENERAL = 0.1\n", + "ENERGY_LOSS_ACTIONS = 0.2\n", + "\n", + "FOOD_TO_ENERGY = 0.1\n", + "WATER_TO_ENERGY = 0.1\n", + "\n", + "# Rotation vectors for movement\n", + "theta = np.deg2rad(45)\n", + "rot_right = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])\n", + "rot_left = np.array([[cos(-theta), -sin(-theta)], [sin(-theta), cos(-theta)]])\n", + "\n", + "class Being:\n", + " \"\"\"\n", + " Living being representation. If energy reaches 0 it will be dead\n", + "\n", + " Energy goes down when performing actions, low energy leads to lower happiness.\n", + " \"\"\"\n", + " # Subjective states (things the \"brain\" feels)\n", + " happiness = 1\n", + " hunger = 0\n", + " thirst = 0\n", + "\n", + " # Objective states (hidden from the \"brain\")\n", + " food = 1\n", + " water = 1\n", + " energy = 1\n", + "\n", + " direction = [1, 0] # vector from (0,0) (the being) to the direction its facing\n", + " action_space = ['NOOP', 'TURN_LEFT', 'TURN_RIGHT', 'MOVE', 'EAT', 'DRINK']\n", + "\n", + " def choose_action(self):\n", + " action = random.choice(self.action_space)\n", + "\n", + " if action != 'NOOP':\n", + " self.energy -= ENERGY_LOSS_ACTIONS\n", + "\n", + " if action == 'TURN_LEFT' or action == 'TURN_RIGHT':\n", + " rot = rot_left if action == 'TURN_LEFT' else rot_right\n", + " self.direction = np.round(np.dot(rot, self.direction), 0).astype(int)\n", + "\n", + " return action\n", + "\n", + " def step(self):\n", + " self.energy -= ENERGY_LOSS_GENERAL\n", + "\n", + " if self.food > 0:\n", + " self.food -= FOOD_TO_ENERGY\n", + " self.energy += FOOD_TO_ENERGY\n", + "\n", + " if self.water > 0:\n", + " self.water -= WATER_TO_ENERGY\n", + " self.energy += WATER_TO_ENERGY\n", + "\n", + " def color(self):\n", + " return 155 + self.energy * 100\n", + "\n", + "class Cell:\n", + " def __init__(self, x, y):\n", + " self.x = x\n", + " self.y = y\n", + " self.type = 'NONE'\n", + " self.content = None\n", + "\n", + " def update(self, type, content=None):\n", + " self.type = type\n", + " self.content = content\n", + "\n", + " def color(self):\n", + " if self.type == 'NONE':\n", + " return 0\n", + "\n", + " if self.type == 'BEING':\n", + " return self.content.color()\n", + "\n", + "class World:\n", + " def __init__(self, w=128, h=128):\n", + " self.w = w\n", + " self.h = h\n", + " self.state = np.empty((w, h), dtype=object)\n", + " for i in range(w):\n", + " for j in range(h):\n", + " self.state[i, j] = Cell(i, j)\n", + "\n", + " self.im = plt.imshow(np.zeros((self.w, self.h)), cmap='gray', vmin=0, vmax=255, animated=True)\n", + "\n", + " def step(self):\n", + " state = np.copy(self.state)\n", + "\n", + " for i, row in enumerate(self.state):\n", + " for j, cell in enumerate(row):\n", + " if cell.type != 'BEING':\n", + " continue\n", + "\n", + " cell.content.step()\n", + " action = cell.content.choose_action()\n", + "\n", + " if action == 'MOVE':\n", + " # lets see if the desired cell is empty\n", + " direction = cell.content.direction\n", + " next_loc = [\n", + " max(0, min(self.w - 1, cell.x + direction[0])),\n", + " max(0, min(self.h - 1, cell.y + direction[1]))\n", + " ]\n", + "\n", + " if state[next_loc[0], next_loc[1]].type == 'NONE':\n", + " # cell is empty, lets move!\n", + " state[next_loc[0], next_loc[1]].update('BEING', cell.content)\n", + " state[i, j].update('NONE')\n", + "\n", + " self.state = state\n", + "\n", + " def spawn(self, number):\n", + " for _ in range(number):\n", + " x = random.randint(0, self.w - 1)\n", + " y = random.randint(0, self.h - 1)\n", + "\n", + " while self.state[x, y].type != 'NONE':\n", + " x = random.randint(0, self.w - 1)\n", + " y = random.randint(0, self.h - 1)\n", + " # TODO: this could be infinite\n", + "\n", + " being = Being()\n", + " self.state[x, y].update('BEING', being)\n", + "\n", + " def render(self):\n", + " state = np.zeros((self.w, self.h))\n", + " for i, row in enumerate(self.state):\n", + " for j, cell in enumerate(row):\n", + " state[i, j] = cell.color()\n", + "\n", + " self.im.set_array(state)\n", + " return [self.im]\n", + "\n", + "fig = plt.figure(figsize=(10, 10))\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "\n", + "world = World()\n", + "world.spawn(10)\n", + "world.render()\n", + "\n", + "def animate():\n", + " world.step()\n", + " return world.render()\n", + "\n", + "fps = 30\n", + "\n", + "animation.FuncAnimation(fig, animate, frames=100, interval=1000/fps)\n", + "plt.show()" + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + }, + { + "cell_type": "code", + "execution_count": 20, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 0 -1]\n", + "[-1 -1]\n", + "[-1 0]\n", + "[-1 1]\n", + "[0 1]\n", + "[1 1]\n", + "[1 0]\n", + "[ 1 -1]\n", + "[ 0 -1]\n", + "[-1 -1]\n" + ] + } + ], + "source": [ + "from math import cos, sin\n", + "\n", + "theta = np.deg2rad(45)\n", + "rot_right = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])\n", + "rot_left = np.array([[cos(-theta), -sin(-theta)], [sin(-theta), cos(-theta)]])\n", + "\n", + "vec = np.array([0, -1])\n", + "\n", + "print(vec)\n", + "for i in range(9):\n", + " vec = np.round(np.dot(rot_left, vec), 0).astype(int)\n", + " print(vec)" + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + }, + { + "cell_type": "code", + "execution_count": 5, + "outputs": [ + { + "ename": "KeyboardInterrupt", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m", + "\u001B[0;31mKeyboardInterrupt\u001B[0m Traceback (most recent call last)", + "Input \u001B[0;32mIn [5]\u001B[0m, in \u001B[0;36m\u001B[0;34m()\u001B[0m\n\u001B[1;32m 31\u001B[0m window \u001B[38;5;241m=\u001B[39m MyGame()\n\u001B[1;32m 32\u001B[0m window\u001B[38;5;241m.\u001B[39msetup()\n\u001B[0;32m---> 33\u001B[0m \u001B[43marcade\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrun\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/arcade/window_commands.py:289\u001B[0m, in \u001B[0;36mrun\u001B[0;34m()\u001B[0m\n\u001B[1;32m 286\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01msys\u001B[39;00m\n\u001B[1;32m 287\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m sys\u001B[38;5;241m.\u001B[39mplatform \u001B[38;5;241m!=\u001B[39m \u001B[38;5;124m'\u001B[39m\u001B[38;5;124mwin32\u001B[39m\u001B[38;5;124m'\u001B[39m:\n\u001B[1;32m 288\u001B[0m \u001B[38;5;66;03m# For non windows platforms, just do pyglet run\u001B[39;00m\n\u001B[0;32m--> 289\u001B[0m \u001B[43mpyglet\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mapp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrun\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 290\u001B[0m \u001B[38;5;28;01melse\u001B[39;00m:\n\u001B[1;32m 291\u001B[0m \u001B[38;5;66;03m# Ok, some Windows platforms have a timer resolution > 15 ms. That can\u001B[39;00m\n\u001B[1;32m 292\u001B[0m \u001B[38;5;66;03m# drop our FPS to 32 FPS or so. This reduces resolution so we can keep\u001B[39;00m\n\u001B[1;32m 293\u001B[0m \u001B[38;5;66;03m# FPS up.\u001B[39;00m\n\u001B[1;32m 294\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mcontextlib\u001B[39;00m\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/pyglet/app/__init__.py:107\u001B[0m, in \u001B[0;36mrun\u001B[0;34m(interval)\u001B[0m\n\u001B[1;32m 99\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21mrun\u001B[39m(interval\u001B[38;5;241m=\u001B[39m\u001B[38;5;241m1\u001B[39m\u001B[38;5;241m/\u001B[39m\u001B[38;5;241m60\u001B[39m):\n\u001B[1;32m 100\u001B[0m \u001B[38;5;124;03m\"\"\"Begin processing events, scheduled functions and window updates.\u001B[39;00m\n\u001B[1;32m 101\u001B[0m \n\u001B[1;32m 102\u001B[0m \u001B[38;5;124;03m This is a convenience function, equivalent to::\u001B[39;00m\n\u001B[0;32m (...)\u001B[0m\n\u001B[1;32m 105\u001B[0m \n\u001B[1;32m 106\u001B[0m \u001B[38;5;124;03m \"\"\"\u001B[39;00m\n\u001B[0;32m--> 107\u001B[0m \u001B[43mevent_loop\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrun\u001B[49m\u001B[43m(\u001B[49m\u001B[43minterval\u001B[49m\u001B[43m)\u001B[49m\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/pyglet/app/base.py:185\u001B[0m, in \u001B[0;36mEventLoop.run\u001B[0;34m(self, interval)\u001B[0m\n\u001B[1;32m 183\u001B[0m \u001B[38;5;28;01mwhile\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhas_exit:\n\u001B[1;32m 184\u001B[0m timeout \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39midle()\n\u001B[0;32m--> 185\u001B[0m \u001B[43mplatform_event_loop\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mstep\u001B[49m\u001B[43m(\u001B[49m\u001B[43mtimeout\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 187\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mis_running \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mFalse\u001B[39;00m\n\u001B[1;32m 188\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mdispatch_event(\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mon_exit\u001B[39m\u001B[38;5;124m'\u001B[39m)\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/pyglet/app/cocoa.py:142\u001B[0m, in \u001B[0;36mCocoaEventLoop.step\u001B[0;34m(self, timeout)\u001B[0m\n\u001B[1;32m 138\u001B[0m \u001B[38;5;66;03m# Retrieve the next event (if any). We wait for an event to show up\u001B[39;00m\n\u001B[1;32m 139\u001B[0m \u001B[38;5;66;03m# and then process it, or if timeout_date expires we simply return.\u001B[39;00m\n\u001B[1;32m 140\u001B[0m \u001B[38;5;66;03m# We only process one event per call of step().\u001B[39;00m\n\u001B[1;32m 141\u001B[0m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_is_running\u001B[38;5;241m.\u001B[39mset()\n\u001B[0;32m--> 142\u001B[0m event \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mNSApp\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mnextEventMatchingMask_untilDate_inMode_dequeue_\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m 143\u001B[0m \u001B[43m \u001B[49m\u001B[43mcocoapy\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mNSAnyEventMask\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mtimeout_date\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mcocoapy\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mNSDefaultRunLoopMode\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43;01mTrue\u001B[39;49;00m\u001B[43m)\u001B[49m\n\u001B[1;32m 145\u001B[0m \u001B[38;5;66;03m# Dispatch the event (if any).\u001B[39;00m\n\u001B[1;32m 146\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m event \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/pyglet/libs/darwin/cocoapy/runtime.py:805\u001B[0m, in \u001B[0;36mObjCBoundMethod.__call__\u001B[0;34m(self, *args)\u001B[0m\n\u001B[1;32m 803\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21m__call__\u001B[39m(\u001B[38;5;28mself\u001B[39m, \u001B[38;5;241m*\u001B[39margs):\n\u001B[1;32m 804\u001B[0m \u001B[38;5;124;03m\"\"\"Call the method with the given arguments.\"\"\"\u001B[39;00m\n\u001B[0;32m--> 805\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mmethod\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mobjc_id\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43margs\u001B[49m\u001B[43m)\u001B[49m\n", + "File \u001B[0;32m/opt/homebrew/Caskroom/miniforge/base/envs/evolving/lib/python3.8/site-packages/pyglet/libs/darwin/cocoapy/runtime.py:775\u001B[0m, in \u001B[0;36mObjCMethod.__call__\u001B[0;34m(self, objc_id, *args)\u001B[0m\n\u001B[1;32m 773\u001B[0m f \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mget_callable()\n\u001B[1;32m 774\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[0;32m--> 775\u001B[0m result \u001B[38;5;241m=\u001B[39m \u001B[43mf\u001B[49m\u001B[43m(\u001B[49m\u001B[43mobjc_id\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mselector\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43margs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 776\u001B[0m \u001B[38;5;66;03m# Convert result to python type if it is a instance or class pointer.\u001B[39;00m\n\u001B[1;32m 777\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mrestype \u001B[38;5;241m==\u001B[39m ObjCInstance:\n", + "\u001B[0;31mKeyboardInterrupt\u001B[0m: " + ] + } + ], + "source": [ + "import arcade\n", + "\n", + "SCREEN_WIDTH = 1000\n", + "SCREEN_HEIGHT = 650\n", + "SCREEN_TITLE = \"Platformer\"\n", + "\n", + "\n", + "class MyGame(arcade.Window):\n", + " \"\"\"\n", + " Main application class.\n", + " \"\"\"\n", + "\n", + " def __init__(self):\n", + "\n", + " # Call the parent class and set up the window\n", + " super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n", + "\n", + " arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)\n", + "\n", + " def setup(self):\n", + " \"\"\"Set up the game here. Call this function to restart the game.\"\"\"\n", + " pass\n", + "\n", + " def on_draw(self):\n", + " \"\"\"Render the screen.\"\"\"\n", + "\n", + " self.clear()\n", + " # Code to draw the screen goes here\n", + "\n", + "\n", + "window = MyGame()\n", + "window.setup()\n", + "arcade.run()\n" + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + }, + { + "cell_type": "code", + "execution_count": null, + "outputs": [], + "source": [ + "window.close()\n", + "arcade.exit()" + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + }, + { + "cell_type": "code", + "execution_count": null, + "outputs": [], + "source": [], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/src/world.py b/src/world.py new file mode 100644 index 0000000..d722f2e --- /dev/null +++ b/src/world.py @@ -0,0 +1,62 @@ +import numpy as np +import random + +from src.being import Being +from src.cell import Cell + + +class World: + def __init__(self, w=128, h=128): + self.w = w + self.h = h + self.state = np.empty((w, h), dtype=object) + for i in range(w): + for j in range(h): + self.state[i, j] = Cell(i, j) + + def step(self): + state = np.copy(self.state) + + for i, row in enumerate(self.state): + for j, cell in enumerate(row): + if cell.type != 'BEING': + continue + + cell.content.step() + action = cell.content.choose_action() + + if action == 'MOVE': + # lets see if the desired cell is empty + direction = cell.content.direction + next_loc = [ + max(0, min(self.w - 1, cell.x + direction[0])), + max(0, min(self.h - 1, cell.y + direction[1])) + ] + + if state[next_loc[0], next_loc[1]].type == 'NONE': + # cell is empty, lets move! + state[next_loc[0], next_loc[1]].update('BEING', cell.content) + state[i, j].update('NONE') + + self.state = state + + def spawn(self, number): + for _ in range(number): + x = random.randint(0, self.w - 1) + y = random.randint(0, self.h - 1) + + while self.state[x, y].type != 'NONE': + x = random.randint(0, self.w - 1) + y = random.randint(0, self.h - 1) + # TODO: this could be infinite + + being = Being() + self.state[x, y].update('BEING', being) + + def render(self): + state = np.zeros((self.w, self.h)) + for i, row in enumerate(self.state): + for j, cell in enumerate(row): + state[i, j] = cell.color() + + return state