❌ Dependence on few star players can be risky if they are unavailable.
</jimmywong1994/EasyZombie/EasyZombie/Assets/Scripts/Managers/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public enum GameState
{
Menu,
Playing,
GameOver
}
public static class GameManager
{
public static GameState gameState = GameState.Menu;
public static bool paused = false;
public static void StartGame()
{
gameState = GameState.Playing;
paused = false;
Time.timeScale = 1f;
PlayerMovement.isDead = false;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public static void EndGame()
{
gameState = GameState.GameOver;
paused = true;
Time.timeScale = .25f;
AudioListener.volume = .25f;
if(PlayerMovement.score > PlayerPrefs.GetInt(“HighScore”))
PlayerPrefs.SetInt(“HighScore”, PlayerMovement.score);
if(PlayerPrefs.GetInt(“BestTime”) == -1 || PlayerMovement.time > PlayerPrefs.GetInt(“BestTime”))
PlayerPrefs.SetInt(“BestTime”, PlayerMovement.time);
Debug.Log($”New High Score: {PlayerMovement.score}”);
}
# EasyZombie
A simple zombie shooter game made using Unity.
## Instructions
Download [Unity](https://unity.com/) version **2020**.
Open `EasyZombie` folder.
Click `Play` button.
## Controls
* WASD / Arrow Keys – Movement
* Spacebar – Jump
* Left Mouse Button – Shoot
## Objective
Shoot zombies before they kill you.
Collect money from zombies you kill.
Buy upgrades between waves.
## Upgrades
* Weapon Upgrade – Shoot faster / Bullet damage increase / Bullet speed increase.
* Health Upgrade – Health increase / Regeneration rate increase.
* Armor Upgrade – Damage reduction.
## Levels / Waves
Every wave increases difficulty.
After each wave you will have an opportunity to buy upgrades using your money.
## Scoreboard / Leaderboard
At end of each level you will be presented with your score.
Your score will be saved into local storage so you can check how well you did later.
## Credits / Acknowledgements
Music used:
[YouTube Audio Library](https://www.youtube.com/audiolibrary/music)
Models used:
[Zombocalypse Pack](https://assetstore.unity.com/packages/vehicles/mechanical/zombocalypse-pack-203684)
[Zombie Hunter Pack](https://assetstore.unity.com/packages/3d/environments/zombie-hunter-pack-198163)
jimmywong1994/EasyZombie<|file_sep OrderedDict([('player', {'id': 'player', 'position': [-5., -0., -10.]})]), OrderedDict([('zombies', {'id': 'zombies', 'position': [[[-6., -0., -9], [-7., -0., -9], [-6., -0., -11], [-7., -0., -11]]]})])]
['[INFO] Initializing new level.', '[INFO] Level initialized successfully!']
{'id': 'player', 'position': [-5., -0., -10.]}
—————————————————————————
AssertionError Traceback (most recent call last)
in ()
—–> 1 assert test_level_init(levels) == True
AssertionError:
[‘[INFO] Initializing new level.’, ‘[INFO] Level initialized successfully!’]
{‘id’: ‘player’, ‘position’: [-5., -0., -10.]}
—————————————————————————
AssertionError Traceback (most recent call last)
in ()
—–> 1 assert test_level_init(levels) == True
AssertionError:
[‘[INFO] Initializing new level.’, ‘[INFO] Level initialized successfully!’]
{‘id’: ‘player’, ‘position’: [-5., -0., -10.]}
—————————————————————————
AssertionError Traceback (most recent call last)
in ()
—–> 1 assert test_level_init(levels) == True
AssertionError:
[‘[INFO] Initializing new level.’, ‘[INFO] Level initialized successfully!’]
{‘id’: ‘player’, ‘position’: [-5., -0., -10.]}
—————————————————————————
AssertionError Traceback (most recent call last)
in ()
—–> 1 assert test_level_init(levels) == True
AssertionError:
[‘[INFO] Initializing new level.’, ‘[INFO] Level initialized successfully!’]
{‘id’: ‘player’, ‘position’: [-5., -0., -10.]}
—————————————————————————
AssertionError Traceback (most recent call last)
in ()
—–> 1 assert test_level_init(levels) == True
AssertionError:
[‘[INFO] Initializing new level.’, ‘[INFO] Level initialized successfully!’]
{‘id’: ‘player’, ‘position’: [-5., -0., -10.]}
—————————————————————————
TypeError Traceback (most recent call last)
in _level_spawn(level_data)
21 print(f'[DEBUG][LevelSpawn]: Entity ID “{entity_id}” spawned.’)
22 print(f'[DEBUG][LevelSpawn]: Entity ID “{entity_id}” position set.’)
—> 23 return entity_id # Return entity ID upon successful spawn.
24
25
TypeError: cannot unpack non-iterable str object
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
Cell In[11], line ??
—->> __cell_line__
f'{level_data[“entities”][i][“type”]}_spawn({level_data[“entities”][i][“data”][“position”]})’
)
File “”, line ?, cell line ?
f'{level_data[“entities”][i][“type”]}_spawn({level_data[“entities”][i][“data”][“position”]})’
)
File “”, line ?, cell line ?
f'{level_data[“entities”][i][“type”]}_spawn({level_data[“entities”][i][“data”][“position”]})’
)
File “”, line ?, cell line ?
f'{level_data[“entities”][i][“type”]}_spawn({level_data[“entities”][i][“data”][“position”]})’
)
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/game.py”, line ?, cell line ?
def _level_spawn(level_data):
–> return _entity_spawn(level_data[“type”], level_data[“data”][“position”])
return _entity_spawn(level_data[“type”], level_data[“data”][“position”])
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/game.py”, line ?, cell line ?
def _entity_spawn(entity_type=None , position=None):
–> entity_id , entity_position = globals()[f”{entity_type}_spawn”](position)
entity_id , entity_position = globals()[f”{entity_type}_player”](position)
NameError: name ‘_entity_spawn_player’ is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
Cell In[12], line ??
—->> __cell_line__
print(test_level_init(levels))
File “”, line ?, cell line ?
print(test_level_init(levels))
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/test_game.py”, line ?, cell line ?
def test_level_init(level_list):
–> result_list , result_dict = _test_level_init(level_list)
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/test_game.py”, line ?, cell line ?
def _test_level_init(level_list):
–> return [_test_entity_spawn(entity) for entity in level_list]
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/test_game.py”, line ?, cell line ?
def _test_entity_spawn(entity):
–> return _test_entity_spawn(entity)
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/test_game.py”, line ?, cell line ?
def _test_entity_spawn(entity):
–> return (_entity_spawn(entity[“type”], entity[“data”][“position”]), entity)
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/game.py”, line ?, cell_line ???
return (_entity_spawn(level_data[“type”], level_data[“data”][“position”]), level_data)
NameError: name ‘_entity_spawn’ is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
Cell In[12], line ??
—->> __cell_line__
print(test_level_init(levels))
File “”, line ?, cell_line ???
print(test_level_init(levels))
File “/Users/jimmywong/Documents/GitHub/EasyZombie/EasyZombie/lib/python_files/test_game.py”,line?,cell_line ???
def test_level_init(level_list):
TypeError: cannot unpack non-iterable NoneType object
***** Tag Data *****
ID: 4
description: Test function that initializes levels by spawning entities dynamically,
start line: 17
end line: 34
dependencies:
– type: Function
name: _test_entity_spawn()
start line: 29
end line: 31
context description: This snippet tests initialization by dynamically spawning entities,
algorithmic depth external dependencies included here show advanced use cases such
as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such
as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
algorithmic depth external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
obscurity external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
obscurity external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
obscurity external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
obscurity external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
obscurity external dependencies included here show advanced use cases such as dynamic function calls based on string names using globals().
advanced coding concepts external dependencies include multiple layers of nested functions along with error handling mechanisms which makes it quite intricate.
************
## Challenging aspects
### Challenging aspects in above code:
1. **Dynamic Function Calls Using `globals()`**: The snippet leverages Python’s `globals()` dictionary for dynamically invoking functions by constructing their name strings at runtime (`globals()[f”{entity_type}_spawn”](pos)`). This requires understanding how Python’s runtime environment manages global variables/functions.
2. **Complex Error Handling**: The snippet uses nested try-except blocks within list comprehensions which makes error tracing more challenging due to multiple layers of exceptions being caught.
3. **Nested List Comprehensions**: The code involves complex list comprehensions that iterate over lists within lists (`for i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d][index]]`). This adds complexity because it requires keeping track of multiple indices across different dimensions.
4. **Data Structure Manipulation**: The snippet operates heavily with dictionaries nested within lists (`{“entities”: [{“type”: …, “data”: {“name”: …, “health”: …, “damage”: …, “speed”: …, “attack_cooldown”: …, “range”: …, “color”: …, “mass”: …}}]}])`, requiring careful manipulation and access patterns.
### Extension:
To extend these challenges specifically:
1. **Adding Conditional Logic Based On Entity Type**: Introduce additional conditions within `_test_entity_spawn()` that handle different types differently during initialization.
2. **Entity Dependencies**: Some entities might depend upon others being spawned first; introduce logic that ensures these prerequisites are met before spawning certain entities.
3. **Dynamic Configuration**: Instead of hardcoding configuration data directly into `_test_entity`, make it accept configurations dynamically via parameters passed at runtime or read from an external source like a JSON file.
4. **Logging Enhancements**: Extend logging capabilities by adding detailed logs at various stages including before calling any spawn functions dynamically through `globals()`, capturing more granular details about each step’s success/failure states.
—
## Exercise:
### Problem Statement:
You are required to expand upon an existing codebase that tests initialization by dynamically spawning entities described by configuration dictionaries containing nested structures representing various attributes like health points (`hp`), attack damage (`damage`), speed (`speed`), etc.
The task involves extending functionality through several steps:
#### Step-by-step Requirements:
1. **Enhance Dynamic Initialization**:
* Modify `_test_entity_spawn()` so it handles different types differently during initialization depending upon additional attributes present within each entity type configuration.
* Introduce conditional logic inside `_test_entity_spawn()` that checks whether certain prerequisite entities have already been spawned before attempting further spawns.
* Ensure comprehensive logging throughout every stage including before invoking any spawn functions dynamically via `globals()`. Log details should include timestamps and specific attributes related to each step’s success/failure states.
#### Additional Constraints:
* Implement dependency checks ensuring certain entities must be spawned prior others where necessary.
* Handle configurations dynamically instead of hardcoding them directly into `_test_entity`. Accept configurations via parameters passed at runtime or read from an externally provided JSON file containing configurations similar but potentially more complex than those given initially.
### Provided Code Snippet ([SNIPPET]):
python
# Use this provided code snippet referred below [SNIPPET]
### Detailed Solution:
python
import json # Assuming JSON file usage for configurations
# Helper Functions assumed present somewhere globally accessible including original ones mentioned earlier e.g.,
# def player_health(): …
# def zombie_health(): …
# def zombie_attack(): …
# New enhanced helper functions would look something like below
def log(message): # Simple logging utility method assuming global context usage
print(f”[LOG]: {message}”)
def check_prerequisites(spawned_entities_set): # Dummy example implementation checking prerequisites prior spawning specific types
prerequisites_met = True # Example placeholder logic assuming all prerequisites met initially
# Add actual prerequisite checks logic according requirements
return prerequisites_met
def load_configurations(file_path): # Utility method loading config from JSON file path provided
try:
with open(file_path,’r’) as config_file:
configs=json.load(config_file)
log(f”Configurations loaded successfully from {file_path}”)
return configs
except Exception as e:
log(f”Failed loading configurations from {file_path}: {str(e)}”)
raise e
def enhanced_test_entity_initialize(config_file_path):
config_levels=load_configurations(config_file_path)
spawned_entities_set=set()
result=[]
try :
result=[_enhanced_test_level_initialize(config_levels)]
log(“[LOG]: Enhanced Test Entity Initialize Completed Successfully.”)
return result
except Exception as e :
def _enhanced_test_level_initialize(level_list):
—
### Follow-up Exercise:
**Further Complexity Addition**:
Imagine now that some entities might require real-time updates after being spawned depending upon interactions happening post-initialization phase (e.g.: health regeneration over time).
#### Additional Requirements:
* Implement periodic updates post-initialization phase which periodically adjust specific attributes for certain entities according predefined rulesets.
* Create unit tests ensuring periodic updates behave correctly adjusting attributes without affecting already existing initializations state integrity.
—
### Solution:
python
import threading # For implementing periodic updates through threads if needed
class PeriodicUpdater(threading.Thread):
def __init__(self,interval,function,args=(),kwargs={}):
super().__init__()
self.interval=interval # Update interval period seconds count
self.function=function # Function pointer performing update action
self.args=args # Args tuple passed into update action
self.kwargs=kwargs # Kwargs dict passed into update action
def run(self):
while True :
self.function(*self.args,**self.kwargs)
time.sleep(self.interval)
# Example dummy update method assuming global context usage
def dummy_update_action(*args,**kwargs):
log(“Performing periodic attribute update…”)
arXiv identifier: hep-th/0004019
DOI: https://doi.org/10.1007/BF02704132
# Hamiltonian formulation for constrained systems arising from gauge theories coupled minimally with gravity via Palatini formalism : general treatment II : Lagrangian constraints versus Hamiltonian constraints : classification scheme I : case IIB : model IIIBG-CS-GYMIIIBCSG-YMIIIBCSGYMIIICSGYMIIICSMG-YMIIICSMGYMIIIDSMGYM-IIIECSMGYM-IIIFCSMGYM-IIIGCSMGYM-IIIHCSMGYM-IIISCGYMIIITCSMGYM-IIIVSCGMYMTHEORY OF CONSTRAINTS FOR CONFINED GRAVITY AND GRAVITY-COUPLED SYSTEMS WITH MINIMAL GAUGE INVARIANCE AND HIGHER DERIVATIVES : CASE IIB : MODEL IIIBG-CS-GYM ; IIIBCSG ; YM ; IIIBCSGYM ; IIICSGYM ; IIICSMG-YM ; IIICSMGYM ; IIIDSMGYM ; IIIECSMGYM ; IIIFCSMGYM ; IIIGCSMGYM ; IIHSCGMYMTHEORY OF CONSTRAINTS FOR CONFINED GRAVITY AND GRAVITY-COUPLED SYSTEMS WITH MINIMAL GAUGE INVARIANCE AND HIGHER DERIVATIVES : CASE IIB : MODEL IIIBG-CS-GYM ; IIIBCSG ; YM ; IIIBCSGYM ; IIICSGYM ; IIICSMG-YM ; IIICSMGYM ; IIIDSMGYM ;
Authors: M.P.Gregoriadis Jr.(RRC-Kanazawa University), J.L.Silva Neto(RRC-Kanazawa University), J.A.Nascimento(RRC-Kanazawa University), M.A.Castro-Rodrigues(RRC-Kanazawa University), L.J.Borges da Silva(RCC-USP-Brazil), E.M.R.Ferreira-da-Costa(RCC-USP-Brazil).
Date: None<>
if not data.name.startswith(‘tmp’):
# don’t rename tmp files generated during import/export operations…
new_name=data.name.replace(old_suffix,new_suffix)+’.’+new_ext.lower()
data.rename(new_name)
else:
self.logger.info(‘skipping temporary file %r’%repr(data.path))
else:
self.logger.info(‘skipping non-image file %r’%repr(data.path))
def rename_images(self,data_objects,rename_all=False,new_suffix=”,new_ext=’jpg’):
“””rename images”””
if rename_all==True:# rename all files regardless suffixes…
for data_objn,data_objm,data_objl,data_objk,data_obij,data_obi,data_obih
in six.moves.zip_longest(*list(map(list,list(islice(cycle([data_objects]),15))))):
self._rename_image(data_objn,new_suffix,new_ext)# we need only one image object…
if data_objm!=None:self._rename_image(data_objm,new_suffix,new_ext)# updaters may add images…
if data_objl!=None:self._rename_image(data_objl,new_suffix,new_ext)# updaters may add images…
if data_objk!=None:self._rename_image(data_objk,new_suffix,new_ext)# updaters may add images…
if data_obij!=None:self._rename_image(data_obij,new_suffix,new_ext)# updaters may add images…
if data_obi!=None:self._rename_image(data_obi,new_suffix,new_ext)# updaters may add images…
if data_obih!=None:self._rename_image(data_obih,new_suffix,new_ext)# updaters may add images…
else:# rename only files having old suffixes..
for data_objecto,data_objectn,data_objectm,data_objectl,
data_objectk,data_objectj,data_objecti,
data_objecth
in six.moves.zip_longest(*list(map(list,list(islice(cycle([data_objects]),15))))):
self._rename_image_if_old_suffix(
data_objecto,
new_suffix=new_suffix,
new_ext=new_ext,# jpg/jpeg/png/gif/tiff/tif/bmp/heif/heix/hev/hevx/
old_suffix=self.old_default_imagesuffix,
old_ext=self.old_default_imageext.lower())
self._rename_image_if_old_suffix(
data_objectn,
new_suffix=new_suffix,
new_ext=new_ext,# jpg/jpeg/png/gif/tiff/tif/bmp/heif/heix/hev/hevx/
old_suffix=self.old_default_imagesuffix,
old_ext=self.old_default_imageext.lower())
self._rename_image_if_old_suffix(
data_objectm,
new_suffix=new_suffix,
new_ext=new_ext,# jpg/jpeg/png/gif/tiff/tif/bmp/heif/heix/hev/hevx/
old_suffix=self.old_default_imagesuffix,
old_ext=self.old_default_imageext.lower())
self._rename_image_if_old_suffix(
data_objectl,
new_suffix=new_suffix,
new_ext=new_ext,# jpg/jpeg/png/gif/tiff/tif/bmp/heif/heix/hev/hevx/
old_suffix=self.old_default_imagesuffix,
old_ext=self.old_default_imageext.lower())
self._rename_image_if_old_prefix(
data_objectk,
new_prefix=”,
old_prefix=’thumb.’,
new_sufxfix=”,
old_sufxfix=”,
new_postfix=’.jpg’,
old_postfix=’.jpg’)
self._rename_video_thumbnail_if_old_prefix(
data_obij,”,
”,
”,
”,
”,
”)
self._rename_video_thumbnail_if_old_prefix(
data_obi,”,
”,
”,
”,
”,
”)
self._rename_video_thumbnail_if_old_prefix(
data_obih,”,
”,
”,
”,
”
)
return None
def delete_unwanted_thumbnails(self,path_to_folder_with_thumbnails,file_extension_in_lower_case=’jpg’):
“””delete unwanted thumbnails”””
for filename_in_folder_with_thumbnails
in os.listdir(path_to_folder_with_thumbnails)
or []:
filepath=os.path.join(path_to_folder_with_thumbnails,filename_in_folder_with_thumbnails)
try:# filter files by extension only… ignore directories etc..
if os.path.isfile(filepath)
and os.path.splitext(filepath)[1].lower()==’.%s’%file_extension_in_lower_case
and not filename_in_folder_with_thumbnails.startswith(‘original.’)
and not filename_in_folder_with_thumbnails.endswith(‘.%s’%file_extension_in_lower_case)
and filename_in_folder_with_thumbnails!=’default.jpg’:
os.unlink(filepath)
self.logger.info(‘deleted thumbnail %r’%filepath)
else:# skip unwanted files..
pass#print(filename_in_folder_with_thumbnails,’skipped…’)
except EnvironmentError:# catch exceptions only.. do not display tracebacks..
pass#print(filename_in_folder_with_thumbnails,’skipped…’)
return None
def delete_unwanted_videos(self,path_to_folder_with_videos,file_extension_in_lower_case=’mp4′):
“””delete unwanted videos”””
for filename_in_folder_with_videos
in os.listdir(path_to_folder_with_videos)
or []:
filepath=os.path.join(path_to_folder_with_videos,filename_in_folder_with_videos)
try:# filter files by extension only… ignore directories etc..
if os.path.isfile(filepath)
and os.path.splitext(filepath)[1].lower()==’.%s’%file_extension_in_lower_case
and not filename_in_folder_with_videos.startswith(‘original.’)
and not filename_in_folder_with_videos.endswith(‘.%s’%file_extension_in_lower_case)
and filename_in_folder_with_videos!=’default.mp4’:
os.unlink(filepath)
self.logger.info(‘deleted video %r’%filepath)
else:# skip unwanted files..
pass#print(filename_in_folder_with_videos,’skipped…’)
except EnvironmentError:# catch exceptions only.. do not display tracebacks..
pass#print(filename_in_folder_with_videos,’skipped…’)
return None
def delete_unwanted_originals(self,path_to_originals_dir,file_extension_for_original_images=’jpeg’):
for filename_of_original_img
in os.listdir(path_to_originals_dir)
or []:
filepath=os.path.join(path_to_originals_dir,filename_of_original_img)
try:# filter files by extension only… ignore directories etc..
if os.path.isfile(filepath)
and os.path.splitext(filepath)[1].lower()==’.%s’%file_extension_for_original_images
and not filename_of_original_img.startswith(‘original.’)
and not filename_of_original_img.endswith(‘.%s’%file_extension_for_original_images)
and filename_of_original_img!=’default.jpeg’:
os.unlink(filepath)# remove original image without suffixes nor prefixes nor postfixes… keep just default.original.jpg !!
self.logger.info(‘deleted original %r’%filepath)
else:# skip unwanted files..
pass#print(filename_of_original_img,’skipped…’)
except EnvironmentError:# catch exceptions only.. do not display tracebacks..
pass#print(filename_of_original_img,’skipped…’)
return None
def delete_unwanted_album_artworks(self,path_to_album_artworks_dir,file_extension_for_album_artwork_images=’jpeg’):
“””delete unwanted album artworks”””
for filename_of_album_artwork_img
in os.listdir(path_to_album_artworks_dir)
or []:
filepath=os.path.join(path_to_album_artworks_dir,filename_of_album_artwork_img)
try:# filter files by extension only… ignore directories etc..
if os.path.isfile(filepath)
and os.path.splitext(filepath)[1].lower()==’.%s’%file_extension_for_album_artwork_images
and not filename_of_album_artwork_img.startswith(‘albumart.’)
and not filename_of_album_artwork_img.endswith(‘.%s’%file_extension_for_album_artwork_images)
and filename_of_album_artwork_img!=’default.jpeg’:
os.unlink(filepath)# remove album artwork image without suffixes nor prefixes nor postfixes… keep just default.albumart.jpg !!
self.logger.info(‘deleted album artwork %r’%filepath)
else:# skip unwanted files..
pass#print(filename_of_album_artwork_img,’skipped…’)
except EnvironmentError:# catch exceptions only.. do not display tracebacks..
pass#print(filename_of_album_artwork_img,’skipped…’)
return None
def delete_unwanted_musicvideos(self,path_to_musicvideos_dir,file_extensions_for_musicvideo_imgs=[‘avi’,’wmv’,’mov’,’mpg’,’mpeg’,’mkv’]):
“””delete unwanted music videos”””
for filenameofmusicvideoimginmusicvideosdirinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdir
in list(os.listdir(path_to_musicvideos_dir))
or []:
filepath=os.path.join(path_to_musicvideos_dir,filenameofmusicvideoimginmusicvideosdirinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdirorinmusicvideosdir)# get full path !
try:# filter files by extension only… ignore directories etc..
if (
(
(
(
(
(
(
(
(
(
(
os.path.isfile(filepath)
and len(os.listdir(path_to_musicvideos_dir))<=50000#ntttttttttpathlib.Path(directory).iterdir()ntttttttttsorted(x)n t t t t t tfor xn t t t t tin pathlib.Path(directory).iterdir()n t t t tin sorted(x)ntpathlib.Path(directory).iterate()ntpathlib.Path(directory).iterates()ntpathlib.Path(directory).iteratefiles()ntpathlib.Path(directory).iteratefilesandfolders()ntpathlib.Path(directory).iterateimages()ntpathlib.Path(directory).iterateimagesandfolders()ntpathlib.Path(directory).iterateonlyfiles()ntpathlib.Path(directory).iterateonlyimages()
)and len(os.listdir(os.getcwd()))<=50000#ntqdm.tqdm(iterable,nskipinitial=0,ncolor=None,nclassname=None,ndesc=None,ndesc_fill='-',
ndesc_fillchar=' ',
ascii=None,nlazy=texttt{False},
disable=