Skip to content

Instantly share code, notes, and snippets.

@bbkane
Created July 17, 2014 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbkane/8a7408aa4f1acb7a3635 to your computer and use it in GitHub Desktop.
Save bbkane/8a7408aa4f1acb7a3635 to your computer and use it in GitHub Desktop.
2048.py
import console
from random import randint, choice, randrange
class Board:
def __init__(self, xSize=4, ySize=4):
self.xSize=xSize
self.ySize=ySize
self.tiles=[]
for i in range(self.ySize):
self.tiles.append([])
for j in range(self.xSize):
self.tiles[i].append(0)
def __str__(self):
ans=''
for i in range(self.ySize):
for j in range(self.xSize):
ans += ' {:3d}'.format(self.tiles[i][j])
ans += '\n'
return ans
def addRand(self):
a,b= randrange(self.ySize),randrange(self.xSize)
while self.tiles[a][b] != 0:
a,b= randrange(self.ySize),randrange(self.xSize)
self.tiles[a][b]= choice([2,4])
def combine(self, x1, y1, x2, y2):
'''combines two tiles. sum in x2,y2'''
if self.tiles[x2][y2]== self.tiles[x1][y1]:
self.tiles[x2][y2] *= 2
self.tiles[x1][y1]= 0
if self.tiles[x2][y2]== 0:
self.tiles[x2][y2]= self.tiles[x1][y1]
self.tiles[x1][y1]= 0
def canCombine(self, x1, x2, y1, y2):
return self.tiles[x2][y2]== self.tiles[x1][y2] or self.tiles[x2][y2]== 0
def upSlide(self):
'''for now just make it go up'''
for y in range(self.ySize-1):
for x in range(self.xSize):
self.combine(y+1, x, y, x)
print '{} and {}'.format(y+1,y)
print b
def downSlide():
pass
def leftSlide(self):
pass
def rightSlide():
pass
console.clear()
b= Board()
for x in range(b.xSize*b.ySize-2):
b.addRand()
print b
b.upSlide()
print b
#tiles[0 <= row# < yMax][0 <= col# < xMax]
#the format is {<name>:<optional 0><numSpaced><d for decimal base>}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment