Skip to content

Commit

Permalink
User data encription
Browse files Browse the repository at this point in the history
  • Loading branch information
RaffaeleFiorillo committed Oct 21, 2021
1 parent 265764d commit ab73d0d
Show file tree
Hide file tree
Showing 40 changed files with 184 additions and 177 deletions.
115 changes: 63 additions & 52 deletions Auxiliary_Functionalities.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
[120, 0, 120], [0, 255, 255], [0, 0, 255]]
road_colors = [[0, 0, 0], [108, 108, 108]]
code_meaning = {3: "unknown", 0: "road", 1: "parts", -1: "lava"}
valid_characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQERSUVWXYZ_"
valid_characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ _,.'"
# AI variables achieved by a genetic algorithm that can be found in the genetic_algorithm module
WEIGHTS = [-0.024636661554064646, 0.9490338548623168, 0.9490338548623168, 0.17090764398454833, 1.0661495372951384]
BIAS = [0.2670813587084078, -0.6691533200275781, -0.5723370239650385, 0.25406116993577665, -0.486196069971221]
Expand Down Expand Up @@ -199,17 +199,15 @@ def get_fibonacci(order: int)-> int:

# ------------------------------------- MENU FUNCTIONS -----------------------------------------------------------------
def get_sound_volume()-> float:
with open("saves/active_user.txt", "r") as file:
line = file.readline().split(" ")
line = read_file_content("saves/active_user.txt", 1)[0].split(" ")
if len(line) != 1:
return float(line[7])/10
else:
return 1.0


def get_music_volume()-> float:
with open("saves/active_user.txt", "r") as file:
line = file.readline().split(" ")
line = read_file_content("saves/active_user.txt", 1)[0].split(" ")
if len(line) != 1:
return float(line[6])/20.0
else:
Expand Down Expand Up @@ -425,25 +423,20 @@ def get_users_images() -> ([Surface], [Surface]):

# gets the requirement values in order to verify if user has leveled up from the parameters file and returns them
def get_requirements() -> (int, int):
with open("saves/active_user.txt", "r") as f:
str_level = f.readline().split(" ")[3]
user_level = int(str_level)
with open(f"parameters/levels info/{user_level}.txt", "r") as f:
values = f.readline().split(" ")
return int(values[0]), int(values[1])
user_level = int(read_file_content("saves/active_user.txt", 1)[0].split(" ")[3]) # get user level in his file
speed, precision, _parts = read_file_content(f"parameters/levels info/{user_level}.txt", 1)[0].split(" ")
return int(speed), int(precision)


# updates the data in the next_level.txt file
def save_next_level_data(user_name: str, m_ai_data: int, winner_data: int) -> None:
with open(f"saves/{user_name}/next_level.txt", "w") as file:
file.write(f"{m_ai_data} \n{winner_data}")
write_file_content(f"saves/{user_name}/next_level.txt", [f"{m_ai_data} \n{winner_data}"])


# returns current user's information
def get_user_data() -> ([str], [int]):
# active user format: "Name speed best_time level parts password volume1 volume2"
with open("saves/active_user.txt", "r") as file:
values_p = file.readline().split(" ")
values_p = read_file_content("saves/active_user.txt", 1)[0].split(" ")
str_val = [values_p[0], values_p[5]]
int_val = [int(value) for value in values_p if value.isdigit()]
return str_val, int_val
Expand All @@ -453,12 +446,9 @@ def get_user_data() -> ([str], [int]):
def save_user_data(data: (str, int, int, int, int, str, int, int)) -> None:
name, b_speed, b_time, level, parts, password, volume1, volume2 = data
line = f"{name} {b_speed} {b_time} {level} {parts} {password} {volume1} {volume2}"
with open("saves/active_user.txt", "w") as file:
file.write(line)

write_file_content("saves/active_user.txt", line)
line = f"{b_speed} {b_time} {level} {parts} {password} {volume1} {volume2}"
with open(f"saves/{name}/data.txt", "w") as file:
file.write(line)
write_file_content(f"saves/{name}/data.txt", line)


# updates user information after a played match is over, for Mission AI
Expand Down Expand Up @@ -496,18 +486,14 @@ def save_performance_parts(parts: int, speed: int, time: int) -> None:

# returns the current user's level
def get_user_level() -> int:
with open("saves/active_user.txt", "r") as file:
user_level = int(file.readline().split(" ")[3])
user_level = int(read_file_content("saves/active_user.txt", 1)[0].split(" ")[3])
return user_level


