Files
g2048/g2048.py
T
2020-04-24 12:07:55 +03:00

124 lines
3.1 KiB
Python
Executable File

#! /usr/bin/python3
import random, copy
def game_logic(l):
oldHash = hash(tuple(l))
line_state = True
moved=0
ls=1
while line_state:
for i in range(board_line-1):
if l[i+1] == None:
pass
elif l[i+1] != None and l[i] == None:
mi=l.pop(i+1)
l.pop(i)
l.insert(i,mi)
l.insert(i+1,None)
elif l[i] == l[i+1]:
mi=l.pop(i)
l.insert(i,int(mi)*2)
mi=l.pop(i+1)
l.insert(i+1,None)
oldHash = hash(tuple(l))
elif l[i] > l[+1]:
pass
newHash = hash(tuple(l))
#TODO: don't move when there is no chage
if oldHash == newHash and ls==1:
moved=moved+1
print('Moved in line',moved)
ls=i+1
# print (oldHash,newHash)
if oldHash == newHash:
line_state = False
else:
oldHash = newHash
# return l,moved
return l
def movement():
m = input('\nMove the numbers: ')
# board_reset = board
if m == 'h':
for i in range(0,board_size,board_line):
board[i:i+board_line]=game_logic(board[i:i+board_line])
elif m == 'j':
for i in range(board_line):
rl = board[i::board_line]
print(rl)
print(rl[::-1])
board[i::board_line]=game_logic(rl[::-1])[::-1]
elif m == 'k':
for i in range(board_line):
rl = board[i::board_line]
board[i::board_line]=game_logic(rl)
elif m == 'l':
for i in range(0,board_size,board_line):
rl = board[i:i+board_line]
print(rl)
print(rl[::-1])
board[i:i+board_line]=game_logic(rl[::-1])[::-1]
# elif m == 'u':
# board=board_reset
# print(board)
# raise ValueError('Can not move this way')
else:
raise ValueError('Can not move this way')
# try:
# direction in ['h','j','k','l']
# print(direction)
# except:
# print('wtf')
def print_board():
for i in range(0,board_size,board_line):
print(board[i:i+board_line])
# class Game():
# def init():
game_state = True
board = []
board_line=3
board_size=board_line**2
for i in range(board_size):
board.insert(i,None)
# def add_number():
indices = [i for i, x in enumerate(board) if x == None]
p = random.choice(indices)
board[p] = random.choices([2,4],weights=[80,20])[0]
board_reset=copy.deepcopy(board)
# def run():
while game_state:
print('')
print('new choice')
print_board()
try:
# print('\nnew choice')
movement()
except ValueError:
#board=copy.deepcopy(board_reset)
# continue
pass
# print('coumbagia')
try:
indices = [i for i, x in enumerate(board) if x == None]
p = random.choice(indices)
board[p] = random.choices([2,2],weights=[80,20])[0]
board_reset=copy.deepcopy(board)
print('New number at position',p)
except IndexError:
# catch game over here
game_state = False
print('Game Over')