Open in CoCalc
In [1]:
#12.7

from pylab import *

def initialize():
global x, result
x = 0.4
result = [x]

def observe():
global x, result
result.append(x)

def f(x):
return 56*x**4*(1-x)**5 + 84*x**3*(1-x)**6 #difference equation

def update():
global x, result
x = f(x)

initialize()
for t in xrange(30):
update()
observe()

### drawing diagonal line
xmin, xmax = 0, 1
plot([xmin, xmax], [xmin, xmax], 'k')

### drawing curve
rng = arange(xmin, xmax, (xmax - xmin) / 100.)
plot(rng, map(f, rng), 'k')

### drawing trajectory
horizontal = [result[0]]
vertical = [result[0]]
for x in result[1:]:
horizontal.append(vertical[-1])
vertical.append(x)
horizontal.append(x)
vertical.append(x)
plot(horizontal, vertical, 'b')

show()

In [4]:
#game of life simulation

#conducted on local machine
#pasted online for reference
import matplotlib
matplotlib.use('TkAgg')
from pylab import *

n = 100 # size of space: n x n
p = 0.1 # starting state composition

def initialize():
global config, nextconfig
config = zeros([n, n])
for x in range(n):
for y in range(n):
config[x, y] = 1 if random() < p else 0
nextconfig = zeros([n, n])

def observe():
global config, nextconfig
cla()
imshow(config, vmin = 0, vmax = 1, cmap = cm.binary)

def update():
global config, nextconfig
for x in range(n):
for y in range(n):
count = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
count += config[(x + dx) % n, (y + dy) % n]
if config[x,y] == 0:
nextconfig[x,y] = 1 if count == 3 else 0
else:
nextconfig[x,y] = 1 if count == 3 or count == 2 else 0
config, nextconfig = nextconfig, config

import pycxsimulator
pycxsimulator.GUI().start(func=[initialize, observe, update])

In [3]:
#conducted on local machine
#pasted online for reference

#11.8

# Simple CA simulator in Python
#
# *** Hosts & Pathogens ***
#
# [email protected]

import matplotlib
matplotlib.use('TkAgg')

import pylab as PL
import random as RD
import scipy as SP

RD.seed()

width = 50
height = 50
initProb = 0.01
infectionRate = 0.85
regrowthRate = 0.15

def init():
global time, config, nextConfig, density

time = 0

config = SP.zeros([height, width])
for x in xrange(width):
for y in xrange(height):
if RD.random() < initProb:
state = 2
else:
state = 1
config[y, x] = state

nextConfig = SP.zeros([height, width])
density = [config.ravel().mean()]

def draw():
global density
PL.cla()

# Show current state on left subplot.
PL.subplot(1, 2, 1)
PL.pcolor(config, vmin = 0, vmax = 2, cmap = PL.cm.jet)
PL.axis('image')
PL.title('t = ' + str(time))

# Show density right subplot.
PL.subplot(1, 2, 2)
PL.plot(density)
PL.ylim(0, 1)

def step():
global time, config, nextConfig, density

time += 1

for x in xrange(width):
for y in xrange(height):
state = config[y, x]
if state == 0:
for dx in xrange(-1, 2):
for dy in xrange(-1, 2):
if config[(y+dy)%height, (x+dx)%width] == 1:
if RD.random() < regrowthRate:
state = 1
elif state == 1:
for dx in xrange(-1, 2):
for dy in xrange(-1, 2):
if config[(y+dy)%height, (x+dx)%width] == 2:
if RD.random() < infectionRate:
state = 2
else:
state = 0

nextConfig[y, x] = state

config, nextConfig = nextConfig, config
density.append(config.ravel().mean())

import pycxsimulator
pycxsimulator.GUI().start(func=[init,draw,step])


In [1]:
try:
import Tkinter as tk
except:
import tkinter as tk
import tkMessageBox
import random
import time

LARGE_FONT = ("Verdana", 16)

class DuelGame(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)