# returns True if the user has already won the game before, and False in the opposite case
def user_is_a_winner() -> int:
with open("saves/active_user.txt", "r") as file:
user_name = file.readline().split(" ")[0]
with open(f"saves/{user_name}/next_level.txt", "r") as file:
file.readline() # ignore the first line
is_a_winner = int(file.readline())
user_name = int(read_file_content("saves/active_user.txt", 1)[0].split(" ")[3])
is_a_winner = int(read_file_content(f"saves/{user_name}/next_level.txt")[1])
return is_a_winner


Expand Down Expand Up @@ -587,8 +573,7 @@ def get_text_images(line: [str]) -> Surface:
def save_text_image(name: str) -> None:
screen2 = pygame.display.set_mode((519, 135))
background = load_image("texts/text_background.png")
with open(f"texts/{name}.txt", "r") as file:
lines = file.readlines()
lines = read_file_content(f"texts/{name}.txt")
text_font = pygame.font.SysFont('Times New Roman', 20)
text_font.set_bold(True)
coordinates = ((12, 6), (12, 22), (12, 38), (12, 53), (12, 68), (12, 83), (12, 98))
Expand Down Expand Up @@ -665,21 +650,24 @@ def encrypt_letter(letter: str, key: int) -> str:

# given a string, returns the encrypted version of it
def encrypt_line(data: str, key: int)-> str:
data = data if "\n" not in data else data[:-1]
encrypted_data = "".join(reversed([encrypt_letter(char, key) if char != " " else " " for char in data]))
data = data.strip() if "\n" not in data else data[:-1]
encrypted_data = "".join(reversed([encrypt_letter(char, key) for char in data]))
return encrypted_data


# encrypts a file given his directory
def encrypt_file(directory: str) -> None:
with open(directory, "r") as file: # get file content
lines = file.readlines()
if len(lines) == 0: # prevents list index error if file is empty
return None
with open(directory, "w") as file:
for line in lines[:-1]:
for line in lines:
key = randint(1, len(valid_characters) - 1)
file.write(f"{key} {encrypt_line(line, key)}\n")
key = randint(1, len(valid_characters) - 1)
file.write(f"{key} {encrypt_line(lines[-1], key)}")
if line is not lines[-1]:
file.write(f"{key} {encrypt_line(line, key)}\n")
else:
file.write(f"{key} {encrypt_line(lines[-1], key)}")


# encrypts a letter based on a given key_value
Expand All @@ -691,33 +679,56 @@ def decrypt_letter(letter: str, key: int) -> str:
# given a string, returns the decrypted version of it
def decrypt_line(data: str, key):
data = data if "\n" not in data else data[:-1]
decrypted_data = "".join(reversed([decrypt_letter(char, key) if char != " " else " " for char in data]))
decrypted_data = "".join(reversed([decrypt_letter(char, key) for char in data]))
return decrypted_data


# de crypts a file given his directory
def decrypt_file(directory: str):
with open(directory, "r") as file: # get file content
lines = file.readlines()
if len(lines) == 0: # prevents list index error if file is empty
return None
with open(directory, "w") as file:
for line in lines[:-1]:
for line in lines:
key = int(line.split(" ")[0])
start_index = line.index(" ")
file.write(f"{decrypt_line(line[start_index:], key)}\n")
key = int(lines[-1].split(" ")[0])
start_index = lines[-1].index(" ")
file.write(decrypt_line(lines[-1][start_index:], key))
start_index = line.index(" ")+1
if line is not lines[-1]:
file.write(f"{decrypt_line(line[start_index:], key)}\n")
else:
file.write(decrypt_line(lines[-1][start_index:], key))


def read_file_content(file_directory, lines_to_read=0):
decrypt_file(file_directory)
with open(file_directory, "r") as file:
if lines_to_read == 0:
file_content = file.readlines()
else:
file_content = [file.readline() for _ in range(lines_to_read)]
encrypt_file(file_directory)
return file_content


def print_file(directory):
with open(directory, "r") as file:
lines = file.readlines()
for line in lines:
print(line)
def write_file_content(file_directory, content):
with open(file_directory, "w") as file:
file.writelines(content)
encrypt_file(file_directory)


def reset_file(directory):
text = "this file is just for testing 1\nthis file is just for testing 2\nthis file is just for testing 3\nthis " \
"file is just for testing 4"
with open(directory, "w") as file:
file.write(text)
def encrypt_all_files(directories):
for directory in directories:
print(f"encrypting: {directory}")
try:
encrypt_file(directory)
except ValueError:
print(f"!!! Error in current directory: {directory} !!!")


def decrypt_all_files(directories):
for directory in directories:
print(f"decrypting: {directory}")
try:
decrypt_file(directory)
except ValueError:
print(f"!!! Error in current directory: {directory} !!!")
3 changes: 1 addition & 2 deletions entity_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ def activate_fire(self, fire_type):
@staticmethod
def get_car_image():
try:
with open("saves/active_user.txt", "r") as file:
level = file.readline().split(" ")[3]
level = Af.read_file_content("saves/active_user.txt", 1)[0].split(" ")[3]
except IndexError:
level = 21
return Af.load_image(f"cars/{level}.png")
Expand Down
16 changes: 11 additions & 5 deletions eventos.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import game_classes as gc
# import link_functions as lf
import entity_classes as ce

# import math
# import time
# import pygame
Expand Down Expand Up @@ -139,7 +140,6 @@ def initiate_test(self):
return False # if it gets here, it means it not good enough
"""


# SCREEN = pygame.display.set_mode((Af.SCREEN_LENGTH, Af.SCREEN_WIDTH))
"""World = Data_World(SCREEN)
World.initiate_test()"""
Expand All @@ -151,9 +151,15 @@ def initiate_test(self):
file.write(Af.encrypt_line("Raffaele Fiorillo"))
file.close()"""

Af.encrypt_file("test_file.txt")
Af.decrypt_file("test_file.txt")
directories = ["saves/R.F.J.8/data.txt", "saves/Raffaele/data.txt", "saves/teste/data.txt",
"saves/R.F.J.8/next_level.txt", "saves/Raffaele/next_level.txt", "saves/teste/next_level.txt",
"parameters/levels info/1.txt", "parameters/levels info/2.txt", "parameters/levels info/3.txt",
"parameters/levels info/4.txt", "parameters/levels info/5.txt", "parameters/levels info/6.txt",
"parameters/levels info/7.txt", "parameters/levels info/8.txt", "parameters/levels info/9.txt",
"parameters/levels info/10.txt", "parameters/levels info/11.txt", "parameters/levels info/12.txt",
"parameters/levels info/13.txt", "texts/1.txt", "texts/2.txt", "texts/3.txt", "texts/4.txt",
"texts/5.txt", "texts/6.txt", "texts/7.txt", "texts/8.txt", ]

Af.print_file("test_file.txt")
Af.reset_file("test_file.txt")
Af.encrypt_all_files(directories)

# [print(f'"{directory}",') for directory in directories]
Binary file modified game.exe
Binary file not shown.
6 changes: 1 addition & 5 deletions game_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ def __init__(self, screen):
def set_up_texts(self, first=False):
self.text_name = Af.choice(Af.get_text_names())[:-4] # chooses random text from existing texts
self.text_to_write_image = Af.load_image(f"texts/{self.text_name}.png") # loads the text's image
with open(f"texts/{self.text_name}.txt", "r") as file: # loads the text's content
lines = file.readlines()
lines = Af.read_file_content(f"texts/{self.text_name}.txt") # loads the text's content
self.text_to_write = [line.split(" ") for line in lines[1:]] # sets the text in proper format
self.screen.blit(self.text_to_write_image, (280, 320))
image = Af.get_text_images("") # turns written text into images to display
Expand Down Expand Up @@ -353,9 +352,6 @@ def __init__(self, screen):
# loop stuff
self.total_time = 0.0

def take_exclusive_class_action(self):
print(self.resistance)

def set_up_texts(self, first=False):
super(Mission_PARTS, self).set_up_texts() # sets up next text to be displayed
if not first: # if it's not the first text to be loaded:
Expand Down
Binary file modified images/menu/interfaces/prov_image/prov_image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/texts/9.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 4 additions & 5 deletions link_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def game_menu(screen: Af.Surface):
g_m = cm.Menu(buttons_game, f"menu/interfaces/Main/game menu.png", screen, user)
next_link = g_m.display_menu()
if next_link == "m_ai":
if not int(open(f"saves/{user.name}/next_level.txt").readline()):
mission_is_unlocked = int(Af.read_file_content(f"saves/{user.name}/next_level.txt", 1)[0])
if not mission_is_unlocked:
next_link = "nx_l"
return next_link

Expand Down Expand Up @@ -252,13 +253,11 @@ def delete_account(screen: Af.Surface):
buttons = [cm.Button(240, 410, f"menu/buttons/3/1.png", True),
cm.Button(580, 410, f"menu/buttons/3/2.png", False)]
if cm.Exit("menu/exit/delete_account.png", screen, buttons).display_menu():
file = open("saves/active_user.txt", "r")
line = file.readline().split(" ")
user_name = Af.read_file_content("saves/active_user.txt", 1)[0].split(" ")[0]
verification_password = cm.Enter_Password(screen, True).display_menu()
file.close()
if verification_password == "main_menu":
Af.play(delete_account_sound)
Af.delete_user_account(line[0])
Af.delete_user_account(user_name)
return verification_password
return "manage"

Expand Down
Loading

0 comments on commit ab73d0d

Please sign in to comment.