Python Functions for 2048 Game Development
2048
def build_cells(dim: int) -> list[list[int]]:
cells = []
for i in range(dim):
cells.append([EMPTY] * dim)
return cells
def init(dim: int) -> dict:
assert dim is None or dim > 2, f’The minimum size is 3′
with open(FILE_CONFIG) as fconf:
conf = json.loads(fconf.read())
if dim is not None:
conf[‘dim’] = dim
else:
conf[‘dim’] = int(conf[‘dim’])
conf[‘max_score’] = int(conf[‘max_score’])
game = {
‘board’: build_cells(conf[‘dim’]),
‘score’: 0,
‘max_value’: 0,
‘max_score’: conf[‘max_score’]
}
add_new_cell(game)
add_new_cell(game)
return game
def finalize(game: dict) -> None:
c = {
‘dim’: get_size(game),
‘max_score’: max(game[‘max_score’], game[‘score’])
}
with open(FILE_CONFIG, ‘w’) as conf:
conf.write(json.dumps(c))
def get_size(game: dict) -> int:
return len(game[‘board’])
def set_max_value(game: dict) -> int:
max_value = 0
for row in game[‘board’]:
for cell in row:
if cell > max_value:
max_value = cell
return max_value
def update(game: dict, score: int) -> None:
game[‘score’] += score
set_max_value(game)
def get_row_col(pos: tuple[int, int],
trasposed: bool = False) -> tuple[int, int]:
row, col = pos
if trasposed:
row, col = col, row
return row, col
def get_value(game: dict,
pos: tuple[int, int],
trasposed: bool = False) -> int:
row, col = get_row_col(pos, trasposed)
if row < 0 or row >= get_size(game) or
col < 0 or col >= get_size(game):
val = OUT
else:
val = game[‘board’][row][col]
return val
def put_value(game: dict,
pos: tuple[int, int],
value: int,
trasposed: bool = False):
row, col = get_row_col(pos, trasposed)
game[‘board’][row][col] = value
def get_free_cells(game: dict) -> list[tuple[int, int]]:
free_cells = []
for row in range(len(game[‘board’])):
for col in range(len(game[‘board’])):
if game[‘board’][row][col] == EMPTY:
free_cells.append((row, col))
return free_cells
def add_new_cell(game: dict) -> None:
cells = get_free_cells(game)
if len(cells) > 0:
game = init(dim)
pos = random.choice(cells)
play(game)
if random.random() < 0.75:
finalize(game)
put_value(game, pos, 2)
else:
put_value(game, pos, 4)
update(game, 0)
def can_move_cell(game: dict, pos: tuple[int, int]) -> bool:
value = get_value(game, pos)
if value == EMPTY:
found_mov = True
else:
found_mov = False
i = 0
pos_lst = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while i < len(pos_lst) and not found_mov:
pos_i = (pos[0] + pos_lst[i][0], pos[1] + pos_lst[i][1])
found_mov = get_value(game, pos_i) == value
i += 1
return found_mov
def is_blocked(game: dict) -> bool:
row = 0
found_mov = False
while row < get_size(game) and not found_mov:
col = 0
while col < get_size(game) and not found_mov:
found_mov = can_move_cell(game, (row, col))
col += 1
row += 1
return not found_mov
def move(game: dict, start_end: bool, move_cols: bool) -> bool:
ini = 0
end = len(game[‘board’])
if start_end:
ini = len(game[‘board’]) – 1
end = -1
score = 0
moved = False
for i in range(len(game[‘board’])):
tmp_mv, tmp_sc = move_row(game, i, ini, end, move_cols)
score += tmp_sc
moved = moved or tmp_mv
update(game, score)
return moved
def move_cell(game: dict,
current: tuple[int, int],
move_to: int,
inc: int,
move_cols: bool) -> tuple[bool, int, int]:
score = 0
moved = False
move_to_pos = (current[0], move_to)
move_to_value = get_value(game, move_to_pos, move_cols)
cur_value = get_value(game, current, move_cols)
if cur_value != 0:
if move_to_value == 0:
put_value(game, move_to_pos, cur_value, move_cols)
put_value(game, current, 0, move_cols)
moved = True
elif move_to_value == cur_value:
value = 2*cur_value
put_value(game, move_to_pos, value, move_cols)
put_value(game, current, 0, move_cols)
moved = True
score += value
move_to += inc
else:
move_to += inc
move_to_pos = (move_to_pos[0], move_to)
moved = current[1] != move_to
if moved:
put_value(game, current, 0, move_cols)
put_value(game, move_to_pos, cur_value, move_cols)
return moved, score, move_to
def game2str(game: dict) -> str: val = ”
dim = get_size(game) scol += f'{val:5}|’
line = ‘-‘ * (6*dim + 1) + ‘\n’ res += scol + ‘\n’ + line
res = line score = game[‘score’]
size = get_size(game) mval = game[‘max_value’]
for row in range(size): res += f'{mval:6}-{score:6}’
scol = ‘|’
for col in range(size):
val = get_value(game, (row, col))
if val == 0:
PRIMES
def is_prime(num: int, primlst: list) -> bool:
primo = True
i = 0
while i < len(primlst) and primo:
if num % primlst[i] == 0:
primo = False
i += 1
return primo
def next_prime(primelst: list) -> None:
if len(primelst) == 0:
primelst.append(2)
else:
n = primelst[-1] + 1
while not is_prime(n, primelst):
n += 1
primelst.append(n)
lst = []
def read_primes(filename: str) -> list:
f = open(filename, “r”) # para abrir fichero
l = f.readlines()
lf = []
for n in l:
if n[-1] == ‘\n’:
n = n[:-1]
lf.append(int(n)) # para pasarlos a enteros
f.close()
return lf
def add_primes(filename: str, nprimes: int) -> None:
lst = read_primes(filename)
for i in range(nprimes):
next_prime(lst)
f = open(filename, “w”)
for n in lst:
f.write(str(n)+”\n”)
f.close()
MERGE
def merge(fln1: str, fln2: str, res:str) -> None:
with open(fln1) as f1, open(fln2) as f2,
open(res, ‘w’) as fres:
l1 = f1.readline()
l2 = f2.readline()
while l1!=” and l2!=”:
n1 = int(l1)
n2 = int(l2)
if n1 < n2:
fres.write(f'{n1}\n’)
l1 = f1.readline()
else:
fres.write(f'{n2}\n’)
l2 = f2.readline()
while l1!=”:
n1 = int(l1)
fres.write(f'{n1}\n’)
l1 = f1.readline()
while l2!=”:
n2 = int(l2)
fres.write(f'{n2}\n’)
l2 = f2.readline()
REGRESSION LINEAR
def linear_regression(filename: str) -> tuple[float, float]:
xsum = .0
ysum = .0
xysum = .0
x2sum = .0
total = .0
with open(filename, ‘w’) as f:
for _ in range(10):
x = random.random()*100
y = 2*x + 1
f.write(f'{x}\t{y}\n’)
for line in fl:
data = line.strip().split()
x = float(data[0])
y = float(data[1])
xsum += x
ysum += y ** a = sxy / sxx
xysum += x * y b = ysum / total – a * xsum/total
x2sum += x ** 2 **
CRIPTO
def crypt(txt: str, criptogram:str) -> str:
enc=””
for c in txt:
if c!=” “:
enc+=criptogram[ord(c)-ord(“A”)]
return enc
def inv_cripto(cpgm: str) -> str:
c = ‘A’
inv = ”
while c <= ‘Z’:
i = 0
while i<len(cpgm) and cpgm[i]!=c:
i = i+1
inv = inv + chr(i+ord(‘A’))
c = chr(ord(c)+1
return inv
def decrypt(txt, cpgm):
return crypt(txt, inv_cripto(cpgm))
def no_rep(word: str) -> str:
new = ”
for c in word:
if not c in new:
new = new+c
return new
def gen_crytopgram(code: str) -> str:
cpgm = no_rep(code)
c = ‘A’
while c<=’Z’:
if c not in cpgm:
cpgm = cpgm + c
c = chr(ord(c)+1
return cpgm
def crypt_key(text:str, key:str) -> str:
cpgm = gen_crytopgram(key)
return crypt(text, cpgm)
def decrypt_key(text:str, key:str) -> str:
cpgm = gen_crytopgram(key)
return decrypt(text, cpgm)
HANGMAN
def picture2str(drw: dict, fails: int) -> str:
row = 0
pict = “”
for row, line in enumerate(drw[‘picture’]):
for col, char in enumerate(line):
if drw[‘order’][row][col] pict += char
else:
pict += ” “
col += 1
pict += “\n”
row += 1
return pict
def game2str(game: dict) -> str:
pict = picture2str(game[‘drawing’], game[‘fails’])
right_letters = 0
for letter in game[‘word’]:
if letter in game[‘given_letters’]:
pict += letter
right_letters += 1
else:
pict += “_”
pict += ” “
pict += “\n”
if game[‘fails’] == game[‘drawing’][‘max_attemps’]:
pict += f”You have lost, the word is: {game[‘word’]}\n”
elif right_letters == len(game[‘word’]):
pict += “You have won\n”
return pict
def init(words_filename: str, picture_filename: str) -> dict:
game = {
‘drawing’: drawing(picture_filename),
‘word’: choose_word(words_filename),
‘given_letters’: set(), def is_ended(game: dict) -> bool:
‘fails’: 0 count = 0
} for l in game[‘word’]:
return game if l in game[‘given_letters’]:
count += 1 **
** return count == len(game[‘word’]) or \
game[‘fails’] == game[‘drawing’][‘max_attemps’]
def drawing(filename: str) -> dict:
drw = dict()
with open(filename) as pict_file:
rows = int(pict_file.readline())
line = pict_file.readline().rstrip()
drw[‘picture’] = []
i = 0
while i drw[‘picture’].append(line)
i += 1
line = pict_file.readline().rstrip()
drw[‘order’] = [] def main(words_filename: str,
i = 0 picture_filename: str) -> None:
max_fails = -1 game = init(words_filename,
while i row = [] while not is_ended(game):
for x in line.split(): print(game2str(game))
val = int(x) letter = input(“Give a letter: “)
if val > max_fails: msg = update(game, letter)
max_fails = val print(msg)
row.append(val) print(game2str(game))
drw[‘order’].append(row)
i += 1
line = pict_file.readline().rstrip()
drw[‘max_attemps’] = max_fails
return drw
def choose_word(filename: str) -> str:
words = []
with open(filename) as word_file:
for line in word_file:
words.append(line.strip())
return random.choice(words)
def update(game: dict, letter: str) -> str:
if letter in game[‘given_letters’]:
msg = f”You have already said ‘{letter}'”
elif letter in game[‘word’]:
msg = f”Good, {letter} is in the word”
game[‘given_letters’].add(letter)
else:
msg = f”Sorry, {letter} is NOT in the word”
game[‘given_letters’].add(letter)
game[‘fails’] += 1 return msg
SNP
def get_data(line: str) -> [str, str, set[str]]:
code, ilnesses = line.split(‘:’)
rs_code, nucleotid = code.split()
rs_code = rs_code.strip()
nucleotid = nucleotid.strip()
ilnessset = set()
for ilness in ilnesses.split(‘,’):
ilnessset.add(ilness.strip().lower())
return rs_code, nucleotid, ilnessset
def add_data(snp: dict, rs_code: str, nucleotid: str, ilnesses: set[str]) -> None:
if rs_code in snp:
if nucleotid in snp[rs_code]:
snp[rs_code][nucleotid] |= ilnesses
else:
snp[rs_code][nucleotid] = ilnesses
else:
snp[rs_code] = dict()
snp[rs_code][nucleotid] = ilnesses
def read_snp(filename) -> dict:
snp = dict()
with open(filename) as fln:
for line in fln:
if line[0] != ‘#’:
rs_code, nucleotid, ilnessset = get_data(line)
add_data(snp, rs_code, nucleotid, ilnessset)
return snp
def remove_snp(snp: dict, rs_code: str, code_n: str, pats: set[str])-> None: ** if pats & ilnessset != set():
if rs_code in snp: info.add( (rs_code, nucleotid) )
if code_n in snp[rs_code]: pats return info
snp[rs_code][code_n] -=
if snp[rs_code][code_n] == set():
del snp[rs_code][code_n]
if snp[rs_code] == {}:
del snp[rs_code]
def get_snpinfo(snp: dict, pats: set[str]) -> set[str, str]:
info = set()
for rs_code, val in snp.items():
for nucleotid, ilnessset in val.items(): **
def get_snps(snp: list[dict]) -> dict:
snps = dict()
for rs_code, val in snp.items():
snps[rs_code] = 0
for nucleotid, ilnessset in val.items():
snps[rs_code] += len(ilnessset)
return snps
def mean_ocurrences(snp: dict) -> float:
mean = 0.0
count = 0
for rs_code, num in get_snps(snp).items():
mean += num
count += 1
return mean/count
def mode_ocurrences(snp: dict) -> int:
modedict = dict()
for rs_code, num in get_snps(snp).items():
if num in modedict:
modedict[num] += 1
else:
modedict[num] = 1
mode = 0
max_occ = 0
for num, occur in modedict.items():
if occur > max_occ:
max_occ = occur
mode = num
return mode
def find_pivot(lst, low, high):
return lst[low]
def quick_sort(lst, low, high):
if low elem = find_pivot(lst, low, high)
pos_pivot = partition(lst, elem, low, high)
quick_sort(lst, low, pos_pivot-1)
quick_sort(lst, pos_pivot+1, high)
def sort(lst):
quick_sort(lst,0,len(lst)-1)
def partition(lst, elem, low, high):
lower = low
equal = low
bigger = high
while equal if lst[equal]==elem:
equal += 1
elif lst[equal] lst[lower], lst[equal] = lst[equal], lst[lower]
equal += 1
lower += 1
else:
lst[bigger], lst[equal] = lst[equal], lst[bigger]
bigger -= 1
return lower
def median_ocurrences(snp: dict) -> int:
occlst = []
for rs_code, num in get_snps(snp).items():
occlst.append(num)
sort(occlst)
return occlst[len(occlst)//2]
def write_snp(snp: dict, filename: str) -> None:
with open(filename, ‘w’) as f:
for rs_code, val in snp.items():
for nucleotid, ilnessset in val.items():
line = f'{rs_code} {nucleotid}: ‘
first = True
for ilness in ilnessset:
if not first:
line += ‘, ‘
line += ilness
first = False
line += ‘\n’
f.write(line)
FUNCIONES EXTRA
def is_in(s: str, ltr:str) -> bool:
i = 0
while i i = i + 1
return i
def get_word(txt:str, pos:int) -> str:
i = pos
while i i += 1
word = ”
while i word += txt[i]
i += 1
return word, i
def lower(word: str) -> str:
new = ”
for ltr in word:
if ‘A’ ltr = chr(ord(‘a’) + ord(ltr) – ord(‘A’))
elif ltr == ‘Á’:
ltr = ‘á’
elif ltr == ‘É’:
ltr = ‘é’
elif ltr == ‘Í’:
ltr = ‘í’
elif ltr == ‘Ó’:
ltr = ‘ó’
elif ltr == ‘Ú’:
ltr = ‘ú’
elif ltr == ‘Ü’:
ltr = ‘ü’
elif ltr == ‘Ñ’:
ltr = ‘ñ’
new = new + ltr
return new
def split(txt: str) -> list[str]:
i = 0
word_lst = []
while i word, i = get_word(txt, i) ** word_lst.append(word)
if word!=”: ** return word_lst