Last active
February 10, 2018 04:57
-
-
Save ncfavier/21560fc9169229553cfc to your computer and use it in GitHub Desktop.
Text-based 2048 clone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from random import randint | |
size = 4 | |
score = 0 | |
grid = [[0 for i in range(size)] for i in range(size)] | |
def display(grid): | |
print() | |
for i in range(size): | |
for j in range(size): | |
print(str(grid[i][j]).center(4), end=' ') | |
print('\n') | |
def isFull(grid): | |
for i in range(size): | |
for j in range(size): | |
if grid[i][j] == 0: | |
return False | |
return True | |
def spawnNumber(grid): | |
if isFull(grid): | |
return | |
i, j = -1, -1 | |
while i < 0 or grid[i][j] != 0: | |
i = randint(0, size-1) | |
j = randint(0, size-1) | |
grid[i][j] = 2 if randint(1, 10) > 1 else 4 | |
def rotate(grid, direction): | |
if direction == -1: | |
return | |
new = [[0 for i in range(size)] for i in range(size)] | |
for i in range(size): | |
for j in range(size): | |
if direction == +1: | |
new[i][j] = grid[size-i-1][size-j-1] | |
elif direction == -1j: | |
new[i][j] = grid[size-j-1][i] | |
elif direction == +1j: | |
new[i][j] = grid[j][size-i-1] | |
grid[:] = new | |
def move(grid, direction): | |
global score | |
if direction == 0: | |
return | |
original = grid[:] | |
rotate(grid, direction) | |
for i in range(size): | |
grid[i] = [j for j in grid[i] if j != 0] | |
for j in range(size): | |
if j >= len(grid[i]) - 1: | |
break | |
if grid[i][j] == grid[i][j+1]: | |
grid[i][j] += grid[i].pop(j+1) | |
score += grid[i][j] | |
grid[i] += [0]*(size - len(grid[i])) | |
rotate(grid, complex(direction).conjugate()) | |
if grid != original: | |
spawnNumber(grid) | |
try: | |
print("<wasd> + [Enter]") | |
spawnNumber(grid) | |
display(grid) | |
while not isFull(grid): | |
prompt = 'Score: %d > ' % score | |
direction = {'z': +1j, 'q': -1, 's': -1j, 'd': +1}.get(input(prompt).lower(), 0) | |
move(grid, direction) | |
display(grid) | |
except KeyboardInterrupt: | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment