"""Classroom Flappy Bird and streaming Crossy Road-style environments. Actual deterministic physics, sampled independent actions, and shared tabular Q-learning. Both are local teaching adaptations, not the commercial binaries. """ import hashlib,json,threading from collections import OrderedDict from pathlib import Path import numpy as np ROOT=Path(__file__).resolve().parents[1] VERSION=3 def hashed_tiles(columns,offset,slots=16384): values=np.asarray(columns,dtype=np.int64) code=np.full(values.shape[0],7919+offset*104729,dtype=np.int64) for j in range(values.shape[1]):code=(code*1009+(values[:,j]+4096)*(101+j*38))%2147483647 return code%slots+offset*slots class Flight: actions=['Coast','Flap'];hold=3;states=8*16384;goal=20;limit=3200;features=8 input_schema=[{'name':name,'unit':unit} for name,unit in [ ('Bird height','px'),('Vertical speed','px/tick'),('Next pipe left','px'),('Next pipe right','px'), ('Next gap top','px'),('Next gap bottom','px'),('Following pipe left','px'),('Following gap top','px'),('Following gap bottom','px')]] def __init__(self,n,seed,difficulty,course_length=20): if course_length is not None and (type(course_length) is not int or not 1<=course_length<=1_000_000):raise ValueError('Choose 1–1,000,000 pipes, or endless.') self.n=n;self.seed=seed;self.difficulty=difficulty;self.tick=0 self.goal=course_length;self.endless=course_length is None self.limit=None if self.endless else max(3200,int((course_length*190+340)/2.7)+400) self.rng=np.random.default_rng(seed);self.gap=155 if difficulty=='easy' else 125 # Preserve the original early courses for matched old/new comparisons. self.centers=self.rng.uniform(110,285,24);self.origins=340+np.arange(24)*190;self.pipe_cache=OrderedDict() self.speed=2.7;self.x=np.full(n,100.);self.y=np.full(n,210.);self.vy=np.zeros(n) self.done=np.zeros(n,bool);self.reason=np.full(n,'flying',object);self.score=np.zeros(n);self.total=np.zeros(n) def passed(self): count=max(0,int(np.ceil((self.speed*self.tick-304)/190))) return count if self.endless else min(count,self.goal) def geometry(self,index): index=max(0,int(index)) if not self.endless:index=min(index,self.goal-1) if index<24:return float(self.origins[index]-self.speed*self.tick),float(self.centers[index]) if index not in self.pipe_cache: self.pipe_cache[index]=float(np.random.default_rng(np.random.SeedSequence([self.seed,index,717])).uniform(110,285)) if len(self.pipe_cache)>256:self.pipe_cache.popitem(last=False) return float(340+index*190-self.speed*self.tick),self.pipe_cache[index] def pipe(self):return self.geometry(self.passed()) def observe(self): x,c=self.pipe();x2,c2=self.geometry(self.passed()+1) constant=lambda value:np.full(self.n,value) return np.column_stack([self.y,self.vy,constant(x),constant(x+52),constant(c-self.gap/2),constant(c+self.gap/2),constant(x2),constant(c2-self.gap/2),constant(c2+self.gap/2)]) def keys(self): obs=self.observe();center=(obs[:,4]+obs[:,5])/2;center2=(obs[:,7]+obs[:,8])/2 following_offset=190 if self.endless or self.passed()+1380)) for index in range(max(0,self.passed()-1),self.passed()+2): if not self.endless and index>=self.goal:continue x,c=self.geometry(index) if x<112 and x+52>88:crashed|=active&((self.y-10c+self.gap/2)) score=self.passed();passed=np.maximum(0,score-self.score);reward[active]+=passed[active]*5;self.score[active]=score finished=np.zeros(self.n,bool) if self.endless else active&~crashed&(self.score>=self.goal) reward[crashed]-=12;reward[finished]+=20 self.reason[crashed]='pipe or boundary';self.reason[finished]='goal';self.done|=crashed|finished if self.limit is not None: timed=active&~self.done&(self.tick>=self.limit);self.reason[timed]='time limit';self.done|=timed _,next_center=self.pipe();next_phi=-np.abs(self.y-next_center)/100;next_phi[self.done]=0 reward[active]+=.99*next_phi[active]-old_phi[active] self.total+=reward;return reward,active def frame(self): alive=np.flatnonzero(~self.done);leader=int(alive[0]) if len(alive) else int(np.argmax(self.score)) pipes=[] for i in range(max(0,self.passed()-1),self.passed()+6): if not self.endless and i>=self.goal:continue x,c=self.geometry(i) if -601 and (self.endless or number2 and (self.endless or number0,*blocked],dtype=float) self.row_cache[number]=row if len(self.row_cache)>2048:self.row_cache.popitem(last=False) return row def _sample(self,rows): rows=np.asarray(rows,dtype=np.int64) rows=np.maximum(rows,0) if self.endless else np.clip(rows,0,self.goal) return np.stack([self._row(r)['_sensors'] for r in rows.ravel()]).reshape((*rows.shape,15)) def _leader(self): alive=np.flatnonzero(~self.done) return int(alive[np.argmax(self.score[alive])]) if len(alive) else int(np.argmax(self.score)) def _window(self): start=max(0,int(self.y[self._leader()])-12)//8*8 end=start+39 if not self.endless:end=min(end,self.goal) return start,end @property def rows(self): start,end=self._window() return [{k:v for k,v in self._row(i).items() if not k.startswith('_')} for i in range(start,end+1)] @property def trees(self): start,end=self._window() return [(x,i) for i in range(start,end+1) for x in self._row(i)['_trees']] def cars(self,tick=None): tick=self.tick if tick is None else tick;result=[] for row in self.rows: if row['type']!='road':continue for j in range(3): x=(row['phase']+j*row['spacing']+row['speed']*tick)%(row['spacing']*3)-row['spacing']*1.5 result.append({'id':row['row']*3+j,'row':row['row'],'x':float(x),'length':row['length'],'direction':1 if row['speed']>0 else -1}) return result def traffic_hit(self,x,y,tick,margin=.28): hit=np.zeros(np.shape(x),bool) for row in [np.floor(y).astype(int),np.ceil(y).astype(int)]: sensors=self._sample(row);spacing=sensors[...,3] origin=sensors[...,2]+sensors[...,1]*tick-1.5*spacing distance=np.abs((x-origin+spacing/2)%spacing-spacing/2) hit|=sensors[...,0].astype(bool)&(np.abs(y-row)<.65)&(distance4)|(y<0) if not self.endless:result|=y>self.goal sensors=self._sample(np.rint(y).astype(int));col=np.clip(np.rint(x)+4,0,8).astype(int) return result|np.take_along_axis(sensors[...,6:],col[...,None],axis=-1)[...,0].astype(bool) def risk(self,x,y,tick):return self._blocked(x,y)|self.traffic_hit(x,y,tick,.32) def observe(self): x=np.rint(self.x);y=np.rint(self.y);fields=[x] for tick in [self.tick,self.tick+self.hold]: for dx,dy in [(0,0),(0,1),(-1,0),(1,0),(0,-1)]:fields.append(self.risk(x+dx,y+dy,tick).astype(float)) for ahead in [0,1,2]: row=self._sample(y.astype(int)+ahead);road=row[:,0].astype(bool) origin=row[:,2]+row[:,1]*self.tick-1.5*row[:,3] left=origin+np.floor((x-origin)/row[:,3])*row[:,3];right=left+row[:,3] fields.extend([road.astype(float),np.where(road,left,0),np.where(road,right,0),np.where(road,row[:,1],0),np.where(road,row[:,4],0)]) return np.column_stack(fields) def keys(self): obs=self.observe();bits=1<0).astype(int)) values=[] for j in [11,16,21]: road=obs[:,j];phase=np.where(road,(obs[:,0]-obs[:,j+1])/np.maximum(1,obs[:,j+2]-obs[:,j+1]),0) values.extend([road,phase*8,obs[:,j+3]/.025,obs[:,j+4]/.4]) values.append(obs[:,0]);values=np.column_stack(values) return np.column_stack([base]+[self.base_states+hashed_tiles(np.floor(values+tile/4).astype(int),tile) for tile in range(4)]) def step(self,actions,decision): active=~self.done;reward=np.zeros(self.n);reward[active]=-.008 if decision: self.start_x=self.x.copy();self.start_y=self.y.copy() dx=np.array([0,0,-1,1,0])[actions];dy=np.array([0,1,0,0,-1])[actions] tx=self.x+dx;ty=self.y+dy;blocked=self._blocked(tx,ty) reward[active&blocked]-=.2;tx[blocked]=self.x[blocked];ty[blocked]=self.y[blocked] self.target_x=tx;self.target_y=ty phase=(self.tick%self.hold+1)/self.hold self.x[active]=self.start_x[active]+(self.target_x[active]-self.start_x[active])*phase self.y[active]=self.start_y[active]+(self.target_y[active]-self.start_y[active])*phase self.tick+=1;hit=active&self.traffic_hit(self.x,self.y,self.tick) reward[hit]-=10;self.reason[hit]='hit by traffic';self.done|=hit if phase==1: reached=np.maximum(self.score,np.floor(self.y+.001));gain=reached-self.score reward[active]+=gain[active]*2;self.stale[active]=np.where(gain[active]>0,0,self.stale[active]+self.hold);self.score[active]=reached[active] if not self.endless: goal=active&~self.done&(self.y>=self.goal);reward[goal]+=30;self.reason[goal]='goal';self.done|=goal timed=active&~self.done&(self.stale>=240) if self.limit is not None:timed|=active&~self.done&(self.tick>=self.limit) reward[timed]-=4;self.reason[timed]='waited too long';self.done|=timed self.total+=reward;return reward,active def frame(self): phase=(self.tick%self.hold)/self.hold;start,end=self._window() return {'tick':self.tick,'seed':self.seed,'leader':self._leader(),'cars':self.cars(),'trees':self.trees,'rows':self.rows,'goal':self.goal, 'endless':self.endless,'window_start':start,'window_end':end,'input_values':self.observe()[self._leader()].tolist(), 'runners':[{'id':i,'x':float(self.x[i]),'y':float(self.y[i]),'hop':float(np.sin(phase*np.pi)*.35) if not self.done[i] and (self.target_y[i]!=self.start_y[i] or self.target_x[i]!=self.start_x[i]) else 0, 'done':bool(self.done[i]),'score':int(self.score[i]),'reason':self.reason[i]} for i in range(self.n)]} ENVIRONMENTS={'flappy':Flight,'crossy':Crossing} class ArcadeRL: def __init__(self,game,owner='classroom',population=32,difficulty='easy',seed=7,course_length='default'): if game not in ENVIRONMENTS:raise ValueError('Choose Flappy Bird or Crossy Road.') self.game=game;self.owner=owner;self.lock=threading.RLock();self.env_type=ENVIRONMENTS[game] directory=ROOT/'data/arcade_learning';directory.mkdir(exist_ok=True) self.checkpoint=directory/(game+'-'+hashlib.sha256(owner.encode()).hexdigest()[:24]+'.npz') self.reset(population,difficulty,seed,course_length) def reset(self,population=32,difficulty='easy',seed=7,course_length='default'): if not isinstance(population,int) or not 1<=population<=128:raise ValueError('Choose 1–128 agents.') if difficulty not in ['easy','standard']:raise ValueError('Choose easy or standard difficulty.') if course_length=='default':course_length=20 if self.game=='flappy' else 24 if course_length is not None and (type(course_length) is not int or not 1<=course_length<=1_000_000):raise ValueError('Choose a whole-number course length from 1 to 1,000,000, or endless.') with self.lock: self.population=population;self.difficulty=difficulty;self.seed=int(seed);self.rng=np.random.default_rng(seed) self.course_length=course_length self.q=np.zeros((self.env_type.states,len(self.env_type.actions)),np.float32);self.visited=np.zeros(self.env_type.states,bool) self.experiences=self.updates=self.transitions=self.wins=self.episodes=0;self.round=0;self.history=[];self.exploration=.18 if self.game=='flappy' else .25 self.auto_exploration=self.game=='flappy';self.replay_size=0;self.replay_cursor=0;self.replay_capacity=12000;self.replay_updates=0 count=self.env_type.features self.replay_keys=np.zeros((self.replay_capacity,count),np.int64);self.replay_next=np.zeros_like(self.replay_keys) self.replay_actions=np.zeros(self.replay_capacity,np.int64);self.replay_rewards=np.zeros(self.replay_capacity);self.replay_discounts=np.zeros(self.replay_capacity) self._fresh();self.manual=None;self.pending=0 return self.state() def _environment(self,population,seed): if self.game=='crossy':return Crossing(population,seed,self.difficulty,self.course_length) return Flight(population,seed,self.difficulty,self.course_length) def _fresh(self): if self.round: self.history.append({'round':self.round,'mean_score':float(self.env.score.mean()),'best_score':float(self.env.score.max()),'wins':int(np.count_nonzero(self.env.reason=='goal'))}) self.history=self.history[-160:] self.env=self._environment(self.population,self.seed+self.round*9973);self.round+=1 self.actions=np.zeros(self.population,np.int64);self.start_keys=np.zeros((self.population,self.env_type.features),np.int64);self.accum=np.zeros(self.population);self.elapsed=np.zeros(self.population,int) @property def effective_exploration(self): floor=min(.025,self.exploration) return floor+(self.exploration-floor)*np.exp(-self.experiences/35000) if self.auto_exploration else self.exploration def feature_weights(self):return np.ones(self.env_type.features) if self.game=='flappy' else np.array([1.,.1,.1,.1,.1]) def values(self,keys):return (self.q[keys]*self.feature_weights()[None,:,None]).sum(axis=1) def _fit(self,keys,actions,expected,rate=.22): error=expected-self.values(keys)[np.arange(len(keys)),actions] pairs=(keys*len(self.env_type.actions)+actions[:,None]).ravel();unique,inverse=np.unique(pairs,return_inverse=True) mean=np.bincount(inverse,weights=np.repeat(error,keys.shape[1]))/np.bincount(inverse) weights=self.feature_weights();learning_rate=rate/np.sum(weights**2) # Tile tables occupy disjoint ranges, so each pair retains its feature weight. feature=np.tile(np.arange(keys.shape[1]),len(keys));weights_by_pair=np.bincount(inverse,weights=weights[feature])/np.bincount(inverse) self.q.flat[unique]+=learning_rate*weights_by_pair*mean self.updates+=len(unique);self.visited[keys]=True def _update(self,mask): ids=np.flatnonzero(mask) if not len(ids):return current=self.start_keys[ids];act=self.actions[ids];next_keys=self.env.keys()[ids] discount=np.power(.99,self.elapsed[ids])*(~self.env.done[ids]) expected=self.accum[ids]+discount*np.max(self.values(next_keys),axis=1) self._fit(current,act,expected,.22 if self.game=='flappy' else .1872);self.transitions+=len(ids) slots=(self.replay_cursor+np.arange(len(ids)))%self.replay_capacity self.replay_keys[slots]=current;self.replay_next[slots]=next_keys;self.replay_actions[slots]=act self.replay_rewards[slots]=self.accum[ids];self.replay_discounts[slots]=discount self.replay_cursor=(self.replay_cursor+len(ids))%self.replay_capacity;self.replay_size=min(self.replay_capacity,self.replay_size+len(ids)) if self.game=='flappy' and self.replay_size>=64: for _ in range(2): sample=self.rng.integers(self.replay_size,size=min(128,self.replay_size)) target=self.replay_rewards[sample]+self.replay_discounts[sample]*self.values(self.replay_next[sample]).max(axis=1) self._fit(self.replay_keys[sample],self.replay_actions[sample],target,.12);self.replay_updates+=1 def train(self,ticks): with self.lock: frames=[];every=max(1,int(ticks)//24) for t in range(int(ticks)): if self.env.done.all():self._fresh() decision=self.env.tick%self.env_type.hold==0 if decision: self.start_keys=self.env.keys();self.actions=np.argmax(self.values(self.start_keys),axis=1) random=self.rng.random(self.population)