Final changes and commit

This commit is contained in:
Kristofers Solo 2022-08-02 20:34:11 +03:00
parent db328c4350
commit 253802ac88
38 changed files with 1917 additions and 1708 deletions

1
.gitignore vendored
View File

@ -6,3 +6,4 @@
/december/task_081221/*.log /december/task_081221/*.log
**.pkl **.pkl
**test.py **test.py
pygame/snake/source/score.csv

View File

@ -8,56 +8,56 @@ HEADERS = {
class IKEA: class IKEA:
def __init__(self, url): def __init__(self, url):
self.url = 'https://www.ikea.lv/en/products/' + url + '?&&page=1&order=PRICEASC' self.url = 'https://www.ikea.lv/en/products/' + url + '?&&page=1&order=PRICEASC'
def _get_paige_amount(self): def _get_paige_amount(self):
page_amount = 1 page_amount = 1
page = requests.get(self.url, headers=HEADERS) page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
# getting max page amount # getting max page amount
for el in soup.find_all(class_='page-link'): for el in soup.find_all(class_='page-link'):
cropped_name = el.get_text().strip() cropped_name = el.get_text().strip()
if cropped_name.isnumeric(): if cropped_name.isnumeric():
cropped_name = int(cropped_name) cropped_name = int(cropped_name)
if cropped_name > page_amount: if cropped_name > page_amount:
page_amount = cropped_name page_amount = cropped_name
return page_amount return page_amount
def get_data(self): def get_data(self):
prices = [] prices = []
names = [] names = []
prices.clear() prices.clear()
names.clear() names.clear()
# combined_list.clear() # combined_list.clear()
position = self.url.find('page=') + 5 position = self.url.find('page=') + 5
for i in range(1, self._get_paige_amount() + 1): for i in range(1, self._get_paige_amount() + 1):
url = self.url[:position] + str(i) + self.url[position + 1:] url = self.url[:position] + str(i) + self.url[position + 1:]
page = requests.get(url, headers=HEADERS) page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
# getting product name # getting product name
for el in soup.find_all(class_='display-7 mr-2'): for el in soup.find_all(class_='display-7 mr-2'):
cropped_name = el.get_text().strip() cropped_name = el.get_text().strip()
names.append(cropped_name) names.append(cropped_name)
# getting product price # getting product price
for el in soup.find_all(class_='display-6'): for el in soup.find_all(class_='display-6'):
cropped_price = el.get_text().strip() cropped_price = el.get_text().strip()
prices.append(cropped_price[:cropped_price.find("") + 1]) prices.append(cropped_price[:cropped_price.find("") + 1])
combined_list = [i + " - " + j for i, j in zip(names, prices)] combined_list = [i + " - " + j for i, j in zip(names, prices)]
if __name__ == '__main__': if __name__ == '__main__':
SEPARATOR = "\n" SEPARATOR = "\n"
else: else:
SEPARATOR = "<br>" SEPARATOR = "<br>"
output = SEPARATOR.join(str(elem) for elem in combined_list) output = SEPARATOR.join(str(elem) for elem in combined_list)
print(len(names)) print(len(names))
return output return output
arm_chairs = IKEA('ikea-for-business/office/armchairs') arm_chairs = IKEA('ikea-for-business/office/armchairs')
@ -67,29 +67,36 @@ bed_frames = IKEA('bedroom/beds-and-sofa-beds/bed-frames')
bookcases = IKEA('living-room/bookcases/bookcases') bookcases = IKEA('living-room/bookcases/bookcases')
boxes_and_baskets = IKEA('bedroom/sorting-solutions/boxes-and-baskets') boxes_and_baskets = IKEA('bedroom/sorting-solutions/boxes-and-baskets')
candles = IKEA('kitchen/kitchen-decoration/candles') candles = IKEA('kitchen/kitchen-decoration/candles')
ceiling_lamps_and_spotlights = IKEA('decoration/lighting/ceiling-lamps-and-spotlights') ceiling_lamps_and_spotlights = IKEA(
'decoration/lighting/ceiling-lamps-and-spotlights')
chairs_and_benches = IKEA('dining-room/dining-seating/chairs-and-benches') chairs_and_benches = IKEA('dining-room/dining-seating/chairs-and-benches')
chest_of_drawers = IKEA('bedroom/chest-of-drawers-other-furniture/chest-of-drawers') chest_of_drawers = IKEA(
children_storage_furniture = IKEA('children-s-room/children-3-7/children-s-storage-furniture') 'bedroom/chest-of-drawers-other-furniture/chest-of-drawers')
children_storage_furniture = IKEA(
'children-s-room/children-3-7/children-s-storage-furniture')
curtains = IKEA('kitchen/curtains-blinds-and-fabrics/curtains') curtains = IKEA('kitchen/curtains-blinds-and-fabrics/curtains')
day_beds = IKEA('bedroom/beds-and-sofa-beds/day-beds') day_beds = IKEA('bedroom/beds-and-sofa-beds/day-beds')
dining_tables = IKEA('dining-room/dining-tables/dining-tables') dining_tables = IKEA('dining-room/dining-tables/dining-tables')
dinnerware_and_serving = IKEA('kitchen/cookware-and-dinnerware/dinnerware-and-serving') dinnerware_and_serving = IKEA(
'kitchen/cookware-and-dinnerware/dinnerware-and-serving')
glasses = IKEA('kitchen/cookware-and-dinnerware/glasses') glasses = IKEA('kitchen/cookware-and-dinnerware/glasses')
home_desks = IKEA('home-office/desks/home-desks') home_desks = IKEA('home-office/desks/home-desks')
interior_organisers = IKEA('home-office/wardrobes/interior-organisers') interior_organisers = IKEA('home-office/wardrobes/interior-organisers')
kitchen_interior_organisers = IKEA('kitchen/kitchen-interior-organisers/kitchen-interior-organisers') kitchen_interior_organisers = IKEA(
'kitchen/kitchen-interior-organisers/kitchen-interior-organisers')
light_bulbs = IKEA('bedroom/bedroom-lighting/light-bulbs') light_bulbs = IKEA('bedroom/bedroom-lighting/light-bulbs')
mattresses = IKEA('bedroom/mattresses/mattresses') mattresses = IKEA('bedroom/mattresses/mattresses')
mirrors = IKEA('kitchen/kitchen-decoration/mirrors') mirrors = IKEA('kitchen/kitchen-decoration/mirrors')
office_chairs = IKEA('home-office/work-seating-range/office-chairs') office_chairs = IKEA('home-office/work-seating-range/office-chairs')
office_desks_and_tables = IKEA('home-office/desks/office-desks-and-tables') office_desks_and_tables = IKEA('home-office/desks/office-desks-and-tables')
open_shelving_units = IKEA('living-room/shelving-units-systems/open-shelving-units') open_shelving_units = IKEA(
'living-room/shelving-units-systems/open-shelving-units')
pax_wardrobes = IKEA('ikea-for-business/retail/system-wardrobes') pax_wardrobes = IKEA('ikea-for-business/retail/system-wardrobes')
pendant_lamps = IKEA('ikea-for-business/retail/pendant-lamps') pendant_lamps = IKEA('ikea-for-business/retail/pendant-lamps')
pillows = IKEA('bedroom/bedding/pillows') pillows = IKEA('bedroom/bedding/pillows')
pots = IKEA('kitchen/cookware-and-dinnerware/pots') pots = IKEA('kitchen/cookware-and-dinnerware/pots')
quilt_covers_and_pillow_cases = IKEA('bedroom/bedding/quilt-covers-and-pillow-cases') quilt_covers_and_pillow_cases = IKEA(
'bedroom/bedding/quilt-covers-and-pillow-cases')
quilts = IKEA('bedroom/bedding/quilts') quilts = IKEA('bedroom/bedding/quilts')
rugs = IKEA('living-room/home-furnishing-rugs/rugs') rugs = IKEA('living-room/home-furnishing-rugs/rugs')
sheets_and_pillow_cases = IKEA('bedroom/bedding/sheets-and-pillow-cases') sheets_and_pillow_cases = IKEA('bedroom/bedding/sheets-and-pillow-cases')
@ -100,22 +107,23 @@ solitaire_wardrobes = IKEA('bedroom/wardrobes/solitaire-wardrobes')
system_cabinets = IKEA('living-room/solitaire-cabinets/system-cabinets') system_cabinets = IKEA('living-room/solitaire-cabinets/system-cabinets')
table_lamps = IKEA('bedroom/bedroom-lighting/table-lamps') table_lamps = IKEA('bedroom/bedroom-lighting/table-lamps')
towels = IKEA('bathroom/towels/towels') towels = IKEA('bathroom/towels/towels')
toys_for_small_children = IKEA('children-s-room/children-3-7/toys-for-small-children') toys_for_small_children = IKEA(
'children-s-room/children-3-7/toys-for-small-children')
tv_benches = IKEA('living-room/tv-stands-media-units/tv-benches') tv_benches = IKEA('living-room/tv-stands-media-units/tv-benches')
def main(): def main():
# import cProfile # import cProfile
# import pstats # import pstats
# with cProfile.Profile() as pr: # with cProfile.Profile() as pr:
# tv_benches.get_data() # tv_benches.get_data()
# stats = pstats.Stats(pr) # stats = pstats.Stats(pr)
# stats.sort_stats(pstats.SortKey.TIME) # stats.sort_stats(pstats.SortKey.TIME)
# # stats.print_stats() # # stats.print_stats()
# stats.dump_stats(filename='stats.prof') # stats.dump_stats(filename='stats.prof')
print(tv_benches.get_data()) print(tv_benches.get_data())
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,72 +1,80 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="IKEA_logo.svg" type="image/svg" /> <link rel="icon" href="IKEA_logo.svg" type="image/svg" />
<title>IKEA scraper</title> <title>IKEA scraper</title>
<link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="style.css" />
<script src="eel.js"></script> <script src="eel.js"></script>
</head> </head>
<body> <body>
<select name="dropdown" id="product"> <select name="dropdown" id="product">
<option value="Armchairs">Armchairs</option> <option value="Armchairs">Armchairs</option>
<option value="Bathroom furniture">Bathroom furniture</option> <option value="Bathroom furniture">Bathroom furniture</option>
<option value="Bathroom lightning">Bathroom lightning</option> <option value="Bathroom lightning">Bathroom lightning</option>
<option value="Bed frames">Bed frames</option> <option value="Bed frames">Bed frames</option>
<option value="Bookcases">Bookcases</option> <option value="Bookcases">Bookcases</option>
<option value="Boxes and baskets">Boxes and baskets</option> <option value="Boxes and baskets">Boxes and baskets</option>
<option value="Ceiling lamps and spotlight">Ceiling lamps and spotlight</option> <option value="Ceiling lamps and spotlight">
<option value="Chest of drawers">Chest of drawers</option> Ceiling lamps and spotlight
<option value="Children's storage furniture">Children's storage furniture</option> </option>
<option value="curtains">Curtains</option> <option value="Chest of drawers">Chest of drawers</option>
<option value="day beds">Day beds</option> <option value="Children's storage furniture">
<option value="dining tables">Dining tables</option> Children's storage furniture
<option value="dinnerware and serving">Dinnerware and serving</option> </option>
<option value="glasses">Glasses</option> <option value="curtains">Curtains</option>
<option value="home desks">Home desks</option> <option value="day beds">Day beds</option>
<option value="interior organisers">Interior organisers</option> <option value="dining tables">Dining tables</option>
<option value="kitchen interior organisers">Kitchen interior organisers</option> <option value="dinnerware and serving">Dinnerware and serving</option>
<option value="light bulbs">Light bulbs</option> <option value="glasses">Glasses</option>
<option value="mattresses">Mattresses</option> <option value="home desks">Home desks</option>
<option value="mirrors">Mirrors</option> <option value="interior organisers">Interior organisers</option>
<option value="office chairs">Office chairs</option> <option value="kitchen interior organisers">
<option value="office desks and tables">Office desks and tables</option> Kitchen interior organisers
<option value="open shelving units">Open shelving units</option> </option>
<option value="pax wardrobes">PAX wardrobes</option> <option value="light bulbs">Light bulbs</option>
<option value="pendant lamps">Pendant lamps</option> <option value="mattresses">Mattresses</option>
<option value="pillows">Pillows</option> <option value="mirrors">Mirrors</option>
<option value="pots">Pots</option> <option value="office chairs">Office chairs</option>
<option value="quilt covers and pillow cases">Quilt covers and pillow cases</option> <option value="office desks and tables">Office desks and tables</option>
<option value="quilts">Quilts</option> <option value="open shelving units">Open shelving units</option>
<option value="rugs">Rugs</option> <option value="pax wardrobes">PAX wardrobes</option>
<option value="sheets and pillow cases">Sheets and pillow cases</option> <option value="pendant lamps">Pendant lamps</option>
<option value="sofa beds and chair beds">Sofa beds and chair beds</option> <option value="pillows">Pillows</option>
<option value="sofa tables">Sofa tables</option> <option value="pots">Pots</option>
<option value="solitaire cabinets">Solitaire cabinets</option> <option value="quilt covers and pillow cases">
<option value="solitaire wardrobes">Solitaire wardrobes</option> Quilt covers and pillow cases
<option value="system cabinets">System cabinets</option> </option>
<option value="table lamps">Table lamps</option> <option value="quilts">Quilts</option>
<option value="towels">Towels</option> <option value="rugs">Rugs</option>
<option value="toys for small children">Toys for small children</option> <option value="sheets and pillow cases">Sheets and pillow cases</option>
<option value="tv benches">TV benches</option> <option value="sofa beds and chair beds">Sofa beds and chair beds</option>
</select> <option value="sofa tables">Sofa tables</option>
<option value="solitaire cabinets">Solitaire cabinets</option>
<option value="solitaire wardrobes">Solitaire wardrobes</option>
<option value="system cabinets">System cabinets</option>
<option value="table lamps">Table lamps</option>
<option value="towels">Towels</option>
<option value="toys for small children">Toys for small children</option>
<option value="tv benches">TV benches</option>
</select>
<button id="show">Find products</button> <button id="show">Find products</button>
<div id="info"></div> <div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script> <script>
async function call() { async function call() {
let product = document.getElementById("product").value; let product = document.getElementById('product').value
let res = await eel.call_in_js(product)(); let res = await eel.call_in_js(product)()
document.getElementById("info").innerHTML = res; document.getElementById('info').innerHTML = res
} }
jQuery("#show").on("click", function () { jQuery('#show').on('click', function () {
call(); call()
}); })
</script> </script>
</body> </body>
</html> </html>

View File

@ -1,55 +1,55 @@
html, html,
body { body {
font-family: "Roboto", sans-serif; font-family: 'Roboto', sans-serif;
background: #f2f2f2; background: #f2f2f2;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
#product { #product {
display: flex; display: flex;
margin-top: 10px; margin-top: 10px;
height: 30px; height: 30px;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
background-color: #333333; background-color: #333333;
width: 95%; width: 95%;
min-width: 100px; min-width: 100px;
border-radius: 5px; border-radius: 5px;
cursor: pointer; cursor: pointer;
color: #cccccc; color: #cccccc;
} }
#show { #show {
display: block; display: block;
border: none; border: none;
margin: auto; margin: auto;
margin-top: 10px; margin-top: 10px;
margin-bottom: 10px; margin-bottom: 10px;
min-width: 200px; min-width: 200px;
background: #666666; background: #666666;
border-radius: 5px; border-radius: 5px;
padding: 10px; padding: 10px;
color: #f2f2f2; color: #f2f2f2;
outline: none; outline: none;
width: 95%; width: 95%;
font-size: 18px; font-size: 18px;
text-transform: uppercase; text-transform: uppercase;
cursor: pointer; cursor: pointer;
transition: transform 0.7s ease; transition: transform 0.7s ease;
} }
#show:hover { #show:hover {
opacity: 0.9; opacity: 0.9;
transform: scale(1.01); transform: scale(1.01);
} }
#info { #info {
color: #666666; color: #666666;
display: block; display: block;
text-align: center; text-align: center;
font-size: 16px; font-size: 16px;
font-weight: bold; font-weight: bold;
} }

View File

@ -8,37 +8,37 @@ url = "https://www.ikea.lv/"
all_page = requests.get(url) all_page = requests.get(url)
if all_page.status_code == 200: if all_page.status_code == 200:
page = BeautifulSoup(all_page.content, 'html.parser') page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock") found = page.find_all(class_="itemBlock")
info = [] info = []
item_array = [] item_array = []
for item in found: for item in found:
item = item.findChild("div").findChild(class_="card-body") item = item.findChild("div").findChild(class_="card-body")
item_name = item.findChild(class_="itemName") item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6") item_name = item_name.findChild("div").findChild("h6")
item_array.append(item_name.string) item_array.append(item_name.string)
price = item.findChild(class_="itemPrice-wrapper") price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span") price = price.findChild("p").findChild("span")
try: try:
item_array.append(price.attrs["data-price"]) item_array.append(price.attrs["data-price"])
except: except:
item_array.append(price.attrs["data-pricefamily"]) item_array.append(price.attrs["data-pricefamily"])
all_facts = [] all_facts = []
for facts in all_facts: for facts in all_facts:
if len(facts) == 1: if len(facts) == 1:
all_facts.append(facts.string) all_facts.append(facts.string)
else: else:
atrasts = facts.findChildren("span") atrasts = facts.findChildren("span")
for i in atrasts: for i in atrasts:
all_facts.append(i.string) all_facts.append(i.string)
item_array.append(all_facts) item_array.append(all_facts)
info.append(item_array) info.append(item_array)
for ieraksts in info: for ieraksts in info:
print(ieraksts) print(ieraksts)

View File

@ -10,98 +10,111 @@ from io import BytesIO
from openpyxl.styles import Font, Alignment from openpyxl.styles import Font, Alignment
import openpyxl import openpyxl
HEADERS = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.97 Safari/537.36 Vivaldi/4.1.2369.21'} HEADERS = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.97 Safari/537.36 Vivaldi/4.1.2369.21'}
class SS: class SS:
def __init__(self, url): def __init__(self, url):
self.url = url self.url = url
def _get_page_amount(self): def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS) page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
last_url = soup.find(class_='td2').findChild('a')['href'] last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")] page_amount = last_url[last_url.find(
print(f"Page amount = {page_amount}") "page") + 4:last_url.find(".html")]
print(f"Page amount = {page_amount}")
return int(page_amount) return int(page_amount)
def get_data(self): def get_data(self):
items = [] items = []
images = [] images = []
item_no = 1 item_no = 1
for page_number in range(1, self._get_page_amount() + 1): for page_number in range(1, self._get_page_amount() + 1):
url = self.url + f"/page{page_number}.html" url = self.url + f"/page{page_number}.html"
page = requests.get(url, headers=HEADERS) page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
# item ids # item ids
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids ids = [tag['id']
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list for tag in soup.select('tr[id]')] # creates list with ids
ids.remove("head_line") # removes first "head_line" id # removes "tr_bnr" elements from list
print(f"Page {page_number}") ids = [x for x in ids if "tr_bnr" not in x]
ids.remove("head_line") # removes first "head_line" id
print(f"Page {page_number}")
# getting item data # getting item data
for el in soup.find_all(id=ids): for el in soup.find_all(id=ids):
print(f"Item {item_no}") print(f"Item {item_no}")
item_no += 1 item_no += 1
# image # image
image_url = el.find(class_='msga2').find_next_sibling().findChild('a').findChild('img')['src'] # gets image url image_url = el.find(class_='msga2').find_next_sibling().findChild(
response = requests.get(image_url) 'a').findChild('img')['src'] # gets image url
img = Image.open(BytesIO(response.content)) response = requests.get(image_url)
images.append(img) img = Image.open(BytesIO(response.content))
print(img) images.append(img)
for elem in el.find_all(class_='msga2-o pp6'): print(img)
items.append(elem.get_text()) for elem in el.find_all(class_='msga2-o pp6'):
items.append(elem.get_text())
# adverts url # adverts url
item_url = el.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url item_url = el.findChild(class_='msg2').findChild(
item_url = "https://www.ss.com" + item_url 'div').findChild('a')['href'] # gets url
item_page = requests.get(item_url, headers=HEADERS) item_url = "https://www.ss.com" + item_url
item_soup = BeautifulSoup(item_page.content, 'html.parser') item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts full text # adverts full text
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text item_text = item_soup.find(
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table) id='msg_div_msg').get_text() # gets full text
items.append(item_text) # removes text last part (table)
item_text = item_text[:item_text.find("Pilsēta:")]
items.append(item_text)
# adverts publication date # adverts publication date
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class' # gets all 'msg_footer' class'
item_date = item_date[2].get_text() # extracts 3rd element item_date = item_soup.find_all('td', class_='msg_footer')
items.append(item_date[8:18]) # crops date item_date = item_date[2].get_text() # extracts 3rd element
items.append(item_date[8:18]) # crops date
chunk_size = 8 chunk_size = 8
chunked_items_list = [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] # combines each 'chunk_size' elements into array # combines each 'chunk_size' elements into array
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs", "Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"] chunked_items_list = [items[i:i + chunk_size]
df = pd.DataFrame(chunked_items_list, columns=columns) for i in range(0, len(items), chunk_size)]
df.to_excel(excel_writer='output.xlsx', index=False) columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs",
"Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df = pd.DataFrame(chunked_items_list, columns=columns)
df.to_excel(excel_writer='output.xlsx', index=False)
wb = openpyxl.load_workbook("output.xlsx") wb = openpyxl.load_workbook("output.xlsx")
ws = wb.worksheets[0] ws = wb.worksheets[0]
sheet = wb.active sheet = wb.active
# 'I1' cell setup # 'I1' cell setup
ws['I1'] = "Attēli" ws['I1'] = "Attēli"
ws['I1'].font = Font(bold=True) ws['I1'].font = Font(bold=True)
ws["I1"].alignment = Alignment(horizontal='center', vertical='top') ws["I1"].alignment = Alignment(horizontal='center', vertical='top')
# sets cell width # sets cell width
sheet.column_dimensions['A'].width = 20 sheet.column_dimensions['A'].width = 20
sheet.column_dimensions['G'].width = 50 sheet.column_dimensions['G'].width = 50
sheet.column_dimensions['H'].width = 20 sheet.column_dimensions['H'].width = 20
sheet.column_dimensions['I'].width = 13 sheet.column_dimensions['I'].width = 13
for i in range(len(images)): for i in range(len(images)):
sheet.row_dimensions[i + 2].height = 51 # sets cell height sheet.row_dimensions[i + 2].height = 51 # sets cell height
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True) # enables word wrap # enables word wrap
ws[f'G{i + 2}'].alignment = Alignment(wrap_text=True)
img = openpyxl.drawing.image.Image(images[i]) img = openpyxl.drawing.image.Image(images[i])
ws.add_image(img, f"I{i + 2}") # adds images ws.add_image(img, f"I{i + 2}") # adds images
wb.save("output.xlsx") wb.save("output.xlsx")
print("Done") print("Done")
flats = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/") flats = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/")
@ -109,8 +122,8 @@ flats2 = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/")
def main(): def main():
flats.get_data() flats.get_data()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -11,9 +11,9 @@ from selenium.webdriver.common.by import By
use_firefox = True use_firefox = True
if use_firefox: if use_firefox:
browser = webdriver.Firefox() browser = webdriver.Firefox()
else: else:
browser = webdriver.Chrome("chromedriver") browser = webdriver.Chrome("chromedriver")
address = "https://www.riga.lv/lv" address = "https://www.riga.lv/lv"
browser.get(address) browser.get(address)
@ -25,7 +25,8 @@ search = browser.find_element_by_class_name('search-link')
search.click() search.click()
delay = 2 delay = 2
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'edit-search'))) WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'edit-search')))
search = browser.find_element_by_id('edit-search') search = browser.find_element_by_id('edit-search')
search.send_keys("dokum") # writes in search line search.send_keys("dokum") # writes in search line
@ -33,9 +34,11 @@ search = browser.find_element_by_id('search-header-button')
search.click() search.click()
browser.maximize_window() browser.maximize_window()
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content'))) WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
delay = 3 delay = 3
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'filter_type_file'))) WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
filter = browser.find_element_by_css_selector('label[for="filter_type_file"]') filter = browser.find_element_by_css_selector('label[for="filter_type_file"]')
filter.click() filter.click()

View File

@ -16,108 +16,116 @@ firefox = ["2", "firefox"]
def get_data(): def get_data():
user_browser, user_pages, search_word = get_user_input() user_browser, user_pages, search_word = get_user_input()
for page in user_pages: for page in user_pages:
if user_browser in chromium: if user_browser in chromium:
if os.name in ('nt', 'dos'): if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows browser = webdriver.Chrome("chromedriver.exe") # windows
else: else:
browser = webdriver.Chrome("chromedriver") # gnu/linux browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox: elif user_browser in firefox:
browser = webdriver.Firefox() browser = webdriver.Firefox()
url = f"https://www.riga.lv/lv/search?q={search_word}&types=file&page={page - 1}" url = f"https://www.riga.lv/lv/search?q={search_word}&types=file&page={page - 1}"
browser.get(url) browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click() browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
files = browser.find_elements(By.CLASS_NAME, 'file') files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files: for file in files:
file_name = file.text file_name = file.text
file_url = file.get_attribute('href') file_url = file.get_attribute('href')
file_download(file_name, file_url) file_download(file_name, file_url)
browser.quit() browser.quit()
def get_user_input(): def get_user_input():
if debug == True: if debug == True:
search_word = "dokum" search_word = "dokum"
else: else:
search_word = input("Choose keyword to search: ") search_word = input("Choose keyword to search: ")
last_page = get_max_page_amount(search_word) last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:") print("\nChoose which browser to use:")
print("1 - chromium (chrome)") print("1 - chromium (chrome)")
print("2 - firefox") print("2 - firefox")
if debug == True: if debug == True:
browser = "firefox" browser = "firefox"
else: else:
browser = input("").lower() browser = input("").lower()
print(f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.") print(
try: f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
if debug == True: try:
user_input = "1" if debug == True:
else: user_input = "1"
user_input = input("").lower() else:
user_input = input("").lower()
if user_input == "all": if user_input == "all":
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages # creates list with all pages
else: pages = list(map(int, range(1, last_page + 1)))
user_page_list = user_input.split(" ") else:
for page_range in user_page_list: user_page_list = user_input.split(" ")
if "-" in page_range: for page_range in user_page_list:
if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number first_num = int(page_range[:page_range.find("-")])
# gets second number
second_num = int(page_range[page_range.find("-") + 1:]) + 1
if second_num > last_page: # reduces user input to max page amount if second_num > last_page: # reduces user input to max page amount
second_num = last_page second_num = last_page
user_page_list = user_page_list + list(map(str, range(first_num, second_num))) # creates list with str range user_page_list = user_page_list + \
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-" list(map(str, range(first_num, second_num))
pages = list(map(int, pages)) # convers str to int ) # creates list with str range
pages.sort() # sorts list # removes all elements containing "-"
pages = list(set(pages)) # removes duplicates from list pages = [elem for elem in user_page_list if not "-" in elem]
except: pages = list(map(int, pages)) # convers str to int
print("Enered incorrect number/s. Try again.") pages.sort() # sorts list
return browser, pages, search_word pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word
def get_max_page_amount(keyword: str): def get_max_page_amount(keyword: str):
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file" url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url) page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
try: try:
last_page = soup.find(class_='pager__item--last').get_text().strip() last_page = soup.find(class_='pager__item--last').get_text().strip()
except: except:
try: try:
last_page = soup.find_all(class_='pager__item page-item') last_page = soup.find_all(class_='pager__item page-item')
last_page = last_page[-1].get_text().strip()[-1] # gets last number from navigation bar # gets last number from navigation bar
except: last_page = last_page[-1].get_text().strip()[-1]
print("Something went wrong. Please try again or try another keyword.") except:
return int(last_page) print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
def file_download(file_name, file_url): def file_download(file_name, file_url):
print(f"\nNAME: {file_name}") print(f"\nNAME: {file_name}")
print(f"URL: {file_url}") print(f"URL: {file_url}")
path = "files" path = "files"
if not exists(path): if not exists(path):
os.mkdir(path) os.mkdir(path)
response = requests.get(file_url) response = requests.get(file_url)
if ".pdf" in file_name: if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content) open(f"{path}/{file_name}", "wb").write(response.content)
else: else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content) open(f"{path}/{file_name}.pdf", "wb").write(response.content)
def main(): def main():
get_data() get_data()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -21,126 +21,138 @@ firefox = ["2", "firefox"]
def get_data(): def get_data():
user_browser, user_pages, search_word, last_page = get_user_input() user_browser, user_pages, search_word, last_page = get_user_input()
if user_browser in chromium: if user_browser in chromium:
if os.name in ('nt', 'dos'): if os.name in ('nt', 'dos'):
browser = webdriver.Chrome("chromedriver.exe") # windows browser = webdriver.Chrome("chromedriver.exe") # windows
else: else:
browser = webdriver.Chrome("chromedriver") # gnu/linux browser = webdriver.Chrome("chromedriver") # gnu/linux
elif user_browser in firefox: elif user_browser in firefox:
browser = webdriver.Firefox() browser = webdriver.Firefox()
url = "https://www.riga.lv/lv/" url = "https://www.riga.lv/lv/"
browser.get(url) browser.get(url)
browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click() browser.find_element(By.CLASS_NAME, 'cookie-accept-all').click()
browser.find_element(By.CLASS_NAME, 'search-link').click() browser.find_element(By.CLASS_NAME, 'search-link').click()
delay = 2 delay = 2
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'edit-search'))) WebDriverWait(browser, delay).until(
search = browser.find_element(By.ID, 'edit-search') EC.presence_of_all_elements_located((By.ID, 'edit-search')))
search.send_keys(search_word) # writes in search line search = browser.find_element(By.ID, 'edit-search')
search.send_keys(search_word) # writes in search line
browser.find_element(By.ID, 'search-header-button').click() browser.find_element(By.ID, 'search-header-button').click()
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content'))) WebDriverWait(browser, delay).until(
WebDriverWait(browser, delay).until(EC.presence_of_all_elements_located((By.ID, 'filter_type_file'))) EC.presence_of_all_elements_located((By.CLASS_NAME, 'filter-content')))
WebDriverWait(browser, delay).until(
EC.presence_of_all_elements_located((By.ID, 'filter_type_file')))
browser.find_element(By.CSS_SELECTOR, 'label[for="filter_type_file"]').click() browser.find_element(
By.CSS_SELECTOR, 'label[for="filter_type_file"]').click()
browser.find_element(By.ID, 'search-view-button').click() browser.find_element(By.ID, 'search-view-button').click()
for current_page in range(1, last_page + 1): for current_page in range(1, last_page + 1):
if current_page in user_pages: if current_page in user_pages:
files = browser.find_elements(By.CLASS_NAME, 'file') files = browser.find_elements(By.CLASS_NAME, 'file')
for file in files: for file in files:
file_name = file.text file_name = file.text
file_url = file.get_attribute('href') file_url = file.get_attribute('href')
file_download(file_name, file_url) file_download(file_name, file_url)
if current_page != last_page: if current_page != last_page:
browser.find_element(By.CLASS_NAME, 'pager__item--next').click() browser.find_element(By.CLASS_NAME, 'pager__item--next').click()
if current_page == user_pages[-1]: if current_page == user_pages[-1]:
break break
browser.quit() browser.quit()
def get_user_input(): def get_user_input():
if debug == True: if debug == True:
search_word = "dokum" search_word = "dokum"
else: else:
search_word = input("Choose keyword to search: ") search_word = input("Choose keyword to search: ")
last_page = get_max_page_amount(search_word) last_page = get_max_page_amount(search_word)
print("\nChoose which browser to use:") print("\nChoose which browser to use:")
print("1 - chromium (chrome)") print("1 - chromium (chrome)")
print("2 - firefox") print("2 - firefox")
if debug == True: if debug == True:
browser = "firefox" browser = "firefox"
else: else:
browser = input("").lower() browser = input("").lower()
print(f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.") print(
try: f"\nChoose from which pages you want to download files (1 4 7; 2-5; all). Maximum is {last_page} pages.")
if debug == True: try:
user_input = "16-17" if debug == True:
else: user_input = "16-17"
user_input = input("").lower() else:
user_input = input("").lower()
if user_input == "all": if user_input == "all":
pages = list(map(int, range(1, last_page + 1))) # creates list with all pages # creates list with all pages
else: pages = list(map(int, range(1, last_page + 1)))
user_page_list = user_input.split(" ") else:
for page_range in user_page_list: user_page_list = user_input.split(" ")
if "-" in page_range: for page_range in user_page_list:
if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number first_num = int(page_range[:page_range.find("-")])
# gets second number
second_num = int(page_range[page_range.find("-") + 1:]) + 1
if second_num > last_page: # reduces user input to max page amount if second_num > last_page: # reduces user input to max page amount
second_num = last_page second_num = last_page
user_page_list = user_page_list + list(map(str, range(first_num, second_num + 1))) # creates list with str range user_page_list = user_page_list + \
pages = [elem for elem in user_page_list if not "-" in elem] # removes all elements containing "-" list(map(str, range(first_num, second_num + 1))
pages = list(map(int, pages)) # convers str to int ) # creates list with str range
pages.sort() # sorts list # removes all elements containing "-"
pages = list(set(pages)) # removes duplicates from list pages = [elem for elem in user_page_list if not "-" in elem]
except: pages = list(map(int, pages)) # convers str to int
print("Enered incorrect number/s. Try again.") pages.sort() # sorts list
return browser, pages, search_word, last_page pages = list(set(pages)) # removes duplicates from list
except:
print("Enered incorrect number/s. Try again.")
return browser, pages, search_word, last_page
def get_max_page_amount(keyword: str): def get_max_page_amount(keyword: str):
url = f"https://www.riga.lv/lv/search?q={keyword}&types=file" url = f"https://www.riga.lv/lv/search?q={keyword}&types=file"
page = requests.get(url) page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
try: try:
last_page = soup.find(class_='pager__item--last').get_text().strip() last_page = soup.find(class_='pager__item--last').get_text().strip()
except: except:
try: try:
last_page = soup.find_all(class_='pager__item page-item') last_page = soup.find_all(class_='pager__item page-item')
last_page = last_page[-1].get_text().strip()[-1] # gets last number from navigation bar # gets last number from navigation bar
except: last_page = last_page[-1].get_text().strip()[-1]
print("Something went wrong. Please try again or try another keyword.") except:
return int(last_page) print("Something went wrong. Please try again or try another keyword.")
return int(last_page)
def file_download(file_name, file_url): def file_download(file_name, file_url):
print(f"\nNAME: {file_name}") print(f"\nNAME: {file_name}")
print(f"URL: {file_url}") print(f"URL: {file_url}")
path = "files" path = "files"
if not exists(path): if not exists(path):
os.mkdir(path) os.mkdir(path)
response = requests.get(file_url) response = requests.get(file_url)
if ".pdf" in file_name: if ".pdf" in file_name:
open(f"{path}/{file_name}", "wb").write(response.content) open(f"{path}/{file_name}", "wb").write(response.content)
else: else:
open(f"{path}/{file_name}.pdf", "wb").write(response.content) open(f"{path}/{file_name}.pdf", "wb").write(response.content)
def main(): def main():
get_data() get_data()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,26 +1,31 @@
def main(): def main():
try: try:
user_input = input("Input: ") user_input = input("Input: ")
user_input_array = user_input.split(" ") user_input_array = user_input.split(" ")
if user_input == "all": if user_input == "all":
pages = list(map(int, range(1, 17 + 1))) pages = list(map(int, range(1, 17 + 1)))
else: else:
for page_range in user_input_array: for page_range in user_input_array:
if "-" in page_range: if "-" in page_range:
first_num = int(page_range[:page_range.find("-")]) # gets first number # gets first number
second_num = int(page_range[page_range.find("-") + 1:]) + 1 # gets second number first_num = int(page_range[:page_range.find("-")])
user_input_array = user_input_array + list(map(str, range(first_num, second_num))) # creates list with str range # gets second number
pages = [elem for elem in user_input_array if not "-" in elem] # removes all elements containing "-" second_num = int(page_range[page_range.find("-") + 1:]) + 1
pages = list(map(int, pages)) # convers str to int user_input_array = user_input_array + \
pages.sort() # sorts list list(map(str, range(first_num, second_num))
pages = list(set(pages)) # removes duplicates from list ) # creates list with str range
print(pages) # removes all elements containing "-"
pages = [elem for elem in user_input_array if not "-" in elem]
pages = list(map(int, pages)) # convers str to int
pages.sort() # sorts list
pages = list(set(pages)) # removes duplicates from list
print(pages)
except: except:
print("Something went wrong. Try again.") print("Something went wrong. Try again.")
if __name__ == '__main__': if __name__ == '__main__':
main() main()
# 3 1 5 2 7-11 3-30 # 3 1 5 2 7-11 3-30

View File

@ -9,7 +9,7 @@ file = pd.ExcelFile("dati_masiviem.xlsx")
data = [] data = []
for sheet_name in file.sheet_names: for sheet_name in file.sheet_names:
data.append(file.parse(sheet_name)) data.append(file.parse(sheet_name))
# print(data[0]["Nosaukums"]) # print(data[0]["Nosaukums"])
data[0]["Cena"] = round((data[0]["Pašizmaksa"] + .4) * 1.21, 2) data[0]["Cena"] = round((data[0]["Pašizmaksa"] + .4) * 1.21, 2)
@ -42,6 +42,6 @@ found = data[2]["Datums2"] == "2020-09-09"
page_num = 1 page_num = 1
with pd.ExcelWriter("new_file2.xlsx") as file: with pd.ExcelWriter("new_file2.xlsx") as file:
for page in data: for page in data:
page.to_excel(file, sheet_name=str(page_num), index=False) page.to_excel(file, sheet_name=str(page_num), index=False)
page_num += 1 page_num += 1

View File

@ -9,7 +9,7 @@ file = pd.ExcelFile("dzivnieki.xls")
data = [] data = []
for sheet_name in file.sheet_names: for sheet_name in file.sheet_names:
data.append(file.parse(sheet_name)) data.append(file.parse(sheet_name))
# print(data) # print(data)
# print(data[0]) # print(data[0])
@ -22,6 +22,7 @@ for sheet_name in file.sheet_names:
new_data = pd.concat([data[0], data[1]]) # concatenates data new_data = pd.concat([data[0], data[1]]) # concatenates data
# print(new_data) # print(new_data)
print(new_data.sort_values("Vecums", ascending=False)) # sorts table by age, inverted # sorts table by age, inverted
print(new_data.sort_values("Vecums", ascending=False))
new_data.to_excel("new_file.xls", index=False) new_data.to_excel("new_file.xls", index=False)

View File

@ -15,62 +15,63 @@ import matplotlib.pyplot as plt
def get_data(): def get_data():
data = pd.read_csv("auto_imports_mainits.csv") data = pd.read_csv("auto_imports_mainits.csv")
data_copy = data.copy() data_copy = data.copy()
del data_copy["normalized-losses"] del data_copy["normalized-losses"]
dislike = ["N/A", "NA", "--"] dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike) data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Replaces word written numbers to intigers # Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"] columns = ["num-of-doors", "num-of-cylinders"]
for column in columns: for column in columns:
for value in data_copy3[column]: for value in data_copy3[column]:
try: try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value)) data_copy3 = data_copy3.replace(
except: to_replace=value, value=w2n.word_to_num(value))
pass except:
print(data_copy3[["num-of-doors", "num-of-cylinders"]]) pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers # Leaves only columns that contain numbers
data_copy4 = data_copy3.copy() data_copy4 = data_copy3.copy()
for column in data_copy4: for column in data_copy4:
if isinstance(data_copy4[column][0], str): if isinstance(data_copy4[column][0], str):
del data_copy4[column] del data_copy4[column]
print(data_copy4) print(data_copy4)
return data_copy4 return data_copy4
def graph_plot(): def graph_plot():
data = get_data() data = get_data()
sns.set_style("whitegrid") sns.set_style("whitegrid")
plt.figure(figsize=(15, 10)) plt.figure(figsize=(15, 10))
sns.heatmap(data.corr()) sns.heatmap(data.corr())
plt.savefig("plot1.png") plt.savefig("plot1.png")
# plt.show() # plt.show()
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower] # korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi # noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus # matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas # seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
sns.displot(data["price"]) sns.displot(data["price"])
plt.savefig("plot2.png") plt.savefig("plot2.png")
# plt.show() # plt.show()
plt.scatter(data["price"], data["engine-size"]) plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png") plt.savefig("plot3.png")
# plt.show() # plt.show()
sns.scatterplot(data["price"], data["engine-size"]) sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png") plt.savefig("plot4.png")
# plt.show() # plt.show()
if __name__ == '__main__': if __name__ == '__main__':
# get_data() # get_data()
graph_plot() graph_plot()

View File

@ -2,75 +2,76 @@
# Date - 04.02.2022 # Date - 04.02.2022
# Title - Classwork # Title - Classwork
import matplotlib.pyplot as plt
import pandas as pd import pandas as pd
from word2number import w2n from word2number import w2n
import seaborn as sns import seaborn as sns
import matplotlib import matplotlib
matplotlib.use('Qt5Agg') matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
# mathplotlib ir bibliotēka statisku, animētu un interaktīvu vizualizāciju izveidei # mathplotlib ir bibliotēka statisku, animētu un interaktīvu vizualizāciju izveidei
# seaborn padara matplotlib sarežģītākos momentus par vienkāršākiem # seaborn padara matplotlib sarežģītākos momentus par vienkāršākiem
def get_data(): def get_data():
data = pd.read_csv("auto_imports_mainits.csv") data = pd.read_csv("auto_imports_mainits.csv")
data_copy = data.copy() data_copy = data.copy()
del data_copy["normalized-losses"] del data_copy["normalized-losses"]
dislike = ["N/A", "NA", "--"] dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike) data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Replaces word written numbers to intigers # Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"] columns = ["num-of-doors", "num-of-cylinders"]
for column in columns: for column in columns:
for value in data_copy3[column]: for value in data_copy3[column]:
try: try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value)) data_copy3 = data_copy3.replace(
except: to_replace=value, value=w2n.word_to_num(value))
pass except:
print(data_copy3[["num-of-doors", "num-of-cylinders"]]) pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers # Leaves only columns that contain numbers
data_copy4 = data_copy3.copy() data_copy4 = data_copy3.copy()
for column in data_copy4: for column in data_copy4:
if isinstance(data_copy4[column][0], str): if isinstance(data_copy4[column][0], str):
del data_copy4[column] del data_copy4[column]
print(data_copy4) print(data_copy4)
return data_copy4 return data_copy4
def graph_plot(): def graph_plot():
data = get_data() data = get_data()
sns.set_style("whitegrid") sns.set_style("whitegrid")
plt.figure(figsize=(15, 10)) plt.figure(figsize=(15, 10))
sns.heatmap(data.corr()) sns.heatmap(data.corr())
plt.savefig("plot1.png") plt.savefig("plot1.png")
plt.show() plt.show()
# korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower] # korealācija novērojama starp kolonnām [length,width,wheel-base] un [engine-size,price,horsepower]
# noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi # noderīga ir otrā korelācija, jo tā atklāj to savstarpējo ietekmi
# matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus # matplotlib heatmap veido korealāciju starp datiem savstarpēji salīdzinot to vērtības un norādot iegūtos koeficientus
# seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas # seaborn heatmap veido korealāciju starp datu vērtībām pēc pašnoteiktas korealācijas skalas
sns.displot(data["price"]) sns.displot(data["price"])
plt.savefig("plot2.png") plt.savefig("plot2.png")
plt.show() plt.show()
plt.scatter(data["price"], data["engine-size"]) plt.scatter(data["price"], data["engine-size"])
plt.savefig("plot3.png") plt.savefig("plot3.png")
plt.show() plt.show()
sns.scatterplot(data["price"], data["engine-size"]) sns.scatterplot(data["price"], data["engine-size"])
plt.savefig("plot4.png") plt.savefig("plot4.png")
plt.show() plt.show()
if __name__ == '__main__': if __name__ == '__main__':
# get_data() # get_data()
graph_plot() graph_plot()

View File

@ -18,17 +18,20 @@ data = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
del data["normalized-losses"] del data["normalized-losses"]
select_data = data[["make", "engine-size", "num-of-doors"]] select_data = data[["make", "engine-size", "num-of-doors"]]
select_data = select_data.sort_values(by=["make", "engine-size", "num-of-doors"]) select_data = select_data.sort_values(
by=["make", "engine-size", "num-of-doors"])
select_data = select_data.drop_duplicates() select_data = select_data.drop_duplicates()
col_width = usable_w / 3 col_width = usable_w / 3
height = pdf.font_size * 2 height = pdf.font_size * 2
for i in range(select_data.shape[0]): for i in range(select_data.shape[0]):
pdf.cell(col_width, height, str(select_data["make"].iloc[i]), border=1) pdf.cell(col_width, height, str(select_data["make"].iloc[i]), border=1)
pdf.cell(col_width, height, str(select_data["engine-size"].iloc[i]), border=1) pdf.cell(col_width, height, str(
pdf.cell(col_width, height, str(select_data["num-of-doors"].iloc[i]), border=1) select_data["engine-size"].iloc[i]), border=1)
pdf.ln(height) pdf.cell(col_width, height, str(
select_data["num-of-doors"].iloc[i]), border=1)
pdf.ln(height)
# pdf.image("output.png", x=None, y=None, w=usable_w, h=0) # pdf.image("output.png", x=None, y=None, w=usable_w, h=0)
pdf.output("output.pdf") pdf.output("output.pdf")

View File

@ -49,190 +49,206 @@ series_photos = {
class priceGraph: class priceGraph:
def __init__(self, data, pos, title, x_value, xlabel, xticks=None, y_value=PRICE, ylabel="Price"): def __init__(self, data, pos, title, x_value, xlabel, xticks=None, y_value=PRICE, ylabel="Price"):
self.pos = pos self.pos = pos
self.x_value = data[x_value] self.x_value = data[x_value]
self.y_value = data[y_value] self.y_value = data[y_value]
self.title = title self.title = title
self.xlabel = xlabel self.xlabel = xlabel
self.ylabel = ylabel self.ylabel = ylabel
self.xticks = xticks self.xticks = xticks
def _graph_price(self): def _graph_price(self):
plot = plt.subplot2grid((3, 2), self.pos) plot = plt.subplot2grid((3, 2), self.pos)
plot.scatter(self.x_value, self.y_value) plot.scatter(self.x_value, self.y_value)
plot.set_title(self.title) plot.set_title(self.title)
plot.set_xlabel(self.xlabel) plot.set_xlabel(self.xlabel)
plot.set_ylabel(self.ylabel) plot.set_ylabel(self.ylabel)
if self.xticks != None: if self.xticks != None:
plot.set_xticks(self.xticks) plot.set_xticks(self.xticks)
def read(): def read():
files = list(Path(Path(__file__).parent.absolute()).glob("**/*.xlsx")) files = list(Path(Path(__file__).parent.absolute()).glob("**/*.xlsx"))
for file_path in files: for file_path in files:
all_df.append(pd.read_excel(file_path)) all_df.append(pd.read_excel(file_path))
df_combined = pd.concat(all_df).reset_index(drop=True) # combine DataFrames df_combined = pd.concat(all_df).reset_index(
df_combined.sort_values(by=[PRICE, PUB_DATE], inplace=True) # sort DataFrame drop=True) # combine DataFrames
df_combined.drop_duplicates(keep="first", inplace=True) # drop duplicates df_combined.sort_values(by=[PRICE, PUB_DATE],
# replaces floor value to intiger inplace=True) # sort DataFrame
for value in df_combined[FLOOR]: df_combined.drop_duplicates(keep="first", inplace=True) # drop duplicates
df_combined = df_combined.replace(value, int(float(value[:value.find("/")]))) # replaces floor value to intiger
for value in df_combined[FLOOR]:
df_combined = df_combined.replace(
value, int(float(value[:value.find("/")])))
# replaces price value to intiger # replaces price value to intiger
for value in df_combined[PRICE]: for value in df_combined[PRICE]:
df_combined = df_combined.replace(value, replace_value(value, " ", ",", "")) df_combined = df_combined.replace(
value, replace_value(value, " ", ",", ""))
# replaces "Citi" to 7 # replaces "Citi" to 7
for _ in df_combined[ROOM_AMOUNT]: for _ in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(["citi", "Citi"], "7") df_combined = df_combined.replace(["citi", "Citi"], "7")
# converts room amount to intiger # converts room amount to intiger
for value in df_combined[ROOM_AMOUNT]: for value in df_combined[ROOM_AMOUNT]:
df_combined = df_combined.replace(value, int(value)) df_combined = df_combined.replace(value, int(value))
# converts to datetime # converts to datetime
df_combined[PUB_DATE] = pd.to_datetime(df_combined[PUB_DATE], format="%d.%m.%Y").dt.date df_combined[PUB_DATE] = pd.to_datetime(
df_combined[PUB_DATE], format="%d.%m.%Y").dt.date
df_combined.to_excel("output/excel/combined.xlsx", index=False) df_combined.to_excel("output/excel/combined.xlsx", index=False)
return df_combined.sort_values(by=PUB_DATE) return df_combined.sort_values(by=PUB_DATE)
# replace value # replace value
replace_value = lambda value, find, replace, replace_to: int(value[:value.find(find)].replace(replace, replace_to)) def replace_value(value, find, replace, replace_to): return int(
value[:value.find(find)].replace(replace, replace_to))
def graph_corr(data): def graph_corr(data):
data_corr = data.copy() data_corr = data.copy()
plt.rc("font", size=8) plt.rc("font", size=8)
# gets all series # gets all series
series = [] series = []
for i in data_corr[SERIES]: for i in data_corr[SERIES]:
if i not in series: if i not in series:
series.append(i) series.append(i)
# change series names to numbers # change series names to numbers
data_corr[SERIES] = data_corr[SERIES].replace(series, range(len(series))) data_corr[SERIES] = data_corr[SERIES].replace(series, range(len(series)))
sns.heatmap(data_corr.corr()) sns.heatmap(data_corr.corr())
plt.savefig(f"{output_path}/korelacija.png") plt.savefig(f"{output_path}/korelacija.png")
def graph_price(data): def graph_price(data):
plt.figure(figsize=(50, 30)) plt.figure(figsize=(50, 30))
plt.rc("font", size=15) plt.rc("font", size=15)
plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR, "Floor", range(1, max(data[FLOOR]) + 1)) plot1 = priceGraph(data, (0, 0), "Price to floor", FLOOR,
plot2 = priceGraph(data, (0, 1), "Price to room amount", ROOM_AMOUNT, "Room amount") "Floor", range(1, max(data[FLOOR]) + 1))
plot3 = priceGraph(data, (1, 0), "Price to quadrature", QUADRATURE, "Quadrature") plot2 = priceGraph(data, (0, 1), "Price to room amount",
plot4 = priceGraph(data, (1, 1), "Price to series", SERIES, "Series") ROOM_AMOUNT, "Room amount")
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date") plot3 = priceGraph(data, (1, 0), "Price to quadrature",
QUADRATURE, "Quadrature")
plot4 = priceGraph(data, (1, 1), "Price to series", SERIES, "Series")
plot5 = priceGraph(data, (2, 0), "Price to date", PUB_DATE, "Date")
plot1._graph_price() plot1._graph_price()
plot2._graph_price() plot2._graph_price()
plot3._graph_price() plot3._graph_price()
plot4._graph_price() plot4._graph_price()
plot5._graph_price() plot5._graph_price()
plt.savefig(f"{output_path}/cenu_grafiki.png") plt.savefig(f"{output_path}/cenu_grafiki.png")
def create_pdf(data): def create_pdf(data):
pdf = FPDF("P", "mm", "A4") pdf = FPDF("P", "mm", "A4")
pdf.add_page() pdf.add_page()
pdf.add_font("Roboto", fname="fonts/Roboto-Regular.ttf", uni=True) pdf.add_font("Roboto", fname="fonts/Roboto-Regular.ttf", uni=True)
pdf.set_font("Roboto", size=12) pdf.set_font("Roboto", size=12)
usable_w = pdf.w - 2 * pdf.l_margin usable_w = pdf.w - 2 * pdf.l_margin
width = usable_w / 7 width = usable_w / 7
height = pdf.font_size * 2 height = pdf.font_size * 2
LINE_HEIGHT = 5 LINE_HEIGHT = 5
# table head # table head
for column in COLUMNS: for column in COLUMNS:
if column == PUB_DATE: if column == PUB_DATE:
col_width = width * 2 col_width = width * 2
else: else:
col_width = width col_width = width
pdf.cell(col_width, height, column, border=1) pdf.cell(col_width, height, column, border=1)
pdf.ln(height) pdf.ln(height)
# table contents # table contents
for _ in range(5): for _ in range(5):
rand_num = randint(2, len(data)) rand_num = randint(2, len(data))
for column in COLUMNS: for column in COLUMNS:
if column == PUB_DATE: if column == PUB_DATE:
col_width = width * 2 col_width = width * 2
else: else:
col_width = width col_width = width
pdf.cell(col_width, height, str(data[column].iloc[rand_num]), border=1) pdf.cell(col_width, height, str(
pdf.ln(height) data[column].iloc[rand_num]), border=1)
pdf.ln(height)
pdf.ln(height) pdf.ln(height)
pdf.image(f"{output_path}/korelacija.png", w=usable_w) # corr graph pdf.image(f"{output_path}/korelacija.png", w=usable_w) # corr graph
pdf.write(LINE_HEIGHT, "Starp istabu skaitu un cenu, kvadratūru un cenu ir liela korelācija.") pdf.write(
pdf.ln(height) LINE_HEIGHT, "Starp istabu skaitu un cenu, kvadratūru un cenu ir liela korelācija.")
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph pdf.ln(height)
pdf.image(f"{output_path}/cenu_grafiki.png", w=usable_w) # price graph
# price graph conclusions # price graph conclusions
text = """ text = """
"Price to floor" grafiks - lielākā daļa pārdodamo dzīvokļu ir līdz 6. stāvam. "Price to floor" grafiks - lielākā daļa pārdodamo dzīvokļu ir līdz 6. stāvam.
"Price to room amount" grafiks - veido normālo sadalījumu (Gausa sadalījumu). "Price to room amount" grafiks - veido normālo sadalījumu (Gausa sadalījumu).
"Price to quadrature" grafiks - jo lielāka dzīvokļa platība, jo dārgāks dzīvoklis. "Price to quadrature" grafiks - jo lielāka dzīvokļa platība, jo dārgāks dzīvoklis.
"Price to series" grafiks - jaunie, renovētie un pēc kara dzīvokļi ir dārgāki. "Price to series" grafiks - jaunie, renovētie un pēc kara dzīvokļi ir dārgāki.
"Price to date" grafiks - nav nekādas sakarības. "Price to date" grafiks - nav nekādas sakarības.
""" """
for txt in text.split("\n"): for txt in text.split("\n"):
pdf.write(LINE_HEIGHT, txt.strip()) pdf.write(LINE_HEIGHT, txt.strip())
pdf.ln(LINE_HEIGHT) pdf.ln(LINE_HEIGHT)
# mean/mode values # mean/mode values
text = [ text = [
"Vidējā cena: ", "Vidējā cena attiecībā pret kvadratūru: ", "Sērijas moda: ", "Vidējā cena attiecībā pret istabu skaitu: ", "Vidējā cena: ", "Vidējā cena attiecībā pret kvadratūru: ", "Sērijas moda: ", "Vidējā cena attiecībā pret istabu skaitu: ",
"Vidējā cena attiecībā pret stāvu: " "Vidējā cena attiecībā pret stāvu: "
] ]
values = [ values = [
round(mean(data[PRICE]), 2), round(mean(data[PRICE]), 2),
round(mean(data[PRICE]) / mean(data[QUADRATURE])), round(mean(data[PRICE]) / mean(data[QUADRATURE])),
mode(data[SERIES]), mode(data[SERIES]),
round(mean(data[PRICE]) / mean(data[ROOM_AMOUNT])), round(mean(data[PRICE]) / mean(data[ROOM_AMOUNT])),
round(mean(data[PRICE]) / mean(data[FLOOR])) round(mean(data[PRICE]) / mean(data[FLOOR]))
] ]
for txt, value in zip(text, values): for txt, value in zip(text, values):
pdf.write(LINE_HEIGHT, f"{txt}{value}") pdf.write(LINE_HEIGHT, f"{txt}{value}")
pdf.ln(LINE_HEIGHT) pdf.ln(LINE_HEIGHT)
# adds photo of most frequent series # adds photo of most frequent series
response = requests.get(series_photos[mode(data[SERIES])]) response = requests.get(series_photos[mode(data[SERIES])])
img = Image.open(BytesIO(response.content)) img = Image.open(BytesIO(response.content))
pdf.image(img) pdf.image(img)
pdf.output("output/pdf/secinajumi.pdf") pdf.output("output/pdf/secinajumi.pdf")
def make_dir(): def make_dir():
if "output" not in listdir(): if "output" not in listdir():
mkdir("output") mkdir("output")
if "excel" not in listdir("output"): if "excel" not in listdir("output"):
mkdir("output/excel") mkdir("output/excel")
if "graphs" not in listdir("output"): if "graphs" not in listdir("output"):
mkdir("output/graphs") mkdir("output/graphs")
if "pdf" not in listdir("output"): if "pdf" not in listdir("output"):
mkdir("output/pdf") mkdir("output/pdf")
def graph_plot(): def graph_plot():
data = read() data = read()
graph_corr(data) graph_corr(data)
graph_price(data) graph_price(data)
create_pdf(data) create_pdf(data)
flats_riga = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga") flats_riga = SS(
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg") "https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle") flats_rigareg = SS(
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums") "https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre") flats_aizkraukle = SS(
"https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS(
"https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS(
"https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
OPERATIONS = """ OPERATIONS = """
python pd_pandas_k_f_cagulis.py python pd_pandas_k_f_cagulis.py
@ -245,15 +261,15 @@ Operations:
def main(argv): def main(argv):
for arg in argv: for arg in argv:
if arg in ["-h", "--help"]: if arg in ["-h", "--help"]:
print(OPERATIONS) print(OPERATIONS)
exit() exit()
elif arg in ["-n", "--new"]: elif arg in ["-n", "--new"]:
flats_riga.get_data() flats_riga.get_data()
make_dir() make_dir()
graph_plot() graph_plot()
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv[1:]) main(sys.argv[1:])

View File

@ -17,94 +17,110 @@ HEADERS = {
class SS: class SS:
def __init__(self, url, name): def __init__(self, url, name):
self.url = url self.url = url
self.name = name self.name = name
def _get_page_amount(self): def _get_page_amount(self):
page = requests.get(self.url, headers=HEADERS) page = requests.get(self.url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
try: try:
last_url = soup.find(class_='td2').findChild('a')['href'] last_url = soup.find(class_='td2').findChild('a')['href']
page_amount = last_url[last_url.find("page") + 4:last_url.find(".html")] page_amount = last_url[last_url.find(
except: "page") + 4:last_url.find(".html")]
page_amount = 1 except:
# print(f"Page amount = {page_amount}") page_amount = 1
# print(f"Page amount = {page_amount}")
return int(page_amount) return int(page_amount)
def get_data(self): def get_data(self):
items = [] items = []
item_no = 1 item_no = 1
page_amount = self._get_page_amount() page_amount = self._get_page_amount()
# widgets = ["Getting data...", pbar.Bar("*")] # widgets = ["Getting data...", pbar.Bar("*")]
# bar = pbar.ProgressBar(max_value=page_amount, widgets=widgets).start() # bar = pbar.ProgressBar(max_value=page_amount, widgets=widgets).start()
bar = LoadBar(max=page_amount * 30, head="#", body="#") bar = LoadBar(max=page_amount * 30, head="#", body="#")
bar.start() bar.start()
for page_number in range(1, page_amount + 1): for page_number in range(1, page_amount + 1):
url = self.url + f"/page{page_number}.html" url = self.url + f"/page{page_number}.html"
page = requests.get(url, headers=HEADERS) page = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(page.content, 'html.parser') soup = BeautifulSoup(page.content, 'html.parser')
# item ids # item ids
ids = [tag['id'] for tag in soup.select('tr[id]')] # creates list with ids ids = [tag['id']
ids = [x for x in ids if "tr_bnr" not in x] # removes "tr_bnr" elements from list for tag in soup.select('tr[id]')] # creates list with ids
ids.remove("head_line") # removes first "head_line" id # removes "tr_bnr" elements from list
# print(f"Page {page_number}") ids = [x for x in ids if "tr_bnr" not in x]
ids.remove("head_line") # removes first "head_line" id
# print(f"Page {page_number}")
# getting item data # getting item data
for id in soup.find_all(id=ids): for id in soup.find_all(id=ids):
# print(f"Item {item_no}") # print(f"Item {item_no}")
bar.update(step=item_no) bar.update(step=item_no)
item_no += 1 item_no += 1
for elem in id.find_all(class_='msga2-o pp6'): for elem in id.find_all(class_='msga2-o pp6'):
items.append(elem.get_text()) items.append(elem.get_text())
if len(id.find_all(class_='msga2-o pp6')) == 7: if len(id.find_all(class_='msga2-o pp6')) == 7:
del items[-2] del items[-2]
# adverts url # adverts url
item_url = id.findChild(class_='msg2').findChild('div').findChild('a')['href'] # gets url item_url = id.findChild(class_='msg2').findChild(
item_url = "https://www.ss.com" + item_url 'div').findChild('a')['href'] # gets url
item_page = requests.get(item_url, headers=HEADERS) item_url = "https://www.ss.com" + item_url
item_soup = BeautifulSoup(item_page.content, 'html.parser') item_page = requests.get(item_url, headers=HEADERS)
item_soup = BeautifulSoup(item_page.content, 'html.parser')
# adverts full text # adverts full text
item_text = item_soup.find(id='msg_div_msg').get_text() # gets full text item_text = item_soup.find(
item_text = item_text[:item_text.find("Pilsēta:")] # removes text last part (table) id='msg_div_msg').get_text() # gets full text
items.append(item_text) # removes text last part (table)
item_text = item_text[:item_text.find("Pilsēta:")]
items.append(item_text)
# adverts publication date # adverts publication date
item_date = item_soup.find_all('td', class_='msg_footer') # gets all 'msg_footer' class' # gets all 'msg_footer' class'
item_date = item_date[2].get_text() # extracts 3rd element item_date = item_soup.find_all('td', class_='msg_footer')
items.append(item_date[8:18]) # crops date item_date = item_date[2].get_text() # extracts 3rd element
bar.end() items.append(item_date[8:18]) # crops date
chunk_size = 8 bar.end()
chunked_items_list = [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] # combines each 'chunk_size' elements into array chunk_size = 8
columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs", "Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"] # combines each 'chunk_size' elements into array
df = pd.DataFrame(chunked_items_list, columns=columns) chunked_items_list = [items[i:i + chunk_size]
time = datetime.now().strftime("%d%m%y%H%M%S") # current time for i in range(0, len(items), chunk_size)]
if "excel" not in listdir("output"): columns = ["Atrašanās vieta", "Istabu skaits", "Kvadratūra", "Stāvs",
mkdir("output/excel") "Sērija", "Cena", "Pilns sludinājuma teksts", "Izvietošanas datums"]
df.to_excel(excel_writer=f"output/excel/ss_{self.name}_{time}.xlsx", index=False) df = pd.DataFrame(chunked_items_list, columns=columns)
time = datetime.now().strftime("%d%m%y%H%M%S") # current time
if "excel" not in listdir("output"):
mkdir("output/excel")
df.to_excel(
excel_writer=f"output/excel/ss_{self.name}_{time}.xlsx", index=False)
flats_riga = SS("https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga") flats_riga = SS(
flats_rigareg = SS("https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg") "https://www.ss.com/lv/real-estate/flats/riga/all/sell/", "riga")
flats_aizkraukle = SS("https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle") flats_rigareg = SS(
flats_tukums = SS("https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums") "https://www.ss.com/lv/real-estate/flats/riga-region/all/sell/", "rigareg")
flats_ogre = SS("https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre") flats_aizkraukle = SS(
"https://www.ss.com/lv/real-estate/flats/aizkraukle-and-reg/sell/", "aizkraukle")
flats_tukums = SS(
"https://www.ss.com/lv/real-estate/flats/tukums-and-reg/sell/", "tukums")
flats_ogre = SS(
"https://www.ss.com/lv/real-estate/flats/ogre-and-reg/sell/", "ogre")
def main(): def main():
flats_riga.get_data() flats_riga.get_data()
# flats_rigareg.get_data() # flats_rigareg.get_data()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -7,24 +7,24 @@ import pandas as pd
def main(): def main():
print(consuption(6.7, 2500)) print(consuption(6.7, 2500))
def try_except(): def try_except():
try: try:
# print(error) # "Name Error" # print(error) # "Name Error"
data = pd.read_csv("auto_imports_mainits.csx") # "Error 2" data = pd.read_csv("auto_imports_mainits.csx") # "Error 2"
except NameError: except NameError:
print("Name Error") print("Name Error")
except Exception as error: except Exception as error:
print(error) print(error)
except: except:
print("Error 2") print("Error 2")
if __name__ == '__main__': if __name__ == '__main__':
# main() # main()
try_except() try_except()

View File

@ -6,13 +6,13 @@ import pandas as pd
def main(): def main():
data = pd.read_csv("auto_imports_mainits.csv") data = pd.read_csv("auto_imports_mainits.csv")
blank = data.isnull().any().sum() blank = data.isnull().any().sum()
print(f"There are empty spaces in {blank} columns") print(f"There are empty spaces in {blank} columns")
print(data.isnull().sum()) print(data.isnull().sum())
print(data.columns[data.isnull().any()]) print(data.columns[data.isnull().any()])
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -3,4 +3,6 @@ import pandas
dati = pandas.read_csv('auto_imports_mainits.csv') dati = pandas.read_csv('auto_imports_mainits.csv')
for index, element in enumerate(dati.isnull().sum()): for index, element in enumerate(dati.isnull().sum()):
if element != 0: print(f"| {dati.columns[index]}" + " " * (25 - len(str(dati.columns[index]))) + f"{element}") if element != 0:
print(f"| {dati.columns[index]}" + " " * (25 -
len(str(dati.columns[index]))) + f"{element}")

View File

@ -1,11 +1,11 @@
def consuption(consuption: float, distance: int, price: float = 1.34): def consuption(consuption: float, distance: int, price: float = 1.34):
result = distance / 100 * consuption * price result = distance / 100 * consuption * price
return round(result, 3) return round(result, 3)
def main(): def main():
print(consuption(7.2, 7200)) print(consuption(7.2, 7200))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -6,17 +6,18 @@ import pandas as pd
def main(): def main():
data = pd.read_csv("auto_imports_mainits.csv") data = pd.read_csv("auto_imports_mainits.csv")
# 1st method # 1st method
for column in data.columns: for column in data.columns:
if data[column].isnull().sum() > 0: if data[column].isnull().sum() > 0:
print(f"{column} {data[column].isnull().sum()}") print(f"{column} {data[column].isnull().sum()}")
print("-" * 22) print("-" * 22)
# 2nd method # 2nd method
print(pd.DataFrame(data.isnull().sum(), data.columns[data.isnull().any()]).to_string(header=None)) print(pd.DataFrame(data.isnull().sum(),
data.columns[data.isnull().any()]).to_string(header=None))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -7,75 +7,76 @@ from word2number import w2n
def main(): def main():
data = pd.read_csv("auto_imports_mainits.csv") data = pd.read_csv("auto_imports_mainits.csv")
# summary = data["normalized-losses"].notnull() # returns boolean # summary = data["normalized-losses"].notnull() # returns boolean
# print(data[summary], "\n") # "normalized-losses" is not empty # print(data[summary], "\n") # "normalized-losses" is not empty
# print(data[~summary]) # inverts all the bits # print(data[~summary]) # inverts all the bits
# print(len(data[~summary])) # print(len(data[~summary]))
data_copy = data.copy() data_copy = data.copy()
# Delete rows with empty spots # Delete rows with empty spots
# print(f"Before erasing: {data_copy.shape}") # print(f"Before erasing: {data_copy.shape}")
# print(f"After erasing: {data_copy.dropna().shape}") # print(f"After erasing: {data_copy.dropna().shape}")
# Delete column # Delete column
# print(f"Before erasing: {data_copy.shape}") # print(f"Before erasing: {data_copy.shape}")
del data_copy["normalized-losses"] del data_copy["normalized-losses"]
# print(f"After erasing: {data_copy.shape}") # print(f"After erasing: {data_copy.shape}")
# print(f"Blank spots: {data_copy.isnull().any().sum()}") # print(f"Blank spots: {data_copy.isnull().any().sum()}")
# data_copy2 = data_copy.copy() # data_copy2 = data_copy.copy()
# print(data_copy2.head()) # print(data_copy2.head())
# data_copy2.drop(data_copy2.columns[[0, 1]], axis=1, inplace=True) # data_copy2.drop(data_copy2.columns[[0, 1]], axis=1, inplace=True)
# print(data_copy2.head()) # print(data_copy2.head())
dislike = ["N/A", "NA", "--"] dislike = ["N/A", "NA", "--"]
data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike) data_copy3 = pd.read_csv("auto_imports_mainits.csv", na_values=dislike)
# Mean # Mean
# print(data_copy3.iloc[52], "\n") # print(data_copy3.iloc[52], "\n")
# mean = data_copy3["bore"].mean() # mean = data_copy3["bore"].mean()
# data_copy3["bore"].fillna(mean, inplace=True) # data_copy3["bore"].fillna(mean, inplace=True)
# print(data_copy3.iloc[52]) # print(data_copy3.iloc[52])
# Median # Median
# print(data_copy3.iloc[53], "\n") # print(data_copy3.iloc[53], "\n")
# median = data_copy3["bore"].median() # median = data_copy3["bore"].median()
# data_copy3["bore"].fillna(median, inplace=True) # data_copy3["bore"].fillna(median, inplace=True)
# print(data_copy3.iloc[53]) # print(data_copy3.iloc[53])
# Mode # Mode
# print(data_copy3.iloc[60], "\n") # print(data_copy3.iloc[60], "\n")
# mode = data_copy3["bore"].mode() # mode = data_copy3["bore"].mode()
# data_copy3["bore"].fillna(mode, inplace=True) # data_copy3["bore"].fillna(mode, inplace=True)
# print(data_copy3.iloc[60]) # print(data_copy3.iloc[60])
# print(data_copy3.dtypes) # print(data_copy3.dtypes)
# data_copy3["curb-weight"] = pd.to_numeric(data_copy3["curb-weight"], errors='coerce') # data_copy3["curb-weight"] = pd.to_numeric(data_copy3["curb-weight"], errors='coerce')
# data_copy3["curb-weight"] = data_copy3["curb-weight"].astype("float64") # data_copy3["curb-weight"] = data_copy3["curb-weight"].astype("float64")
# print(data_copy3.dtypes) # print(data_copy3.dtypes)
# Replaces word written numbers to intigers # Replaces word written numbers to intigers
columns = ["num-of-doors", "num-of-cylinders"] columns = ["num-of-doors", "num-of-cylinders"]
for column in columns: for column in columns:
for value in data_copy3[column]: for value in data_copy3[column]:
try: try:
data_copy3 = data_copy3.replace(to_replace=value, value=w2n.word_to_num(value)) data_copy3 = data_copy3.replace(
print(type(w2n.word_to_num(value))) to_replace=value, value=w2n.word_to_num(value))
except: print(type(w2n.word_to_num(value)))
pass except:
print(data_copy3[["num-of-doors", "num-of-cylinders"]]) pass
print(data_copy3[["num-of-doors", "num-of-cylinders"]])
# Leaves only columns that contain numbers # Leaves only columns that contain numbers
data_copy4 = data_copy3.copy() data_copy4 = data_copy3.copy()
for column in data_copy4: for column in data_copy4:
if isinstance(data_copy4[column][0], str): if isinstance(data_copy4[column][0], str):
del data_copy4[column] del data_copy4[column]
print(data_copy4) print(data_copy4)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -7,38 +7,42 @@ CHAPTERS = 61
# creates file with chapters and row numbers # creates file with chapters and row numbers
def read_array(document): def read_array(document):
with open(document, "r", encoding='utf-8') as book: with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n') for line in book] # removes 'enter' characters lines = [line.strip('\n')
with open('array_output.txt', 'w') as output: for line in book] # removes 'enter' characters
for i in range(1, CHAPTERS + 1): with open('array_output.txt', 'w') as output:
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines for i in range(1, CHAPTERS + 1):
output.write(f"Line {line} - Chapter {i}\n") # writes line in file # finds all chapter indexes/lines
line = lines.index(f"Chapter {i}") + 1
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
# creates file with chapter positions # creates file with chapter positions
def read_string(document): def read_string(document):
with open(document, "r", encoding='utf-8') as book: with open(document, "r", encoding='utf-8') as book:
lines = book.read() lines = book.read()
with open('str_output.txt', 'w') as output: with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1): for i in range(1, CHAPTERS + 1):
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions # finds all chapter positions
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file _, position = re.finditer(rf"\bChapter {i}\b", lines)
# writes position in file
output.write(f"Position {position.start()} - Chapter {i}\n")
def read_book(document): def read_book(document):
read_array(document) read_array(document)
read_string(document) read_string(document)
def main(): def main():
try: try:
read_book("book.txt") read_book("book.txt")
except: except:
try: try:
read_book("1342-0.txt") read_book("1342-0.txt")
except: except:
read_book(input("Ievadiet faila nosaukumu: ")) read_book(input("Ievadiet faila nosaukumu: "))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -8,91 +8,95 @@ data = pd.read_csv("company_sales_data.csv")
def task_1(): def task_1():
plt.figure(figsize=(10, 6)) # (x, y) plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months x = range(len(data["month_number"])) # gets range of months
plt.plot(x, data["total_profit"]) # sets up the plot plt.plot(x, data["total_profit"]) # sets up the plot
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15) plt.yticks(fontsize=15)
plt.ylim(ymin=100000) # sets minimal y value plt.ylim(ymin=100000) # sets minimal y value
set_labels("Company profit per month", "Month number", "Total profit") set_labels("Company profit per month", "Month number", "Total profit")
plt.show() plt.show()
def task_2(): def task_2():
plt.figure(figsize=(10, 6)) # (x, y) plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months x = range(len(data["month_number"])) # gets range of months
data_list = list(data.columns)[1:-2] # gets and trims column names data_list = list(data.columns)[1:-2] # gets and trims column names
for column in data_list: for column in data_list:
plt.plot(x, data[column], lw=4, marker='o', ms=10) # ms = marker size plt.plot(x, data[column], lw=4, marker='o', ms=10) # ms = marker size
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15) plt.yticks(fontsize=15)
set_labels("Sales data", "Month number", "Sales units in number") set_labels("Sales data", "Month number", "Sales units in number")
new_data_list = list(map(lambda x: x.capitalize() + " Sales Data", data_list)) # capitalizes each word in list # capitalizes each word in list
plt.legend(new_data_list, loc='upper left', fontsize=15) new_data_list = list(
plt.show() map(lambda x: x.capitalize() + " Sales Data", data_list))
plt.legend(new_data_list, loc='upper left', fontsize=15)
plt.show()
def task_3(): def task_3():
plt.figure(figsize=(10, 6)) # (x, y) plt.figure(figsize=(10, 6)) # (x, y)
x = range(len(data["month_number"])) # gets range of months x = range(len(data["month_number"])) # gets range of months
plt.scatter(x, data["toothpaste"], s=75) # sets up the plot plt.scatter(x, data["toothpaste"], s=75) # sets up the plot
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
plt.xticks(x, data["month_number"], fontsize=15) # sets x value step plt.xticks(x, data["month_number"], fontsize=15) # sets x value step
plt.yticks(fontsize=15) plt.yticks(fontsize=15)
set_labels("Toothpaste Sales data", "Month number", "Number of units Sold") set_labels("Toothpaste Sales data", "Month number", "Number of units Sold")
plt.legend(["Toothpaste Sales data"], loc='upper left', fontsize=15) plt.legend(["Toothpaste Sales data"], loc='upper left', fontsize=15)
plt.show() plt.show()
def task_4(): def task_4():
items = ["facecream", "facewash"] items = ["facecream", "facewash"]
data.plot(x="month_number", y=["facecream", "facewash"], kind='bar', figsize=(10, 6), fontsize=15) data.plot(x="month_number", y=[
"facecream", "facewash"], kind='bar', figsize=(10, 6), fontsize=15)
plt.xticks(rotation=0) # rotates x lables to 0 plt.xticks(rotation=0) # rotates x lables to 0
plt.grid(ls='dashed', lw=1.5) # sets grid line type and width plt.grid(ls='dashed', lw=1.5) # sets grid line type and width
set_labels("Facewash and Facecream Sales data", "Month number", "Sales units in number") set_labels("Facewash and Facecream Sales data",
new_items_list = list(map(lambda x: x.capitalize() + " Sales Data", items)) "Month number", "Sales units in number")
plt.legend(new_items_list, loc='upper left', fontsize=15) new_items_list = list(map(lambda x: x.capitalize() + " Sales Data", items))
plt.show() plt.legend(new_items_list, loc='upper left', fontsize=15)
plt.show()
def set_labels(title: str, xlabel: str, ylabel: str): def set_labels(title: str, xlabel: str, ylabel: str):
plt.title(title, fontsize=15) plt.title(title, fontsize=15)
plt.xlabel(xlabel, fontsize=15) plt.xlabel(xlabel, fontsize=15)
plt.ylabel(ylabel, fontsize=15) plt.ylabel(ylabel, fontsize=15)
def main(): def main():
task = input("""Ivēlieties uzdevumu: task = input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums 1 - pirmais uzdevums
2 - otrais uzdevums 2 - otrais uzdevums
3 - trešais uzdevums 3 - trešais uzdevums
4 - ceturtais uzdevums 4 - ceturtais uzdevums
""") """)
if task == "1": if task == "1":
task_1() task_1()
elif task == "2": elif task == "2":
task_2() task_2()
elif task == "3": elif task == "3":
task_3() task_3()
elif task == "4": elif task == "4":
task_4() task_4()
else: else:
print("Tika ievadīts nepareiz cipars") print("Tika ievadīts nepareiz cipars")
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -8,37 +8,37 @@ url = "https://www.ikea.lv/"
all_page = requests.get(url) all_page = requests.get(url)
if all_page.status_code == 200: if all_page.status_code == 200:
page = BeautifulSoup(all_page.content, 'html.parser') page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find_all(class_="itemBlock") found = page.find_all(class_="itemBlock")
info = [] info = []
item_array = [] item_array = []
for item in found: for item in found:
item = item.findChild("div").findChild(class_="card-body") item = item.findChild("div").findChild(class_="card-body")
item_name = item.findChild(class_="itemName") item_name = item.findChild(class_="itemName")
item_name = item_name.findChild("div").findChild("h6") item_name = item_name.findChild("div").findChild("h6")
item_array.append(item_name.string) item_array.append(item_name.string)
price = item.findChild(class_="itemPrice-wrapper") price = item.findChild(class_="itemPrice-wrapper")
price = price.findChild("p").findChild("span") price = price.findChild("p").findChild("span")
try: try:
item_array.append(price.attrs["data-price"]) item_array.append(price.attrs["data-price"])
except: except:
item_array.append(price.attrs["data-pricefamily"]) item_array.append(price.attrs["data-pricefamily"])
all_facts = [] all_facts = []
for facts in all_facts: for facts in all_facts:
if len(facts) == 1: if len(facts) == 1:
all_facts.append(facts.string) all_facts.append(facts.string)
else: else:
atrasts = facts.findChildren("span") atrasts = facts.findChildren("span")
for i in atrasts: for i in atrasts:
all_facts.append(i.string) all_facts.append(i.string)
item_array.append(all_facts) item_array.append(all_facts)
info.append(item_array) info.append(item_array)
for ieraksts in info: for ieraksts in info:
print(ieraksts) print(ieraksts)

View File

@ -7,21 +7,22 @@ all_page = requests.get(url)
# print(all_page) # print(all_page)
if all_page.status_code == 200: if all_page.status_code == 200:
print(":)") print(":)")
page = BeautifulSoup(all_page.content, 'html.parser') page = BeautifulSoup(all_page.content, 'html.parser')
found = page.find(id="Etymology") found = page.find(id="Etymology")
# print(found) # print(found)
# print(found.constents) # print(found.constents)
# print(found.string) # print(found.string)
found = page.find_all(class_="mw-headline") found = page.find_all(class_="mw-headline")
# print(found) # print(found)
found = page.find_all("li", class_="interlanguage-link") found = page.find_all("li", class_="interlanguage-link")
# print(found) # print(found)
found = page.find_all("a", class_="interlanguage-link-target") found = page.find_all("a", class_="interlanguage-link-target")
# print(found) # print(found)
for i in found: for i in found:
# print(i.prettify()) # print(i.prettify())
if i.attrs["lang"] == "ru": if i.attrs["lang"] == "ru":
print(f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}") print(
f"{i.attrs['lang']} \t {i.attrs['title']} \n {i.attrs['href']}")
else: else:
print(":(") print(":(")

View File

@ -7,38 +7,42 @@ CHAPTERS = 61
# creates file with chapters and row numbers # creates file with chapters and row numbers
def read_array(document): def read_array(document):
with open(document, "r", encoding='utf-8') as book: with open(document, "r", encoding='utf-8') as book:
lines = [line.strip('\n') for line in book] # removes 'enter' characters lines = [line.strip('\n')
with open('array_output.txt', 'w') as output: for line in book] # removes 'enter' characters
for i in range(1, CHAPTERS + 1): with open('array_output.txt', 'w') as output:
line = lines.index(f"Chapter {i}") + 1 # finds all chapter indexes/lines for i in range(1, CHAPTERS + 1):
output.write(f"Line {line} - Chapter {i}\n") # writes line in file # finds all chapter indexes/lines
line = lines.index(f"Chapter {i}") + 1
output.write(f"Line {line} - Chapter {i}\n") # writes line in file
# creates file with chapter positions # creates file with chapter positions
def read_string(document): def read_string(document):
with open(document, "r", encoding='utf-8') as book: with open(document, "r", encoding='utf-8') as book:
lines = book.read() lines = book.read()
with open('str_output.txt', 'w') as output: with open('str_output.txt', 'w') as output:
for i in range(1, CHAPTERS + 1): for i in range(1, CHAPTERS + 1):
_, position = re.finditer(rf"\bChapter {i}\b", lines) # finds all chapter positions # finds all chapter positions
output.write(f"Position {position.start()} - Chapter {i}\n") # writes position in file _, position = re.finditer(rf"\bChapter {i}\b", lines)
# writes position in file
output.write(f"Position {position.start()} - Chapter {i}\n")
def read_book(document): def read_book(document):
read_array(document) read_array(document)
read_string(document) read_string(document)
def main(): def main():
try: try:
read_book("book.txt") read_book("book.txt")
except: except:
try: try:
read_book("1342-0.txt") read_book("1342-0.txt")
except: except:
read_book(input("Ievadiet faila nosaukumu: ")) read_book(input("Ievadiet faila nosaukumu: "))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -5,182 +5,189 @@ from random import randrange
class Cube: class Cube:
def __init__(self, position, color=DARK_PURPLE) -> None: def __init__(self, position, color=DARK_PURPLE) -> None:
self.pos = position self.pos = position
self.direction = (1, 0) self.direction = (1, 0)
self.color = color self.color = color
def move(self, direction: tuple) -> None: def move(self, direction: tuple) -> None:
self.direction = direction self.direction = direction
self.pos = (self.pos[0] + self.direction[0], self.pos[1] + self.direction[1]) self.pos = (self.pos[0] + self.direction[0],
self.pos[1] + self.direction[1])
def draw(self, eyes=False) -> None: def draw(self, eyes=False) -> None:
distance = WIDTH // ROWS distance = WIDTH // ROWS
i, j = self.pos i, j = self.pos
pygame.draw.rect(WINDOW, self.color, (i * distance + 1, j * distance + 1, distance - 2, distance - 2)) pygame.draw.rect(WINDOW, self.color, (i * distance + 1,
if eyes: j * distance + 1, distance - 2, distance - 2))
center = distance // 2 if eyes:
radius = 3 center = distance // 2
circle_middle = (i * distance + center - radius, j * distance + 8) radius = 3
circle_middle_2 = (i * distance + distance - radius * 2, j * distance + 8) circle_middle = (i * distance + center - radius, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius) circle_middle_2 = (i * distance + distance -
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius) radius * 2, j * distance + 8)
pygame.draw.circle(WINDOW, BLACK, circle_middle, radius)
pygame.draw.circle(WINDOW, BLACK, circle_middle_2, radius)
class Snake: class Snake:
def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None: def __init__(self, position: tuple, color: tuple, name: str, player_number: int = 1, multiplayer: bool = False) -> None:
self.color = color self.color = color
self.head = Cube(position, self.color) self.head = Cube(position, self.color)
self.body = [] self.body = []
self.body.append(self.head) self.body.append(self.head)
self.turns = {} self.turns = {}
self.direction = (1, 0) self.direction = (1, 0)
self.number = player_number self.number = player_number
self.name = name self.name = name
self.multiplayer = multiplayer self.multiplayer = multiplayer
def move(self) -> None: def move(self) -> None:
keys = pygame.key.get_pressed() keys = pygame.key.get_pressed()
if self.multiplayer: if self.multiplayer:
num_1, num_2 = 1, 2 num_1, num_2 = 1, 2
else: else:
num_1, num_2 = 1, 1 num_1, num_2 = 1, 1
if self.number == num_1: if self.number == num_1:
if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left if keys[pygame.K_LEFT] and self.direction != (1, 0): # turn left
self.direction = -1, 0 self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_RIGHT] and self.direction != (-1, 0): # turn right # turn right
self.direction = 1, 0 if keys[pygame.K_RIGHT] and self.direction != (-1, 0):
self.turns[self.head.pos[:]] = self.direction self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_UP] and self.direction != (0, 1): # turn up if keys[pygame.K_UP] and self.direction != (0, 1): # turn up
self.direction = 0, -1 self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down if keys[pygame.K_DOWN] and self.direction != (0, -1): # turn down
self.direction = 0, 1 self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if self.number == num_2: if self.number == num_2:
if keys[pygame.K_a] and self.direction != (1, 0): # turn left if keys[pygame.K_a] and self.direction != (1, 0): # turn left
self.direction = -1, 0 self.direction = -1, 0
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_d] and self.direction != (-1, 0): # turn right if keys[pygame.K_d] and self.direction != (-1, 0): # turn right
self.direction = 1, 0 self.direction = 1, 0
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_w] and self.direction != (0, 1): # turn up if keys[pygame.K_w] and self.direction != (0, 1): # turn up
self.direction = 0, -1 self.direction = 0, -1
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
if keys[pygame.K_s] and self.direction != (0, -1): # turn down if keys[pygame.K_s] and self.direction != (0, -1): # turn down
self.direction = 0, 1 self.direction = 0, 1
self.turns[self.head.pos[:]] = self.direction self.turns[self.head.pos[:]] = self.direction
for index, head in enumerate(self.body): for index, head in enumerate(self.body):
head_pos = head.pos[:] head_pos = head.pos[:]
if head_pos in self.turns: if head_pos in self.turns:
turn = self.turns[head_pos] turn = self.turns[head_pos]
head.move((turn[0], turn[1])) head.move((turn[0], turn[1]))
if index == len(self.body) - 1: if index == len(self.body) - 1:
self.turns.pop(head_pos) self.turns.pop(head_pos)
else: else:
from globals import walls from globals import walls
from snake import end_screen from snake import end_screen
if walls: # end game if goes into the wall if walls: # end game if goes into the wall
head.move(head.direction) head.move(head.direction)
if head.direction[0] == -1 and head.pos[0] < 0: # left to right if head.direction[0] == -1 and head.pos[0] < 0: # left to right
end_screen() end_screen()
if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left if head.direction[0] == 1 and head.pos[0] >= ROWS: # right to left
end_screen() end_screen()
if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top if head.direction[1] == 1 and head.pos[1] >= COLUMNS: # bottom to top
end_screen() end_screen()
if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom if head.direction[1] == -1 and head.pos[1] < 0: # top to bottom
end_screen() end_screen()
else: # move player to other screen size else: # move player to other screen size
if head.direction[0] == -1 and head.pos[0] <= 0: # left to right if head.direction[0] == -1 and head.pos[0] <= 0: # left to right
head.pos = (ROWS - 1, head.pos[1]) head.pos = (ROWS - 1, head.pos[1])
elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left elif head.direction[0] == 1 and head.pos[0] >= ROWS - 1: # right to left
head.pos = (0, head.pos[1]) head.pos = (0, head.pos[1])
elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1: # bottom to top # bottom to top
head.pos = (head.pos[0], 0) elif head.direction[1] == 1 and head.pos[1] >= COLUMNS - 1:
head.pos = (head.pos[0], 0)
elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom elif head.direction[1] == -1 and head.pos[1] <= 0: # top to bottom
head.pos = (head.pos[0], COLUMNS - 1) head.pos = (head.pos[0], COLUMNS - 1)
else: else:
head.move(head.direction) head.move(head.direction)
def add_cube(self) -> None: def add_cube(self) -> None:
tail = self.body[-1] tail = self.body[-1]
if tail.direction == (1, 0): if tail.direction == (1, 0):
self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color)) self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]), self.color))
elif tail.direction == (-1, 0): elif tail.direction == (-1, 0):
self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color)) self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]), self.color))
elif tail.direction == (0, 1): elif tail.direction == (0, 1):
self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color)) self.body.append(Cube((tail.pos[0], tail.pos[1] - 1), self.color))
elif tail.direction == (0, -1): elif tail.direction == (0, -1):
self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color)) self.body.append(Cube((tail.pos[0], tail.pos[1] + 1), self.color))
self.body[-1].direction = tail.direction self.body[-1].direction = tail.direction
def remove_cube(self) -> None: def remove_cube(self) -> None:
self.body.pop(-1) self.body.pop(-1)
def draw(self) -> None: def draw(self) -> None:
for index, head in enumerate(self.body): for index, head in enumerate(self.body):
if index == 0: if index == 0:
head.draw(eyes=True) head.draw(eyes=True)
else: else:
head.draw() head.draw()
class Snack: class Snack:
def __init__(self, texture) -> None: def __init__(self, texture) -> None:
self.texture = texture self.texture = texture
self.randomize() self.randomize()
def draw_snack(self) -> None: def draw_snack(self) -> None:
snack_rect = pygame.Rect(self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE) snack_rect = pygame.Rect(
WINDOW.blit(self.texture, snack_rect) self.pos[0] * CELL_SIZE, self.pos[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
WINDOW.blit(self.texture, snack_rect)
def randomize(self) -> None: def randomize(self) -> None:
self.pos = (randrange(ROWS), randrange(COLUMNS)) self.pos = (randrange(ROWS), randrange(COLUMNS))
class Button(): class Button():
def __init__(self, position, text, font_size, base_color, hover_color) -> None: def __init__(self, position, text, font_size, base_color, hover_color) -> None:
self.pos = position self.pos = position
self.font = set_font(font_size) self.font = set_font(font_size)
self.base_color = base_color self.base_color = base_color
self.hover_color = hover_color self.hover_color = hover_color
self.text = text self.text = text
self.text_rect = self.font.render(self.text, 1, self.base_color).get_rect(center=(self.pos)) self.text_rect = self.font.render(
self.text, 1, self.base_color).get_rect(center=(self.pos))
def update(self) -> None: def update(self) -> None:
WINDOW.blit(self.text, self.text_rect) WINDOW.blit(self.text, self.text_rect)
def check_input(self, mouse_pos) -> bool: def check_input(self, mouse_pos) -> bool:
if mouse_pos[0] in range(self.text_rect.left, self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): if mouse_pos[0] in range(self.text_rect.left, self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom):
return True return True
return False return False
def change_color(self, mouse_pos) -> None: def change_color(self, mouse_pos) -> None:
if mouse_pos[0] in range(self.text_rect.left, if mouse_pos[0] in range(self.text_rect.left,
self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): # on hover self.text_rect.right) and mouse_pos[1] in range(self.text_rect.top, self.text_rect.bottom): # on hover
self.text = self.font.render(self.text, 1, self.hover_color) self.text = self.font.render(self.text, 1, self.hover_color)
else: else:
self.text = self.font.render(self.text, 1, self.base_color) self.text = self.font.render(self.text, 1, self.base_color)

View File

@ -11,178 +11,225 @@ color_index = [0, 1]
def main_menu() -> None: def main_menu() -> None:
pygame.display.set_caption("Snake - Menu") pygame.display.set_caption("Snake - Menu")
while True: while True:
WINDOW.fill(BLACK) WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos() mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render("SNAKE GAME", 1, WHITE) menu_text = set_font(100).render("SNAKE GAME", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125)) menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect) WINDOW.blit(menu_text, menu_rect)
play_button = Button((MID_WIDTH, MID_HEIGHT - 50), "PLAY", 75, GRAY, WHITE) play_button = Button((MID_WIDTH, MID_HEIGHT - 50),
options_button = Button((MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE) "PLAY", 75, GRAY, WHITE)
score_button = Button((MID_WIDTH, MID_HEIGHT + 150), "SCORE", 75, GRAY, WHITE) options_button = Button(
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250), "QUIT", 75, GRAY, WHITE) (MID_WIDTH, MID_HEIGHT + 50), "OPTIONS", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button] score_button = Button((MID_WIDTH, MID_HEIGHT + 150),
"SCORE", 75, GRAY, WHITE)
quit_button = Button((MID_WIDTH, MID_HEIGHT + 250),
"QUIT", 75, GRAY, WHITE)
buttons = [play_button, options_button, score_button, quit_button]
on_hover(buttons) on_hover(buttons)
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: quit() if event.type == pygame.QUIT:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: quit()
if play_button.check_input(mouse_pos): user_input(0) if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if options_button.check_input(mouse_pos): options() if play_button.check_input(mouse_pos):
if score_button.check_input(mouse_pos): scoreboard() user_input(0)
if quit_button.check_input(mouse_pos): quit() if options_button.check_input(mouse_pos):
options()
if score_button.check_input(mouse_pos):
scoreboard()
if quit_button.check_input(mouse_pos):
quit()
pygame.display.update() pygame.display.update()
def user_input(player: int) -> None: def user_input(player: int) -> None:
from snake import main from snake import main
global user_name global user_name
global color_index global color_index
pygame.display.set_caption("Snake") pygame.display.set_caption("Snake")
select_active = True select_active = True
outline_color = WHITE outline_color = WHITE
name_rect_w = 140 name_rect_w = 140
while True: while True:
from globals import multiplayer from globals import multiplayer
WINDOW.fill(BLACK) WINDOW.fill(BLACK)
mouse_pos = pygame.mouse.get_pos() mouse_pos = pygame.mouse.get_pos()
menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE) menu_text = set_font(100).render(f"PLAYER {player + 1}", 1, WHITE)
menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125)) menu_rect = menu_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(menu_text, menu_rect) WINDOW.blit(menu_text, menu_rect)
back_button = Button((130, WINDOW_HEIGHT - 50), "BACK", 75, GRAY, WHITE) back_button = Button((130, WINDOW_HEIGHT - 50),
if multiplayer and player == 0: "BACK", 75, GRAY, WHITE)
next_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE) if multiplayer and player == 0:
buttons = [back_button, next_button] next_button = Button(
else: (WIDTH - 130, WINDOW_HEIGHT - 50), "NEXT", 75, GRAY, WHITE)
play_button = Button((WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE) buttons = [back_button, next_button]
buttons = [back_button, play_button] else:
play_button = Button(
(WIDTH - 130, WINDOW_HEIGHT - 50), "PLAY", 75, GRAY, WHITE)
buttons = [back_button, play_button]
on_hover(buttons) on_hover(buttons)
name_rect = pygame.Rect(MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32) name_rect = pygame.Rect(
pygame.draw.rect(WINDOW, outline_color, name_rect, 2) MID_WIDTH - name_rect_w / 2, 200, name_rect_w, 32)
user_text = set_font(20).render(user_name[player], 1, WHITE) pygame.draw.rect(WINDOW, outline_color, name_rect, 2)
WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5)) user_text = set_font(20).render(user_name[player], 1, WHITE)
name_rect_w = max(140, user_text.get_width() + 10) WINDOW.blit(user_text, (name_rect.x + 5, name_rect.y + 5))
name_rect_w = max(140, user_text.get_width() + 10)
color = COLORS[color_index[player]] color = COLORS[color_index[player]]
color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100) color_rect = pygame.Rect(MID_WIDTH - 50, 350, 100, 100)
pygame.draw.rect(WINDOW, color, color_rect) pygame.draw.rect(WINDOW, color, color_rect)
if select_active: outline_color = WHITE if select_active:
else: outline_color = DARK_GRAY outline_color = WHITE
else:
outline_color = DARK_GRAY
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: quit() if event.type == pygame.QUIT:
quit()
if event.type == pygame.MOUSEBUTTONDOWN: if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: if event.button == 1:
if name_rect.collidepoint(event.pos): select_active = True if name_rect.collidepoint(event.pos):
else: select_active = False select_active = True
else:
select_active = False
if back_button.check_input(mouse_pos): main_menu() if back_button.check_input(mouse_pos):
if multiplayer and player == 0: main_menu()
if next_button.check_input(mouse_pos): user_input(1) if multiplayer and player == 0:
else: if next_button.check_input(mouse_pos):
if play_button.check_input(mouse_pos): main() user_input(1)
if color_rect.collidepoint(event.pos): else:
color_index[player] += 1 if play_button.check_input(mouse_pos):
if color_index[player] == len(COLORS) - 1: main()
color_index[player] = 0 if color_rect.collidepoint(event.pos):
color_index[player] += 1
if color_index[player] == len(COLORS) - 1:
color_index[player] = 0
if event.button == 3: # clear user name on mouse right click if event.button == 3: # clear user name on mouse right click
if name_rect.collidepoint(event.pos): user_name[player] = "" if name_rect.collidepoint(event.pos):
user_name[player] = ""
if event.type == pygame.KEYDOWN: if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: main_menu() if event.key == pygame.K_ESCAPE:
main_menu()
if select_active: if select_active:
if event.key == pygame.K_BACKSPACE: user_name[player] = user_name[player][:-1] if event.key == pygame.K_BACKSPACE:
elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: continue user_name[player] = user_name[player][:-1]
else: user_name[player] += event.unicode elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
continue
else:
user_name[player] += event.unicode
if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
if multiplayer and player == 0: user_input(1) if multiplayer and player == 0:
else: main() user_input(1)
else:
main()
pygame.display.update() pygame.display.update()
def options() -> None: def options() -> None:
pygame.display.set_caption("Snake - Options") pygame.display.set_caption("Snake - Options")
while True: while True:
from globals import fps, multiplayer, walls from globals import fps, multiplayer, walls
mouse_pos = pygame.mouse.get_pos() mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK) WINDOW.fill(BLACK)
options_text = set_font(100).render("OPTIONS", 1, WHITE) options_text = set_font(100).render("OPTIONS", 1, WHITE)
options_rect = options_text.get_rect(center=(MID_WIDTH, 125)) options_rect = options_text.get_rect(center=(MID_WIDTH, 125))
WINDOW.blit(options_text, options_rect) WINDOW.blit(options_text, options_rect)
# change state names # change state names
# multiplayer # multiplayer
if multiplayer: multiplayer_state = "on" if multiplayer:
else: multiplayer_state = "off" multiplayer_state = "on"
# walls else:
if walls: walls_state = "on" multiplayer_state = "off"
else: walls_state = "off" # walls
if walls:
walls_state = "on"
else:
walls_state = "off"
speed_state = {5: "Slow", 10: "Normal", 15: "Fast"} speed_state = {5: "Slow", 10: "Normal", 15: "Fast"}
speed_button = Button((MID_WIDTH, MID_HEIGHT - 100), f"SPEED - {speed_state[fps]}", 75, GRAY, WHITE) speed_button = Button((MID_WIDTH, MID_HEIGHT - 100),
multiplayer_button = Button((MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE) f"SPEED - {speed_state[fps]}", 75, GRAY, WHITE)
walls_button = Button((MID_WIDTH, MID_HEIGHT + 100), f"WALLS - {walls_state}", 75, GRAY, WHITE) multiplayer_button = Button(
back_button = Button((MID_WIDTH, MID_HEIGHT + 200), "BACK", 75, GRAY, WHITE) (MID_WIDTH, MID_HEIGHT), f"MULTIPLAYER - {multiplayer_state}", 75, GRAY, WHITE)
buttons = [speed_button, multiplayer_button, walls_button, back_button] walls_button = Button((MID_WIDTH, MID_HEIGHT + 100),
f"WALLS - {walls_state}", 75, GRAY, WHITE)
back_button = Button((MID_WIDTH, MID_HEIGHT + 200),
"BACK", 75, GRAY, WHITE)
buttons = [speed_button, multiplayer_button, walls_button, back_button]
on_hover(buttons) on_hover(buttons)
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: quit() if event.type == pygame.QUIT:
if event.type == pygame.KEYDOWN: quit()
if event.key == pygame.K_ESCAPE: main_menu() if event.type == pygame.KEYDOWN:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if event.key == pygame.K_ESCAPE:
if speed_button.check_input(mouse_pos): change_speed() main_menu()
if multiplayer_button.check_input(mouse_pos): switch_multiplayer() if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if walls_button.check_input(mouse_pos): switch_walls() if speed_button.check_input(mouse_pos):
if back_button.check_input(mouse_pos): main_menu() change_speed()
if multiplayer_button.check_input(mouse_pos):
switch_multiplayer()
if walls_button.check_input(mouse_pos):
switch_walls()
if back_button.check_input(mouse_pos):
main_menu()
pygame.display.update() pygame.display.update()
def scoreboard() -> None: def scoreboard() -> None:
while True: while True:
mouse_pos = pygame.mouse.get_pos() mouse_pos = pygame.mouse.get_pos()
WINDOW.fill(BLACK) WINDOW.fill(BLACK)
top_text = set_font(100).render("TOP 10", 1, WHITE) top_text = set_font(100).render("TOP 10", 1, WHITE)
top_rect = top_text.get_rect(center=(MID_WIDTH, 55)) top_rect = top_text.get_rect(center=(MID_WIDTH, 55))
WINDOW.blit(top_text, top_rect) WINDOW.blit(top_text, top_rect)
back_button = Button((MID_WIDTH, MID_HEIGHT + 250), "BACK", 75, GRAY, WHITE) back_button = Button((MID_WIDTH, MID_HEIGHT + 250),
on_hover([back_button]) "BACK", 75, GRAY, WHITE)
on_hover([back_button])
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: quit() if event.type == pygame.QUIT:
if event.type == pygame.KEYDOWN: quit()
if event.key == pygame.K_ESCAPE: main_menu() if event.type == pygame.KEYDOWN:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if event.key == pygame.K_ESCAPE:
if back_button.check_input(mouse_pos): main_menu() main_menu()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if back_button.check_input(mouse_pos):
main_menu()
csv_file = read_score(BASE_PATH) csv_file = read_score(BASE_PATH)
for i, line in enumerate(sort(csv_file, reverse=True)[:11]): for i, line in enumerate(sort(csv_file, reverse=True)[:11]):
for j, text in enumerate(line): for j, text in enumerate(line):
score_text = set_font(30).render(text, 1, WHITE) score_text = set_font(30).render(text, 1, WHITE)
score_rect = score_text.get_rect(center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i)) score_rect = score_text.get_rect(
WINDOW.blit(score_text, score_rect) center=(MID_WIDTH - 150 + 300 * j, 150 + 30 * i))
WINDOW.blit(score_text, score_rect)
pygame.display.update() pygame.display.update()
def on_hover(buttons: list) -> None: def on_hover(buttons: list) -> None:
for button in buttons: for button in buttons:
button.change_color(pygame.mouse.get_pos()) button.change_color(pygame.mouse.get_pos())
button.update() button.update()

View File

@ -5,33 +5,34 @@ fields = ["Name", "Score"]
def write_score(name: str, score: int, base_path: str) -> None: def write_score(name: str, score: int, base_path: str) -> None:
create_header = False create_header = False
path = join(base_path, "score.csv") path = join(base_path, "score.csv")
if not exists(path): if not exists(path):
create_header = True create_header = True
with open(path, 'a', encoding='UTF-8', newline='') as file: with open(path, 'a', encoding='UTF-8', newline='') as file:
write = csv.writer(file) write = csv.writer(file)
if create_header: if create_header:
write.writerow(fields) write.writerow(fields)
write.writerows([[name, score]]) write.writerows([[name, score]])
def read_score(path: str): def read_score(path: str):
lines = [] lines = []
path = join(path, "score.csv") path = join(path, "score.csv")
try: try:
with open(path, 'r', encoding='UTF-8') as file: with open(path, 'r', encoding='UTF-8') as file:
for line in csv.reader(file): for line in csv.reader(file):
lines.append(line) lines.append(line)
return lines return lines
except FileNotFoundError: except FileNotFoundError:
return [fields] return [fields]
def sort(data, reverse: bool): def sort(data, reverse: bool):
if reverse == None: reverse = False if reverse == None:
header = data[0] reverse = False
data.remove(header) # remove header header = data[0]
data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data data.remove(header) # remove header
data.insert(0, header) # add header data = sorted(data, key=lambda x: int(x[1]), reverse=reverse) # sort data
return data data.insert(0, header) # add header
return data

View File

@ -1,5 +1,5 @@
import pygame
from os.path import join, abspath, dirname from os.path import join, abspath, dirname
import pygame
CELL_SIZE = 30 CELL_SIZE = 30
ROWS, COLUMNS = 30, 20 ROWS, COLUMNS = 30, 20
@ -11,9 +11,12 @@ pygame.font.init()
BASE_PATH = abspath(dirname(__file__)) BASE_PATH = abspath(dirname(__file__))
FONT = join(BASE_PATH, "fonts", "roboto.ttf") FONT = join(BASE_PATH, "fonts", "roboto.ttf")
SPRITE_PATH = join(BASE_PATH, "assets", "sprites") SPRITE_PATH = join(BASE_PATH, "assets", "sprites")
APPLE_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE)) APPLE_TEXTURE = pygame.transform.scale(pygame.image.load(
POISON_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE)) join(SPRITE_PATH, "golden_apple.png")), (CELL_SIZE, CELL_SIZE))
COBBLESTONE_TEXTURE = pygame.transform.scale(pygame.image.load(join(SPRITE_PATH, "cobblestone.jpeg")), (CELL_SIZE, CELL_SIZE)) POISON_TEXTURE = pygame.transform.scale(pygame.image.load(
join(SPRITE_PATH, "poison.png")), (CELL_SIZE, CELL_SIZE))
COBBLESTONE_TEXTURE = pygame.transform.scale(pygame.image.load(
join(SPRITE_PATH, "cobblestone.jpeg")), (CELL_SIZE, CELL_SIZE))
BLACK = (0, 0, 0) BLACK = (0, 0, 0)
DARK_BLUE = (0, 0, 170) DARK_BLUE = (0, 0, 170)
@ -32,9 +35,12 @@ LIGHT_PURPLE = (255, 85, 255)
YELLOW = (255, 255, 85) YELLOW = (255, 255, 85)
WHITE = (242, 242, 242) WHITE = (242, 242, 242)
COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW] COLORS = [DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE,
GOLD, BLUE, GREEN, AQUA, RED, LIGHT_PURPLE, YELLOW]
def set_font(size): return pygame.font.Font(FONT, size) # sets font size
set_font = lambda size: pygame.font.Font(FONT, size) # sets font size
fps = 10 # speed fps = 10 # speed
multiplayer = False multiplayer = False
@ -42,17 +48,20 @@ walls = False
def change_speed() -> None: def change_speed() -> None:
global fps global fps
if fps == 5: fps = 10 if fps == 5:
elif fps == 10: fps = 15 fps = 10
elif fps == 15: fps = 5 elif fps == 10:
fps = 15
elif fps == 15:
fps = 5
def switch_multiplayer() -> None: def switch_multiplayer() -> None:
global multiplayer global multiplayer
multiplayer = not multiplayer multiplayer = not multiplayer
def switch_walls() -> None: def switch_walls() -> None:
global walls global walls
walls = not walls walls = not walls

159
pygame/snake/source/snake.py Executable file → Normal file
View File

@ -17,104 +17,109 @@ snakes = []
def draw_grid() -> None: def draw_grid() -> None:
x, y = 0, 0 x, y = 0, 0
for _ in range(ROWS): for _ in range(ROWS):
x += CELL_SIZE x += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT)) pygame.draw.line(WINDOW, WHITE, (x, 0), (x, HEIGHT))
for _ in range(COLUMNS): for _ in range(COLUMNS):
y += CELL_SIZE y += CELL_SIZE
pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y)) pygame.draw.line(WINDOW, WHITE, (0, y), (WIDTH, y))
def draw_score(snakes) -> None: def draw_score(snakes) -> None:
for index, snake in enumerate(snakes): for index, snake in enumerate(snakes):
score_label = set_font(40).render(f"Score {len(snake.body) - 1}", 1, snake.color) score_label = set_font(40).render(
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)), (WINDOW_HEIGHT - score_label.get_height()))) f"Score {len(snake.body) - 1}", 1, snake.color)
WINDOW.blit(score_label, (10 + (index * (WIDTH - score_label.get_width() - 20)),
(WINDOW_HEIGHT - score_label.get_height())))
def collision_check(snakes, snack) -> None: def collision_check(snakes, snack) -> None:
for snake in snakes: for snake in snakes:
for block in snake.body: for block in snake.body:
if block.pos == snack.pos: if block.pos == snack.pos:
snack.randomize() snack.randomize()
def end_screen() -> None: def end_screen() -> None:
for snake in snakes: for snake in snakes:
if len(snake.body) > 1: if len(snake.body) > 1:
write_score(snake.name, len(snake.body) - 1, BASE_PATH) write_score(snake.name, len(snake.body) - 1, BASE_PATH)
main_menu() main_menu()
def main() -> None: def main() -> None:
snakes.clear() snakes.clear()
from globals import fps, multiplayer, walls from globals import fps, multiplayer, walls
pygame.display.set_caption("Snake") pygame.display.set_caption("Snake")
clock = pygame.time.Clock() clock = pygame.time.Clock()
from assets.scripts.menu import user_name, color_index from assets.scripts.menu import user_name, color_index
snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[0]], user_name[0], 1, multiplayer) snake_one = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
snakes.append(snake_one) COLORS[color_index[0]], user_name[0], 1, multiplayer)
snakes.append(snake_one)
if multiplayer: if multiplayer:
snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)), COLORS[color_index[1]], user_name[1], 2, multiplayer) snake_two = Snake((randint(0, ROWS - 1), randint(0, COLUMNS - 1)),
snakes.append(snake_two) COLORS[color_index[1]], user_name[1], 2, multiplayer)
apple = Snack(APPLE_TEXTURE) snakes.append(snake_two)
collision_check(snakes, apple) apple = Snack(APPLE_TEXTURE)
poison = Snack(POISON_TEXTURE) collision_check(snakes, apple)
collision_check(snakes, poison) poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison)
def redraw_window() -> None: def redraw_window() -> None:
WINDOW.fill(BLACK) WINDOW.fill(BLACK)
draw_grid() draw_grid()
draw_score(snakes) draw_score(snakes)
for snake in snakes: for snake in snakes:
snake.draw() snake.draw()
apple.draw_snack() apple.draw_snack()
poison.draw_snack() poison.draw_snack()
if walls: if walls:
for i in range(ROWS): for i in range(ROWS):
COBBLE_RECT = pygame.Rect(i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE) COBBLE_RECT = pygame.Rect(
WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT) i * CELL_SIZE, HEIGHT, WIDTH, CELL_SIZE)
pygame.display.update() WINDOW.blit(COBBLESTONE_TEXTURE, COBBLE_RECT)
pygame.display.update()
while True: while True:
clock.tick(fps) clock.tick(fps)
pygame.time.delay(0) pygame.time.delay(0)
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
quit() quit()
if event.type == pygame.KEYDOWN: if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: if event.key == pygame.K_ESCAPE:
end_screen() end_screen()
for snake in snakes: for snake in snakes:
snake.move() snake.move()
if snake.body[0].pos == apple.pos: if snake.body[0].pos == apple.pos:
snake.add_cube() snake.add_cube()
apple = Snack(APPLE_TEXTURE) apple = Snack(APPLE_TEXTURE)
collision_check(snakes, apple) collision_check(snakes, apple)
if snake.body[0].pos == poison.pos: if snake.body[0].pos == poison.pos:
if len(snake.body) > 1: if len(snake.body) > 1:
snake.remove_cube() snake.remove_cube()
poison = Snack(POISON_TEXTURE) poison = Snack(POISON_TEXTURE)
collision_check(snakes, poison) collision_check(snakes, poison)
for i in range(len(snake.body)): for i in range(len(snake.body)):
if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])): if snake.body[i].pos in list(map(lambda z: z.pos, snake.body[i + 1:])):
end_screen() end_screen()
if multiplayer: if multiplayer:
for i in snakes[0].body: for i in snakes[0].body:
if i.pos == snakes[1].head.pos: if i.pos == snakes[1].head.pos:
end_screen() end_screen()
for i in snakes[1].body: for i in snakes[1].body:
if i.pos == snakes[0].head.pos: if i.pos == snakes[0].head.pos:
end_screen() end_screen()
redraw_window() redraw_window()
if __name__ == '__main__': if __name__ == '__main__':
main_menu() main_menu()

View File

@ -20,17 +20,23 @@ FONT = join(BASE_PATH, "fonts", "space_invaders.ttf")
# load sprites # load sprites
SPACESHIP = pygame.image.load(join(SPRITE_PATH, "playership.png")) # player SPACESHIP = pygame.image.load(join(SPRITE_PATH, "playership.png")) # player
PLAYER_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile PLAYER_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "playermissile.png")) # player missile
# enemies # enemies
ENEMY_1 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_magenta.png")), (40, 35)) ENEMY_1 = pygame.transform.scale(pygame.image.load(
ENEMY_2 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_cyan.png")), (40, 35)) join(ENEMY_PATH, "enemy_magenta.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(join(ENEMY_PATH, "enemy_lime.png")), (40, 35)) ENEMY_2 = pygame.transform.scale(pygame.image.load(
ENEMY_MISSILE = pygame.image.load(join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile join(ENEMY_PATH, "enemy_cyan.png")), (40, 35))
ENEMY_3 = pygame.transform.scale(pygame.image.load(
join(ENEMY_PATH, "enemy_lime.png")), (40, 35))
ENEMY_MISSILE = pygame.image.load(
join(SPRITE_PATH, "missiles", "enemymissile.png")) # enemy missile
pygame.display.set_icon(ENEMY_3) pygame.display.set_icon(ENEMY_3)
# background # background
BACKGROUND = pygame.transform.scale(pygame.image.load(join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT)) BACKGROUND = pygame.transform.scale(pygame.image.load(
join(BASE_PATH, "assets", "background.jpg")), (WIDTH, HEIGHT))
# colors (R, G, B) # colors (R, G, B)
BLUE = (16, 16, 69) BLUE = (16, 16, 69)
@ -40,259 +46,267 @@ RED = (188, 2, 5)
class Missile: class Missile:
def __init__(self, x: int, y: int, img) -> None: def __init__(self, x: int, y: int, img) -> None:
self.x = x self.x = x
self.y = y self.y = y
self.img = img self.img = img
self.mask = pygame.mask.from_surface(self.img) self.mask = pygame.mask.from_surface(self.img)
def draw(self, window) -> None: def draw(self, window) -> None:
window.blit(self.img, (self.x, self.y)) window.blit(self.img, (self.x, self.y))
def move(self, vel: int) -> None: def move(self, vel: int) -> None:
self.y += vel self.y += vel
def off_screen(self, height: int) -> bool: def off_screen(self, height: int) -> bool:
return not (self.y <= height and self.y >= 0) return not (self.y <= height and self.y >= 0)
def collision(self, obj) -> bool: def collision(self, obj) -> bool:
return collide(self, obj) return collide(self, obj)
class Ship: class Ship:
COOLDOWN = 30 # cooldown before shooting next missile COOLDOWN = 30 # cooldown before shooting next missile
def __init__(self, x: int, y: int, lives: int = 3) -> None: def __init__(self, x: int, y: int, lives: int = 3) -> None:
self.x = x self.x = x
self.y = y self.y = y
self.lives = lives self.lives = lives
self.ship_img = None self.ship_img = None
self.missile_img = None self.missile_img = None
self.missiles = [] self.missiles = []
self.cooldown_counter = 0 self.cooldown_counter = 0
def draw(self, window) -> None: def draw(self, window) -> None:
window.blit(self.ship_img, (self.x, self.y)) window.blit(self.ship_img, (self.x, self.y))
for missile in self.missiles: for missile in self.missiles:
missile.draw(WINDOW) missile.draw(WINDOW)
def move_missiles(self, vel: int, obj) -> None: def move_missiles(self, vel: int, obj) -> None:
self.cooldown() self.cooldown()
for missile in self.missiles: for missile in self.missiles:
missile.move(vel) missile.move(vel)
if missile.off_screen(HEIGHT): if missile.off_screen(HEIGHT):
self.missiles.remove(missile) self.missiles.remove(missile)
elif missile.collision(obj): elif missile.collision(obj):
obj.lives -= 1 obj.lives -= 1
self.missiles.remove(missile) self.missiles.remove(missile)
def cooldown(self) -> None: def cooldown(self) -> None:
if self.cooldown_counter >= self.COOLDOWN: if self.cooldown_counter >= self.COOLDOWN:
self.cooldown_counter = 0 self.cooldown_counter = 0
elif self.cooldown_counter > 0: elif self.cooldown_counter > 0:
self.cooldown_counter += 1 self.cooldown_counter += 1
def shoot(self) -> None: def shoot(self) -> None:
if self.cooldown_counter == 0: if self.cooldown_counter == 0:
missile = Missile(self.x + self.get_width() / 2 - 5 / 2, self.y, self.missile_img) # missile spawn with offset missile = Missile(self.x + self.get_width() / 2 - 5 / 2,
self.missiles.append(missile) self.y, self.missile_img) # missile spawn with offset
self.cooldown_counter = 1 self.missiles.append(missile)
self.cooldown_counter = 1
def get_width(self) -> int: def get_width(self) -> int:
return self.ship_img.get_width() return self.ship_img.get_width()
def get_height(self) -> int: def get_height(self) -> int:
return self.ship_img.get_height() return self.ship_img.get_height()
class Player(Ship): class Player(Ship):
def __init__(self, x: int, y: int, lives: int = 3) -> None: def __init__(self, x: int, y: int, lives: int = 3) -> None:
super().__init__(x, y, lives) super().__init__(x, y, lives)
self.ship_img = SPACESHIP self.ship_img = SPACESHIP
self.missile_img = PLAYER_MISSILE self.missile_img = PLAYER_MISSILE
self.mask = pygame.mask.from_surface(self.ship_img) self.mask = pygame.mask.from_surface(self.ship_img)
self.max_lives = lives self.max_lives = lives
self.score = 0 self.score = 0
def move_missiles(self, vel: int, objs: list) -> None: def move_missiles(self, vel: int, objs: list) -> None:
self.cooldown() self.cooldown()
for missile in self.missiles: for missile in self.missiles:
missile.move(vel) missile.move(vel)
if missile.off_screen(HEIGHT): if missile.off_screen(HEIGHT):
self.missiles.remove(missile) self.missiles.remove(missile)
self.score -= 10 self.score -= 10
else: else:
for obj in objs: for obj in objs:
if missile.collision(obj): if missile.collision(obj):
objs.remove(obj) objs.remove(obj)
# different scores for different colored enemies # different scores for different colored enemies
if obj.color == "lime": if obj.color == "lime":
self.score += 10 self.score += 10
elif obj.color == "cyan": elif obj.color == "cyan":
self.score += 20 self.score += 20
elif obj.color == "magenta": elif obj.color == "magenta":
self.score += 30 self.score += 30
if missile in self.missiles: if missile in self.missiles:
self.missiles.remove(missile) self.missiles.remove(missile)
class Enemy(Ship): class Enemy(Ship):
COLOR_MAP = { COLOR_MAP = {
"magenta": ENEMY_1, "magenta": ENEMY_1,
"cyan": ENEMY_2, "cyan": ENEMY_2,
"lime": ENEMY_3, "lime": ENEMY_3,
} }
def __init__(self, x: int, y: int, color: str) -> None: def __init__(self, x: int, y: int, color: str) -> None:
super().__init__(x, y) super().__init__(x, y)
self.missile_img = ENEMY_MISSILE self.missile_img = ENEMY_MISSILE
self.ship_img = self.COLOR_MAP[color] self.ship_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img) self.mask = pygame.mask.from_surface(self.ship_img)
self.color = color self.color = color
def move(self, vel_x: int, vel_y: int = 0) -> None: def move(self, vel_x: int, vel_y: int = 0) -> None:
self.x += vel_x self.x += vel_x
self.y += vel_y self.y += vel_y
def main() -> None: def main() -> None:
FPS = 60 FPS = 60
run = True run = True
lost = False lost = False
lost_count = 0 lost_count = 0
level = 0 level = 0
enemies = [] enemies = []
player_vel = 7 player_vel = 7
player_missile_vel = 15 player_missile_vel = 15
enemy_x_vel = 2 enemy_x_vel = 2
enemy_y_vel = 2 enemy_y_vel = 2
vel_x = enemy_x_vel vel_x = enemy_x_vel
enemy_missile_vel = 6 enemy_missile_vel = 6
last_enemy_shot = 0 last_enemy_shot = 0
player = Player(WIDTH / 2, 650) player = Player(WIDTH / 2, 650)
clock = pygame.time.Clock() clock = pygame.time.Clock()
def redraw_window() -> None: def redraw_window() -> None:
WINDOW.blit(BACKGROUND, (0, 0)) WINDOW.blit(BACKGROUND, (0, 0))
# draw text # draw text
lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE) lives_label = set_font(40).render(f"Lives: {player.lives}", 1, WHITE)
score_label = set_font(40).render(f"Score {player.score}", 1, WHITE) score_label = set_font(40).render(f"Score {player.score}", 1, WHITE)
level_label = set_font(40).render(f"Level: {level}", 1, WHITE) level_label = set_font(40).render(f"Level: {level}", 1, WHITE)
WINDOW.blit(lives_label, (10, 10)) WINDOW.blit(lives_label, (10, 10))
WINDOW.blit(score_label, (10, lives_label.get_height() + 10)) WINDOW.blit(score_label, (10, lives_label.get_height() + 10))
WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10)) WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
for enemy in enemies: for enemy in enemies:
enemy.draw(WINDOW) enemy.draw(WINDOW)
player.draw(WINDOW) player.draw(WINDOW)
if lost: if lost:
lost_label = set_font(60).render("You lost!", 1, RED) lost_label = set_font(60).render("You lost!", 1, RED)
WINDOW.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 350)) WINDOW.blit(lost_label, (WIDTH / 2 -
lost_label.get_width() / 2, 350))
pygame.display.update() pygame.display.update()
while run: while run:
clock.tick(FPS) clock.tick(FPS)
redraw_window() redraw_window()
if player.lives <= 0: if player.lives <= 0:
lost = True lost = True
lost_count += 1 lost_count += 1
# stop game # stop game
if lost: if lost:
if lost_count > FPS * 3: # wait for 3 sec if lost_count > FPS * 3: # wait for 3 sec
run = False run = False
else: else:
continue continue
# spawn enemies # spawn enemies
if len(enemies) == 0: if len(enemies) == 0:
level += 1 level += 1
margin = 75 margin = 75
for x in range(margin, WIDTH - margin, margin): for x in range(margin, WIDTH - margin, margin):
for y in range(margin, int(HEIGHT / 2), margin): for y in range(margin, int(HEIGHT / 2), margin):
if y == margin: # top row if y == margin: # top row
color = "magenta" color = "magenta"
elif y == 2 * margin: # rows 2-3 elif y == 2 * margin: # rows 2-3
color = "cyan" color = "cyan"
elif y == 4 * margin: # rows 4-5 elif y == 4 * margin: # rows 4-5
color = "lime" color = "lime"
enemy = Enemy(x, y, color) enemy = Enemy(x, y, color)
enemies.append(enemy) enemies.append(enemy)
for event in pygame.event.get(): for event in pygame.event.get():
# quit game # quit game
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
quit() quit()
keys = pygame.key.get_pressed() keys = pygame.key.get_pressed()
# move left # move left
if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0): if (keys[pygame.K_a] or keys[pygame.K_LEFT]) and (player.x - player_vel > 0):
player.x -= player_vel player.x -= player_vel
# move right # move right
if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH): if (keys[pygame.K_d] or keys[pygame.K_RIGHT]) and (player.x + player_vel + player.get_width() < WIDTH):
player.x += player_vel player.x += player_vel
# shoot # shoot
if keys[pygame.K_SPACE]: if keys[pygame.K_SPACE]:
player.shoot() player.shoot()
# enemies action # enemies action
for enemy in enemies[:]: for enemy in enemies[:]:
if enemy.x >= WIDTH - enemy.get_width(): if enemy.x >= WIDTH - enemy.get_width():
move(0, enemy_y_vel, enemies) move(0, enemy_y_vel, enemies)
vel_x = -enemy_x_vel vel_x = -enemy_x_vel
elif enemy.x <= 0: elif enemy.x <= 0:
move(0, enemy_y_vel, enemies) move(0, enemy_y_vel, enemies)
vel_x = enemy_x_vel vel_x = enemy_x_vel
enemy.move_missiles(enemy_missile_vel, player) enemy.move_missiles(enemy_missile_vel, player)
if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT): if collide(enemy, player) or (enemy.y + enemy.get_height() > HEIGHT):
player.score -= 10 player.score -= 10
player.lives -= 1 player.lives -= 1
enemies.remove(enemy) enemies.remove(enemy)
move(vel_x, 0, enemies) move(vel_x, 0, enemies)
if pygame.time.get_ticks() - last_enemy_shot > 2000: if pygame.time.get_ticks() - last_enemy_shot > 2000:
choice(enemies).shoot() choice(enemies).shoot()
last_enemy_shot = pygame.time.get_ticks() last_enemy_shot = pygame.time.get_ticks()
player.move_missiles(-player_missile_vel, enemies) player.move_missiles(-player_missile_vel, enemies)
# lambda functions # lambda functions
set_font = lambda size, font=FONT: pygame.font.Font(font, size) # sets font size def set_font(size, font=FONT): return pygame.font.Font(
collide = lambda obj1, obj2: obj1.mask.overlap(obj2.mask, (obj2.x - obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap font, size) # sets font size
def collide(obj1, obj2): return obj1.mask.overlap(obj2.mask, (obj2.x -
obj1.x, obj2.y - obj1.y)) != None # checks if 2 objs collide/overlap
def move(vel_x: int, vel_y: int, enemies: list) -> None: def move(vel_x: int, vel_y: int, enemies: list) -> None:
for enemy in enemies: for enemy in enemies:
enemy.move(vel_x, vel_y) enemy.move(vel_x, vel_y)
def main_menu() -> None: def main_menu() -> None:
while True: while True:
WINDOW.blit(BACKGROUND, (0, 0)) WINDOW.blit(BACKGROUND, (0, 0))
title_label = set_font(50).render("Press any key to start...", 1, WHITE) title_label = set_font(50).render(
WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, HEIGHT / 2 - title_label.get_height() / 2)) "Press any key to start...", 1, WHITE)
pygame.display.update() WINDOW.blit(title_label, (WIDTH / 2 - title_label.get_width() /
for event in pygame.event.get(): 2, HEIGHT / 2 - title_label.get_height() / 2))
if event.type == pygame.QUIT: pygame.display.update()
quit() for event in pygame.event.get():
if event.type == pygame.KEYDOWN: if event.type == pygame.QUIT:
main() quit()
if event.type == pygame.KEYDOWN:
main()
if __name__ == "__main__": if __name__ == "__main__":
main_menu() main_menu()

View File

@ -1,29 +1,29 @@
beautifulsoup4==4.10.0 beautifulsoup4==4.11.1
bs4==0.0.1 bs4==0.0.1
certifi==2021.10.8 certifi==2022.6.15
charset-normalizer==2.0.12 charset-normalizer==2.1.0
click==8.1.2 click==8.1.3
cycler==0.11.0 cycler==0.11.0
defusedxml==0.7.1 defusedxml==0.7.1
et-xmlfile==1.1.0 et-xmlfile==1.1.0
fonttools==4.31.2 fonttools==4.34.4
fpdf2==2.5.1 fpdf2==2.5.5
idna==3.3 idna==3.3
kiwisolver==1.4.2 kiwisolver==1.4.4
matplotlib==3.5.1 matplotlib==3.5.2
numpy==1.22.3 numpy==1.23.1
openpyxl==3.0.9 openpyxl==3.0.10
packaging==21.3 packaging==21.3
pandas==1.4.2 pandas==1.4.3
Pillow==9.1.0 Pillow==9.2.0
pyparsing==3.0.7 pyparsing==3.0.9
python-dateutil==2.8.2 python-dateutil==2.8.2
pytz==2022.1 pytz==2022.1
requests==2.27.1 requests==2.28.1
scipy==1.8.0 scipy==1.9.0
seaborn==0.11.2 seaborn==0.11.2
six==1.16.0 six==1.16.0
soupsieve==2.3.1 soupsieve==2.3.2.post1
urllib3==1.26.9 urllib3==1.26.11
word2number==1.1 word2number==1.1
yapf==0.32.0 yapf==0.32.0

View File

@ -4,76 +4,85 @@
# task 1 - train # task 1 - train
def trains(): def trains():
# blue train from Jelgava to Riga # blue train from Jelgava to Riga
blue_train_speed = 57 blue_train_speed = 57
blue_train_time_driven = 10 / 60 blue_train_time_driven = 10 / 60
# green train form Riga to Jelgava # green train form Riga to Jelgava
green_train_speed = 60 green_train_speed = 60
# red train from Valka to Jelgava # red train from Valka to Jelgava
red_train_speed = 60 red_train_speed = 60
red_train_time_driven = 4 red_train_time_driven = 4
# distances # distances
distance_riga_jelgava = 42 # from Riga to Jelgava (blue and green train) distance_riga_jelgava = 42 # from Riga to Jelgava (blue and green train)
distance_riga_valka = 164 # from Riga to Valka (red train) distance_riga_valka = 164 # from Riga to Valka (red train)
def blue_green_train(): def blue_green_train():
blue_train_already_driven_distance = blue_train_speed * blue_train_time_driven # blue train driven distance in 10 min blue_train_already_driven_distance = blue_train_speed * \
meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (blue_train_speed + green_train_speed) # time after which the two trains meet blue_train_time_driven # blue train driven distance in 10 min
green_train_distance = meeting_time * green_train_speed # distance green train has driven meeting_time = (distance_riga_jelgava - blue_train_already_driven_distance) / (
meeting_distance = distance_riga_jelgava - green_train_distance # distance from meeting point to Riga blue_train_speed + green_train_speed) # time after which the two trains meet
green_train_distance = meeting_time * \
green_train_speed # distance green train has driven
meeting_distance = distance_riga_jelgava - \
green_train_distance # distance from meeting point to Riga
return f"Zilais un zaļais vilciens tiksies {round(meeting_distance, 2)}km no Rīgas." return f"Zilais un zaļais vilciens tiksies {round(meeting_distance, 2)}km no Rīgas."
def red_train(): def red_train():
red_train_distance_driven = red_train_time_driven * red_train_speed # red train driven distance in given time red_train_distance_driven = red_train_time_driven * \
print(f"Sarkanais vilciens ir nobraucis {round(red_train_distance_driven, 2)}km.") red_train_speed # red train driven distance in given time
if red_train_distance_driven > distance_riga_valka: print(
return "Sarkanais vilciens ir pabraucis garām Rīgai." f"Sarkanais vilciens ir nobraucis {round(red_train_distance_driven, 2)}km.")
if red_train_distance_driven > distance_riga_valka:
return "Sarkanais vilciens ir pabraucis garām Rīgai."
print(blue_green_train()) print(blue_green_train())
print(red_train()) print(red_train())
# task 2 - sheep # task 2 - sheep
def farm(): def farm():
sheep_amount = 255 # amount of sheep in farm sheep_amount = 255 # amount of sheep in farm
sheep_price = 20.5 # price per sheep's wool sheep_price = 20.5 # price per sheep's wool
wool_total_price = sheep_amount * sheep_price # price for all sheep wool wool_total_price = sheep_amount * sheep_price # price for all sheep wool
additional_sheep = 120 # additional sheep additional_sheep = 120 # additional sheep
new_sheep_amount = sheep_amount + additional_sheep # sum of original and added sheep # sum of original and added sheep
new_wool_total_price = new_sheep_amount * wool_total_price # price for original and added sheep wool new_sheep_amount = sheep_amount + additional_sheep
# price for original and added sheep wool
new_wool_total_price = new_sheep_amount * wool_total_price
ostrich_amount = 15 # amount of ostrich in farm ostrich_amount = 15 # amount of ostrich in farm
ostrich_egg_price = 30 # price per egg ostrich_egg_price = 30 # price per egg
ostrich_time = 2 # time required to get one ostrich egg ostrich_time = 2 # time required to get one ostrich egg
days = 30 # the time when ostriches lay eggs days = 30 # the time when ostriches lay eggs
ostrich_egg_total_price = ostrich_amount * ostrich_egg_price * days / ostrich_time # price for all ostrich eggs in 30 days ostrich_egg_total_price = ostrich_amount * ostrich_egg_price * \
days / ostrich_time # price for all ostrich eggs in 30 days
if wool_total_price >= ostrich_egg_total_price: if wool_total_price >= ostrich_egg_total_price:
return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas." return "Iegūtās naudas pietiks, lai nopirktu visas mēneša olas."
else: else:
print("Iegūtās naudas nepietiks, lai nopirktu visas mēneša olas.") print("Iegūtās naudas nepietiks, lai nopirktu visas mēneša olas.")
if new_wool_total_price >= ostrich_egg_total_price: if new_wool_total_price >= ostrich_egg_total_price:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas pietiktu, lai nopirktu visas mēneša olas." return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas pietiktu, lai nopirktu visas mēneša olas."
else: else:
return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas nepietiktu, lai nopirktu visas mēneša olas." return f"Ja aitu būtu par {additional_sheep}, tad iegūtās naudas nepietiktu, lai nopirktu visas mēneša olas."
def main(): def main():
task = int(input("""Ivēlieties uzdevumu: task = int(input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums 1 - pirmais uzdevums
2 - otrais uzdevums 2 - otrais uzdevums
""")) """))
if task == 1: if task == 1:
trains() trains()
elif task == 2: elif task == 2:
print(farm()) print(farm())
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -3,22 +3,24 @@
class SalaryBonus(): class SalaryBonus():
def __init__(self): def __init__(self):
self.percent = .15 # percent self.percent = .15 # percent
self.salary = float(input("Mēneša algas apjoms: ")) # salary per month self.salary = float(input("Mēneša algas apjoms: ")) # salary per month
self.time_worked = int(input("Nostrādātais gadu skaits: ")) # number of years worked # number of years worked
self.time_worked = int(input("Nostrādātais gadu skaits: "))
def _calculate_bonus(self): def _calculate_bonus(self):
if self.time_worked > 2: # if worked for more than 2 years if self.time_worked > 2: # if worked for more than 2 years
salary_bonus = self.percent * self.salary * (self.time_worked - 2) # calculates salary bonus salary_bonus = self.percent * self.salary * \
return f"Algas bonuss ir {round(salary_bonus, 2)}" (self.time_worked - 2) # calculates salary bonus
else: return f"Algas bonuss ir {round(salary_bonus, 2)}"
return "Algas bonuss nepienākas." else:
return "Algas bonuss nepienākas."
def main(): def main():
print(SalaryBonus()._calculate_bonus()) print(SalaryBonus()._calculate_bonus())
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -4,36 +4,38 @@
# task 1 - prime numbers # task 1 - prime numbers
def is_prime(number): def is_prime(number):
import math import math
if number > 0: if number > 0:
if number == 1: if number == 1:
return "1 nav pirmsskaitlis" return "1 nav pirmsskaitlis"
else: else:
for i in range(2, int(math.sqrt(number)) + 1): # range from 2 to sqrt(n) for i in range(2, int(math.sqrt(number)) + 1): # range from 2 to sqrt(n)
if number % i == 0: if number % i == 0:
return f"{number} nav pirmsskaitlis" return f"{number} nav pirmsskaitlis"
return f"{number} ir pirmsskaitlis" return f"{number} ir pirmsskaitlis"
else: else:
return "Skaitlim jābūt lielākam par 0" return "Skaitlim jābūt lielākam par 0"
# task 2 - cities # task 2 - cities
class Cities: class Cities:
def __init__(self, p0, perc, delta, p): def __init__(self, p0, perc, delta, p):
self.p0 = p0 # initial population self.p0 = p0 # initial population
self.perc = float(perc[:-1]) / 100 # annual percentage population growth # annual percentage population growth
self.delta = delta # number of arrivals (departures) per year self.perc = float(perc[:-1]) / 100
self.p = p # population size required self.delta = delta # number of arrivals (departures) per year
self.p = p # population size required
def _calculate(self): def _calculate(self):
years = 0 years = 0
while (True): while (True):
self.p0 = self.p0 + self.p0 * self.perc + self.delta # calculate the new population in each year via the formula # calculate the new population in each year via the formula
years += 1 self.p0 = self.p0 + self.p0 * self.perc + self.delta
if self.p0 >= self.p: # if the initial population reaches the required years += 1
return f"{self.p} iedzīvotāju skaits tiks sasniegts pēc {years} gadiem" if self.p0 >= self.p: # if the initial population reaches the required
if self.p0 < 0: # if the required population is unreachable return f"{self.p} iedzīvotāju skaits tiks sasniegts pēc {years} gadiem"
return -1 if self.p0 < 0: # if the required population is unreachable
return -1
city_0 = Cities(1000, "2%", 50, 1200) city_0 = Cities(1000, "2%", 50, 1200)
@ -43,33 +45,33 @@ city_3 = Cities(1_500_000, "2.5%", 10_000, 2_000_000)
def main(): def main():
task = int(input("""Ivēlieties uzdevumu: task = int(input("""Ivēlieties uzdevumu:
1 - pirmais uzdevums 1 - pirmais uzdevums
2 - otrais uzdevums 2 - otrais uzdevums
""")) """))
if task == 1: if task == 1:
print(is_prime(int(input("Ievadiet skaitli: ")))) print(is_prime(int(input("Ievadiet skaitli: "))))
elif task == 2: elif task == 2:
city = int(input("""Izvēlieties pilsētu: city = int(input("""Izvēlieties pilsētu:
0 - piemēra pilsēta 0 - piemēra pilsēta
1 - pirmā pilsēta 1 - pirmā pilsēta
2 - otrā pilsēta 2 - otrā pilsēta
3 - trešā pilsēta 3 - trešā pilsēta
""")) """))
if city == 0: if city == 0:
print(city_0._calculate()) print(city_0._calculate())
elif city == 1: elif city == 1:
print(city_1._calculate()) print(city_1._calculate())
elif city == 2: elif city == 2:
print(city_2._calculate()) print(city_2._calculate())
elif city == 3: elif city == 3:
print(city_3._calculate()) print(city_3._calculate())
else: else:
print("Ievadīts nepareizs skaitlis.") print("Ievadīts nepareizs skaitlis.")
else: else:
print("Ievadīts nepareizs skaitlis.") print("Ievadīts nepareizs skaitlis.")
if __name__ == '__main__': if __name__ == '__main__':
main() main()