{ "metadata": { "name": "fun_with_ipythonblocks" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "from ipythonblocks import colors, BlockGrid\n", "import random" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "# Draw rainbows!!!!\n", "rainbow_colors = ['Red', 'Purple', 'Blue', 'Green', 'Yellow', 'Orange']\n", "n_colors = len(rainbow_colors)\n", "grid = BlockGrid(41, 5, block_size=30, lines_on=False)\n", "for i in range(100):\n", " for block in grid:\n", " color_name = rainbow_colors[(block.row + block.col + i) % n_colors]\n", " block.rgb = colors[color_name]\n", " grid.flash()\n", "grid.show()" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "
" ], "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "def inside_grid(ball_position, grid):\n", " return ball_position[0] >= 0 \\\n", " and ball_position[1] >= 0 \\\n", " and ball_position[0] <= grid.shape[0] - 1 \\\n", " and ball_position[1] <= grid.shape[1] - 1\n", "\n", "def move_monster(monster_position, grid):\n", " while True:\n", " move_directions = [(0,1), (1, 0), (-1, 0), (0, -1)] # try changing this!\n", " move = random.choice(move_directions)\n", " next_position = add_position(monster_position, move)\n", " if inside_grid(next_position, grid):\n", " break\n", " return next_position\n", "\n", "def add_position(pos1, pos2):\n", " \"\"\" \n", " Add a position and a move together:\n", " add_position( (2,3), (0,1) ) == (2,4)\n", " \"\"\"\n", " return (pos1[0] + pos2[0], pos1[1] + pos2[1])\n", "\n", "monster_position = (randint(1, grid.shape[0]), randint(1, grid.shape[1]))\n", "grid = BlockGrid(41, 10, block_size=30, lines_on=True)\n", "eaten_positions = []\n", "\n", "# Try changing the colors!\n", "monster_color = colors['DarkOrange']\n", "grid_color = colors['Purple']\n", "eaten_color = colors['White']\n", "\n", "for i in range(100):\n", " # Add the monster position to the list of eaten positions\n", " eaten_positions.append(monster_position)\n", " monster_position = move_monster(monster_position, grid)\n", " for block in grid:\n", " block_coordinates = (block.col, block.row)\n", " if block_coordinates == monster_position:\n", " block.rgb = monster_color\n", " elif block_coordinates in eaten_positions:\n", " block.rgb = eaten_color\n", " else:\n", " block.rgb = grid_color\n", " grid.flash()\n", "grid.show()" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "
" ], "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 3 } ], "metadata": {} } ] }