container.pack(side="top", fill="both", expand=True)

container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)

self.frames = {}

for F in (StartPage, Game):

frame = F(container, self)

self.frames[F] = frame

frame.grid(row=0, column=0, sticky="nsew")

self.show_frame(StartPage)

def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()

class StartPage(tk.Frame):

def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Duel Game", font=LARGE_FONT)

start_button = tk.Button(self, text="Start",
command=lambda:controller.show_frame(Game))
start_button.pack()
exit_button = tk.Button(self, text="Exit", command=self.exit)
exit_button.pack()

def exit(self):
self.quit()

class Game(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)

self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)

label = tk.Label(self, text="Teh ReAl Du3l G4m3", font=LARGE_FONT)
label.grid(row=0, column=0) #suboptimal, should use grid

yscrollbar = tk.Scrollbar(self)
yscrollbar.grid(row=1, column=1, sticky='ns')

self.text_box = tk.Text(self, wrap=None, bd=0,
yscrollcommand=yscrollbar.set)

self.text_box.grid(row=1, column=0, sticky='nsew')

yscrollbar.config(command=self.text_box.yview)

self.step_button = tk.Button(self, text="Step", command=self.step)
self.step_button.grid(row=2,column=0,sticky='nsew')
self.shoot_button = tk.Button(self, text="Shoot", command=self.shoot)
self.shoot_button.grid(row=3,column=0,sticky='nsew')
self.reset_button = tk.Button(self, text="Reset", command=self.reset)
self.reset_button.grid(row=4,column=0,sticky='nsew')
self.end_button = tk.Button(self, text="I'm bored...",
command=lambda:controller.show_frame(StartPage))
self.end_button.grid(row=5,column=0,sticky='nsew')

self.pack()

self.d = 20
self.n = self.d
self.bullet_cap = 3
self.turn = 1

def turn_det(self):
if self.turn:
self.text_box.insert("end", "Player 1: ", "bold")
else:
self.text_box.insert("end", "Player 2: ", "bold")

def step(self):
turn_det()

if self.d > 0:
self.d -= 1
else:
self.text_box.insert("end", "Invalid move! Try again.\n")
self.text_box.insert("end", "You are now " + str(self.d) + " steps away.\n")
self.text_box.see("end")

def shoot(self, p=1):
turn_det()

p=lambda n, d: (.9/n)*(n-d)+.1
if random.random() < p(self.n, self.d):
self.text_box.insert("end", "Shot Fired! Gg.\n")
self.end_game()
else:
self.text_box.insert("end", "Shot fired and missed :(\n")
self.text_box.see("end")

def reset(self):
self.text_box.delete("1.0", "end")
self.step_button['state'] = 'normal'
self.shoot_button['state'] = 'normal'
self.d = 20
self.n = self.d

def end_game(self):
self.step_button['state'] = 'disabled'
self.shoot_button['state'] = 'disabled'
text = tkMessageBox.showinfo("Duel Game", "Game Ends!")
if text:
self.reset()
#print game history

app = DuelGame()
app.mainloop()

--------------------------------------------------------------------------- TclError Traceback (most recent call last) <ipython-input-1-4d4f2ae56fb2> in <module>() 130 #print game history 131 --> 132 app = DuelGame() 133 app.mainloop() <ipython-input-1-4d4f2ae56fb2> in __init__(self, *args, **kwargs) 11 class DuelGame(tk.Tk): 12 def __init__(self, *args, **kwargs): ---> 13 tk.Tk.__init__(self, *args, **kwargs) 14 container = tk.Frame(self) 15 /ext/sage/sage-8.1/local/lib/python2.7/lib-tk/Tkinter.pyc in __init__(self, screenName, baseName, className, useTk, sync, use) 1817 baseName = baseName + ext 1818 interactive = 0 -> 1819 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) 1820 if useTk: 1821 self._loadtk() TclError: no display name and no \$DISPLAY environment variable 
In [ ]: