more accurate names, working on 01.md
parent
ebfefb97a9
commit
c83e01ad94
@ -0,0 +1,27 @@
|
||||
# 01
|
||||
|
||||
## Python, programovací jazyky, interpretace
|
||||
Když programujeme, píšeme nějaké výrazy v programovacím jazyce,
|
||||
následně voláme program, který zpracovává námi napsaný kód,
|
||||
a překládá ho do nějakého kódu nižší úrovně.
|
||||
Často to bývá strojový kód, který je jazykem samotného procesoru.
|
||||
Výsledkem takového překladu je většinou spustitelný (binární) soubor
|
||||
V případě Pythonu se binární soubor netvoří, ale Python interpreter
|
||||
zpracovává naše instrukce a rovnou je provádí.
|
||||
Tomuto procesu se říká interpretace, zatímco tvoření samostatného binárního souboru je kompilace.
|
||||
|
||||
Python stáhneme z této stránky: [](https://www.python.org/).
|
||||
|
||||
Nebo si ho pořídíme pomocí package manageru, což je preferovaný přístup v
|
||||
Unix-like operačních systémech.
|
||||
|
||||
Jeho přitomnost si můžeme ověřit zadáním `python` do příkazového řádku:
|
||||
|
||||
```shell
|
||||
Python 3.9.7 (default, Aug 31 2021, 13:28:12)
|
||||
[GCC 11.1.0] on linux
|
||||
Type "help", "copyright", "credits" or "license" for more information.
|
||||
>>>
|
||||
```
|
||||
|
||||
## Interaktivní mód
|
@ -1,83 +0,0 @@
|
||||
# matej.py
|
||||
```python
|
||||
import requests
|
||||
|
||||
# wtf jsou tyhle obrovsky mezery
|
||||
|
||||
def ship_detail(ShipName):
|
||||
url = 'https://swapi.co/api/starships'
|
||||
r = requests.get(url).json() # ^-- tohle je mega gay, protoze si nacitas vsechny data
|
||||
res = r['results'] # a sortujes v pythonu, misto toho abys si upravil
|
||||
ship_absolute = '' # url - mel bys to jednodussi, rychlejsi, prehlednejsi
|
||||
for ship in res: # a pametove efektivnejsi
|
||||
if ship['name'] == ShipName: # lol
|
||||
ship_absolute = ship
|
||||
break
|
||||
return[ship_absolute['name'], ship_absolute['model'], [requests.get(film).json()['title'] for film in ship_absolute['films']]] # sexy
|
||||
|
||||
def species_detail(SpeciesName):
|
||||
url = 'https://swapi.co/api/species' # stejnej problem jako nahore
|
||||
r = requests.get(url).json()
|
||||
res = r['results']
|
||||
species_absolute = '' # eeh, celkem dlouhej nazev, sice to neni explicitni chyba ale kratsi nazev = lepsi nazev
|
||||
for specie in res:
|
||||
if specie['name'] == SpeciesName:
|
||||
species_absolute = specie
|
||||
break
|
||||
list_title = [requests.get(film).json()['title'] for film in species_absolute['films']]
|
||||
list_id = [requests.get(film).json()['episode_id'] for film in species_absolute['films']]
|
||||
sort = sorted(zip(list_id, list_title))
|
||||
return [species_absolute['name'], species_absolute['classification'], species_absolute['designation'], requests.get(species_absolute['homeworld']).json()['name'], sort] # sexy
|
||||
|
||||
|
||||
def person_detail(Name): # a zase
|
||||
url = 'https://swapi.co/api/people'
|
||||
r = requests.get(url).json()
|
||||
res = r['results']
|
||||
person_absolute = ''
|
||||
for person in res:
|
||||
if person['name'] == Name:
|
||||
person_absolute = person
|
||||
break
|
||||
|
||||
list_title = [requests.get(film).json()['title'] for film in person_absolute['films']]
|
||||
list_id = [requests.get(film).json()['episode_id'] for film in person_absolute['films']]
|
||||
sort = sorted(zip(list_id, list_title))
|
||||
return [person_absolute['name'], person_absolute['gender'], requests.get(person_absolute['homeworld']).json()['name'], sort] # sexy
|
||||
|
||||
def Crawl(Film_Title): # a poctvrte
|
||||
url = 'https://swapi.co/api/films'
|
||||
r = requests.get(url).json()
|
||||
res = r['results']
|
||||
film_absolute = ''
|
||||
for film in res:
|
||||
if film['title'] == Film_Title:
|
||||
film_absolute = film # <-- mozny vynechat protoze film == film_absolute je True
|
||||
break # protoze film se updateuje kazdou loopu - kdyz loop skonci (`break`) tak film je promenna po breaku
|
||||
# coz je hezky protoze recyklujes promenne aniz by jejich nazev
|
||||
# neodpovidal hodnote
|
||||
print(film_absolute['opening_crawl'])
|
||||
|
||||
|
||||
def film_detail(FilmIdentifier): # a popate :D
|
||||
url = 'https://swapi.co/api/films'
|
||||
r = requests.get(url).json()
|
||||
res = r['results']
|
||||
film_absolute = ''
|
||||
for film in res:
|
||||
if film['title'] == FilmIdentifier or film['episode_id'] == FilmIdentifier:
|
||||
film_absolute = film
|
||||
break
|
||||
list_char = [requests.get(char).json() for char in film_absolute['characters']]
|
||||
list_ship = [requests.get(char).json() for char in film_absolute['starships']]
|
||||
return [film_absolute['title'], film_absolute['director'], film_absolute['episode_id'], sorted([ch['name'] for ch in list_char]), sorted([ch['name'] for ch in list_ship])] # sexy
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(ship_detail('Executor'))
|
||||
print(species_detail('Hutt'))
|
||||
print(person_detail('Luke Skywalker'))
|
||||
print(film_detail(3))
|
||||
print(film_detail('A New Hope'))
|
||||
Crawl('The Phantom Menace')
|
||||
```
|
@ -1,121 +0,0 @@
|
||||
# petr.py
|
||||
```python
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
|
||||
|
||||
# helper functions - Pedro
|
||||
# nice, delas abstrakce coz je super
|
||||
def get_json(url):
|
||||
return requests.get(url).json()
|
||||
|
||||
# dalsi abstrakce, hmm
|
||||
# asi celkem v pohode, ale nazvy potencialne moc dlouhy
|
||||
def get_film_titles(films):
|
||||
list_films = []
|
||||
for film in films:
|
||||
list_films.append(get_json(film)["title"])
|
||||
# mohl si napsat:
|
||||
#return [get_json(film)["title"] for film in films]
|
||||
return list_films
|
||||
|
||||
|
||||
def get_character_names(characters):
|
||||
list_characters = []
|
||||
for character in characters:
|
||||
list_characters.append(get_json(character)["name"])
|
||||
|
||||
return sorted(list_characters) # asi ne uplne dobry volat na tom sorted
|
||||
# ztracis trochu generalizaci
|
||||
# ale to je fakt detail
|
||||
|
||||
def get_spaceship_names(spaceships):
|
||||
list_spaceships = []
|
||||
for spaceship in spaceships:
|
||||
list_spaceships.append(get_json(spaceship)["name"])
|
||||
|
||||
return sorted(list_spaceships)
|
||||
|
||||
|
||||
def get_film_info(film):
|
||||
list_characters = get_character_names(film["characters"])
|
||||
list_spaceships = get_spaceship_names(film["starships"])
|
||||
return [film["title"], film["director"], film["episode_id"],
|
||||
list_characters, list_spaceships] # kdyz uz takhle formatujes tak
|
||||
# muzes rovnou na vic radku
|
||||
|
||||
|
||||
def ship_detail(shipname):
|
||||
web = get_json("https://swapi.co/api/starships/?search={}".format(shipname))["results"]
|
||||
list_results = []
|
||||
for result in web:
|
||||
list_films = get_film_titles(result["films"])
|
||||
list_results.append(
|
||||
[result["name"], result["model"], result["starship_class"], result["hyperdrive_rating"], list_films])
|
||||
|
||||
return list_results
|
||||
|
||||
|
||||
def species_detail(speciesname):
|
||||
web = get_json("https://swapi.co/api/species/?search={}".format(speciesname))["results"]
|
||||
list_results = []
|
||||
for result in web:
|
||||
list_films = get_film_titles(result["films"])
|
||||
homeworld = get_json(result["homeworld"])["name"]
|
||||
list_results.append(
|
||||
[result["name"], result["classification"], result["designation"], homeworld, list_films])
|
||||
|
||||
return list_results
|
||||
|
||||
|
||||
def person_detail(name):
|
||||
web = get_json("https://swapi.co/api/people/?search={}".format(name))["results"]
|
||||
list_results = []
|
||||
for result in web:
|
||||
list_films = get_film_titles(result["films"])
|
||||
homeworld = get_json(result["homeworld"])["name"]
|
||||
list_results.append(
|
||||
[result["name"], result["gender"], homeworld, list_films])
|
||||
|
||||
return list_results
|
||||
|
||||
|
||||
def film_detail(filmidentifier, id_type="ep_id"):
|
||||
list_results = []
|
||||
if id_type == "ep_id":
|
||||
web = get_json("https://swapi.co/api/films/{}".format(filmidentifier))
|
||||
list_results.append(get_film_info(web))
|
||||
elif id_type == "title":
|
||||
web = get_json("https://swapi.co/api/films/?search={}".format(filmidentifier))["results"]
|
||||
for result in web:
|
||||
list_results.append(get_film_info(result))
|
||||
|
||||
else:
|
||||
raise Exception('Bad film id type') # eeh, ok
|
||||
|
||||
return list_results
|
||||
|
||||
|
||||
def crawl(title):
|
||||
web = get_json("https://swapi.co/api/films/?search={}".format(title))["results"]
|
||||
for result in web:
|
||||
film_crawl = result["opening_crawl"].split("\r\n")
|
||||
for line in film_crawl:
|
||||
print(line)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# testing program. runs only if run as main - Pedro
|
||||
print(ship_detail("Imperial shuttle"))
|
||||
print(species_detail("Hutt"))
|
||||
print(person_detail("Owen Lars"))
|
||||
|
||||
print(film_detail("The Phantom Menace", "title"))
|
||||
print(film_detail(2))
|
||||
|
||||
crawl("A New Hope")
|
||||
|
||||
# shit Pedro mas to moc dobry, priste to udelej hur pls
|
||||
```
|
@ -1,76 +0,0 @@
|
||||
# katka.py
|
||||
```python
|
||||
plocha = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] # globaly - spatnej zvyk
|
||||
hrac = "X"
|
||||
|
||||
def kontrola(): # kontrola vsech moznosti; celkem v pohode tady ale slo to vyresit chytreji
|
||||
# kdybychom najednou zmenili plochu z 3x3 na 4x4 tak uz by to nefungovalo
|
||||
# jinak je to celkem hezky
|
||||
if plocha[0][0] == plocha[0][1] and plocha[0][1] == plocha[0][2] and plocha[0][2] != " ":
|
||||
print("Vyhrál " + hrac) # print ve funkci, ne moc idealni z funkcionalniho hlediska
|
||||
# protoze `hrac` je tady globalni promenna; nevadi, to jeste budeme resit; v takhle
|
||||
# malym programu to ani tolik nevadi
|
||||
return True
|
||||
if plocha[1][0] == plocha[1][1] and plocha[1][1] == plocha[1][2] and plocha[1][2] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True # skvele ze je tady return, diky tomuhle se utece z funkce aniz by se kontroloval zbytek
|
||||
if plocha[2][0] == plocha[2][1] and plocha[2][1] == plocha[2][2] and plocha[2][2] != " ":
|
||||
#if plocha[2][0] == plocha[2][1] == plocha[2][2] != " ":
|
||||
# ^ ekvivalence, asi trochu hezci
|
||||
# je to ale specifikum pythonu ze to funguje
|
||||
# takze tohle je ve skutecnosti v poradku
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
if plocha[0][0] == plocha[1][0] and plocha[1][0] == plocha[2][0] and plocha[2][0] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
if plocha[0][1] == plocha[1][1] and plocha[1][1] == plocha[2][1] and plocha[2][1] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
if plocha[0][2] == plocha[1][2] and plocha[1][2] == plocha[2][2] and plocha[2][2] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
if plocha[0][0] == plocha[1][1] and plocha[1][1] == plocha[2][2] and plocha[2][2] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
if plocha[0][2] == plocha[1][1] and plocha[1][1] == plocha[2][0] and plocha[2][0] != " ":
|
||||
print("Vyhrál " + hrac)
|
||||
return True
|
||||
return False
|
||||
|
||||
def vytiskni(): # tady vsechno super
|
||||
print(plocha[0][0] + "|" + plocha[0][1] + "|" + plocha[0][2])
|
||||
print("-+-+-")
|
||||
print(plocha[1][0] + "|" + plocha[1][1] + "|" + plocha[1][2])
|
||||
print("-+-+-")
|
||||
print(plocha[2][0] + "|" + plocha[2][1] + "|" + plocha[2][2])
|
||||
|
||||
vytiskni()
|
||||
while True:
|
||||
x = input()
|
||||
y = x.split() # asi bych tohle zkratil, ta promenna x tam tak trochu visi bez cile
|
||||
# taky by mozna bylo chytry si rovnou vzit prvni 2 prvky z `x.split()`
|
||||
# napsal bych:
|
||||
#x = input()
|
||||
#x = x.split()
|
||||
# nebo:
|
||||
#x = input().split()
|
||||
# k tomu ze bych rovnou vzal 2 prvky tak bych napsal:
|
||||
#x = input().split()
|
||||
#y = int(x[0])
|
||||
#x = int(x[1])
|
||||
if plocha[int(y[0])][int(y[1])] == " ": # tady by bylo: `plocha[y][x] == " "`
|
||||
plocha[int(y[0])][int(y[1])] = hrac
|
||||
if kontrola(): # tohle se mi libi - hromada lidi by napsala:
|
||||
# `if kontrola() == True:`
|
||||
vytiskni()
|
||||
break
|
||||
if hrac == "X": # lze napsat hezcejc, ale to jeste neumite
|
||||
hrac = "O"
|
||||
else:
|
||||
hrac = "X"
|
||||
vytiskni()
|
||||
# sice to vypada ze to hodne hatim ale libi se mi to
|
||||
# je to presne jak jsem si to predstavoval
|
||||
# cili exactly co jsem od vas ocekaval
|
||||
```
|
@ -1,216 +0,0 @@
|
||||
# matej.py
|
||||
```python
|
||||
grid = [
|
||||
["", "", ""],
|
||||
["", "", ""],
|
||||
["", "", ""]
|
||||
]
|
||||
|
||||
x = False
|
||||
# nazev promenny nic nerika
|
||||
# taky ta definice je kilometry od mista kde se
|
||||
# ta promenna pouzije :(
|
||||
|
||||
def play1(): # dve oddeleny funkce pro ruzne hrace
|
||||
# debilni protoze a) nemuzeme snadno pridat hrace
|
||||
# b) opakovani kodu
|
||||
|
||||
global x_input_1
|
||||
global y_input_1
|
||||
# oof, globaly
|
||||
|
||||
true_x = False # lol, to jsou nazvy.
|
||||
true_y = False # procs tam nenapsal rovnou:
|
||||
#false_y = True
|
||||
# :D
|
||||
# ale vazne by bylo lepsi:
|
||||
#bool_y = False
|
||||
true_taken_1 = False
|
||||
|
||||
print("Now will play player 1") # english
|
||||
|
||||
while not true_taken_1: # celkem elegantni, az na to ze moc ne
|
||||
# chytrejsi by bylo volat funkci na taken ale to by
|
||||
# vyzadovalo premyslet o strukture programu, vid ze jo?
|
||||
|
||||
while not true_x:
|
||||
|
||||
x_input_1 = int(input("Enter x axis position (1, 2, 3): "))
|
||||
|
||||
if x_input_1 == 1:
|
||||
true_x = True
|
||||
elif x_input_1 == 2:
|
||||
true_x = True
|
||||
elif x_input_1 == 3:
|
||||
true_x = True
|
||||
else:
|
||||
print("Try again (1, 2, 3)") # eeeh, zdaleka ne moc elegantni
|
||||
|
||||
while not true_y:
|
||||
|
||||
y_input_1 = int(input("Enter y axis position (1, 2, 3): "))
|
||||
|
||||
if y_input_1 == 1:
|
||||
true_y = True
|
||||
elif y_input_1 == 2:
|
||||
true_y = True
|
||||
elif y_input_1 == 3:
|
||||
true_y = True
|
||||
else:
|
||||
print("Try again (1, 2, 3)")
|
||||
|
||||
if grid[x_input_1 - 1][y_input_1 - 1] not in ("X", "O"):
|
||||
true_taken_1 = True
|
||||
|
||||
else:
|
||||
print("That position is taken")
|
||||
true_x = False
|
||||
true_y = False
|
||||
|
||||
grid[x_input_1 - 1][y_input_1 - 1] = "X"
|
||||
|
||||
print(grid[0][0] + " | " + grid[1][0] + " | " + grid[2][0] + "\n" + "__" + " " + "__" + " " + "__" +
|
||||
"\n" + grid[0][1] + " | " + grid[1][1] + " | " + grid[2][1] + "\n" + "__" + " " + "__" + " " + "__" +
|
||||
"\n" + grid[0][2] + " | " + grid[1][2] + " | " + grid[2][2]) # celkem v pohode lol
|
||||
|
||||
def play2():
|
||||
print("Now will play player 2\n")
|
||||
global x_input_2
|
||||
global y_input_2
|
||||
# globaly fuj fuj
|
||||
true_taken_2 = False
|
||||
true_x_1 = False
|
||||
true_y_1 = False
|
||||
|
||||
while not true_taken_2:
|
||||
while not true_x_1:
|
||||
|
||||
x_input_2 = int(input("Enter x axis position (1, 2, 3): "))
|
||||
|
||||
if x_input_2 == 1:
|
||||
true_x_1 = True
|
||||
elif x_input_2 == 2:
|
||||
true_x_1 = True
|
||||
elif x_input_2 == 3:
|
||||
true_x_1 = True
|
||||
else:
|
||||
print("Try again (1, 2, 3)")
|
||||
|
||||
while not true_y_1:
|
||||
y_input_2 = int(input("Enter y axis position (1, 2, 3): "))
|
||||
|
||||
if y_input_2 == 1:
|
||||
true_y_1 = True
|
||||
elif y_input_2 == 2:
|
||||
true_y_1 = True
|
||||
elif y_input_2 == 3:
|
||||
true_y_1 = True
|
||||
else:
|
||||
print("Try again (1, 2, 3)")
|
||||
|
||||
if grid[x_input_2 - 1][y_input_2 - 1] not in ("X", "O"):
|
||||
true_taken_2 = True
|
||||
|
||||
else:
|
||||
print("That position is taken")
|
||||
true_x_1 = False
|
||||
true_y_1 = False
|
||||
|
||||
grid[x_input_2 - 1][y_input_2 - 1] = "O"
|
||||
|
||||
print(grid[0][0] + " | " + grid[1][0] + " | " + grid[2][0] + "\n" + "__" + " " + "__" + " " + "__" +
|
||||
"\n" + grid[0][1] + " | " + grid[1][1] + " | " + grid[2][1] + "\n" + "__" + " " + "__" + " " + "__" +
|
||||
"\n" + grid[0][2] + " | " + grid[1][2] + " | " + grid[2][2])
|
||||
|
||||
def win():
|
||||
global x
|
||||
# globaly fuj fuj
|
||||
x0_y0 = grid[0][0] # <-- gay
|
||||
x0_y1 = grid[0][1] # <-- gay
|
||||
x0_y2 = grid[0][2] # <-- gay
|
||||
x1_y0 = grid[1][0] # <-- gay
|
||||
x1_y1 = grid[1][1] # <-- gay
|
||||
x1_y2 = grid[1][2] # <-- gay
|
||||
x2_y0 = grid[2][0] # <-- gay
|
||||
x2_y1 = grid[2][1] # <-- gay
|
||||
x2_y2 = grid[2][2] # <-- gay
|
||||
|
||||
if x0_y0 == x0_y1 == x0_y2 and x0_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
|
||||
elif x1_y0 == x1_y1 == x1_y2 and x1_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x2_y0 == x2_y1 == x2_y2 and x2_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x0_y0 == x1_y0 == x2_y0 and x0_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x0_y1 == x1_y1 == x0_y2 and x0_y1 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x0_y2 == x1_y2 == x2_y2 and x0_y2 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x0_y0 == x1_y1 == x2_y2 and x0_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
elif x2_y0 == x1_y1 == x0_y2 and x2_y0 == "X":
|
||||
print("Player 1 wins")
|
||||
x = True
|
||||
|
||||
elif x0_y0 == x0_y1 == x0_y2 and x0_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x1_y0 == x1_y1 == x1_y2 and x1_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x2_y0 == x2_y1 == x2_y2 and x2_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x0_y0 == x1_y0 == x2_y0 and x0_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x0_y1 == x1_y1 == x0_y2 and x0_y1 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x0_y2 == x1_y2 == x2_y2 and x0_y2 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x0_y0 == x1_y1 == x2_y2 and x0_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
elif x2_y0 == x1_y1 == x0_y2 and x2_y0 == "O":
|
||||
print("Player 2 wins")
|
||||
x = True
|
||||
# top kek, jeste jsi ani neresil to ze vlastne nemusis rozlisovat
|
||||
# mezi X a O, staci ze jsou stejny. dalo se to vymyslet mnohem
|
||||
# jednoduseji, o tom byl ten ukol
|
||||
|
||||
while not x: # mega gay, tyhle casti programu se rika
|
||||
# mainloop, a princip je takovej ze kdyz
|
||||
# hra skonci tak breakujes. To tady pochopitelne
|
||||
# nemas, protoze tvoje kazda funkce je void (a nic nevraci)
|
||||
# takze vystup je printovej. To je mega gay, protoze nevyuzivas
|
||||
# potencial funkci a taky print je vedlejsi efekt o kterym jsem
|
||||
# se bavil ze je to presne to co nechces
|
||||
|
||||
# takze ten program sice pozna ze nekdo vyhral, ale neskonci
|
||||
win()
|
||||
play1()
|
||||
|
||||
win()
|
||||
if not x:
|
||||
play2()
|
||||
|
||||
print("End of the game")
|
||||
|
||||
# krasnej priklad toho, proc jsem vam rikal abyste si nejdriv program
|
||||
# promysleli nez ho naprogramujete
|
||||
|
||||
# na druhou stranu respekt zes to dotahl i presto ze je to tak necitelny
|
||||
# a taky diky tobe mam o cem mluvit :D
|
||||
|
||||
```
|
@ -1,87 +0,0 @@
|
||||
# petr.py
|
||||
```python
|
||||
# OPRAVOVAL LUKÁŠ
|
||||
# Celkový komentář: Hezký, dobře čitelný kód, za mě jsi úplně splnil zadání
|
||||
# Máš to krátké a výstižné
|
||||
|
||||
|
||||
# Hezký, takhle se to normálně dělává, máš nějaký dict, který ti mapuje internální strukturu na její zobrazení
|
||||
values = {
|
||||
0: " ",
|
||||
1: "x",
|
||||
2: "o"
|
||||
}
|
||||
|
||||
# Kdybys pak chtěl přidat možnost opakovaného hraní, tak bys tohle musel přesunout do nějakého cyklu dole
|
||||
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
|
||||
|
||||
def print_board(): # Celkem pěkný, sice to dělá vedlejší efekty, ale tady to moc nevadí
|
||||
for i in range(3):
|
||||
print("{}|{}|{}".format(values.get(board[i][0]), values.get(board[i][1]), values.get(board[i][2])))
|
||||
print("-+-+-")
|
||||
|
||||
def get_user_input():
|
||||
# Taky profi, jenom snad možná by bylo lepší přesunout kód na kontrolu vstupu sem
|
||||
# aby to nemátlo lidi, co čtou kód hlavního cyklu a celkově by to bylo, řekl bych, ucelenější
|
||||
return [int(i) for i in input().split()]
|
||||
|
||||
def check_win():
|
||||
# Je vidět, že narozdíl od Matěje umíš cykly
|
||||
# Bohužel by to nefungovalo, kdybychom zvětšili herní pole
|
||||
# Tahle funkce by mohla brát board jako argument, což by bylo hezčí,
|
||||
# protože by se dala používat flexibilněji a nezávisela na svém umístění
|
||||
# Každopádně zadání celkem hezky splněno
|
||||
for i in range(3):
|
||||
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != 0:
|
||||
return True
|
||||
if board[0][i] == board[1][i] == board[2][i] and board[0][i] != 0:
|
||||
return True
|
||||
|
||||
if board[0][0] == board[1][1] == board[2][2] and board[1][1] != 0:
|
||||
return True
|
||||
if board[2][0] == board[1][1] == board[0][2] and board[1][1] != 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
def main():
|
||||
finished = False
|
||||
plays = 1
|
||||
|
||||
# Fajn, tady jsou dva odlišné přístupy (jeden je s break), ale nikdo neví, který z nich použít, takže dobrý:D
|
||||
while not finished:
|
||||
print_board()
|
||||
# Dá se zjednodušit f-stringem, ale tvá verze je kompatibilní i se staršími verzemi Pythonu 3 (<3.5),
|
||||
# což taky má své výhody
|
||||
print("Hraje {}".format(values.get(plays)))
|
||||
inp = False
|
||||
while not inp:
|
||||
try:
|
||||
user_input = get_user_input()
|
||||
if board[user_input[0]][user_input[1]] == 0:
|
||||
board[user_input[0]][user_input[1]] = plays
|
||||
# Jenom taková zajímavost - dalo by se to zkrátit na plays = (plays+1)%2
|
||||
# Každopádně je otázka, jestli by to bylo čitelnější, takže jsi udělal dobře
|
||||
if plays == 2:
|
||||
plays = 0
|
||||
plays += 1
|
||||
inp = True
|
||||
else:
|
||||
print("Buňka je již obsazena")
|
||||
except:
|
||||
# Jenom prosím, nikdy nepoužívat except bez specifikovaného typu chyby
|
||||
# Tady by stačilo něco jako `except (IndexError, ValueError):`
|
||||
# Vždycky specifikuj typy těch chyb, které zachytáváš, mohlo by se ti totiž stát, že tam bude ještě nějaká další
|
||||
# Pak další věc - snaž se, aby byla část v try-except bloku, co nejkratší,
|
||||
# protože opět, co kdybys udělal nějakou nečekanou chybu
|
||||
# Ty tady totiž máš i tu logiku na udělání tahu a změnu hráče
|
||||
# Každopádně jsem rád, že jsi na try-except vůbec přišel
|
||||
print("Váš vstup není platný")
|
||||
finished = check_win()
|
||||
|
||||
print_board()
|
||||
print("Konec hry")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Dobrá konstrukce, hodí se to, když chceš, aby tvůj kód byl také snadno importovatelný jako knihovna
|
||||
main()
|
||||
```
|
@ -1,62 +0,0 @@
|
||||
# tobias.py
|
||||
```python
|
||||
|
||||
pisk = [[" ", " ", " "],
|
||||
[" ", " ", " "],
|
||||
[" ", " ", " "]]
|
||||
|
||||
player = 'x'
|
||||
|
||||
def print_board(pisk): # beres board jako argument - super
|
||||
|
||||
for x in pisk: # sice se ti tam dela jedna cara navic ale je to elegantni
|
||||
# takze super
|
||||
print(f'{x[0]} | {x[1]} | {x[2]}')
|
||||
print('--+---+--')
|
||||
|
||||
def check():
|
||||
for i in range(3): # pouzivas cykly, taky fajn protoze si zjednodussujes praci
|
||||
if pisk[i][0] == pisk[i][1] and pisk[i][1] == pisk[i][2] and pisk[i][1] != ' ':
|
||||
print('Player ' + player + ' is the winner!!!')
|
||||
return True
|
||||
for i in range(3):
|
||||
if pisk[0][i] == pisk[1][i] and pisk[1][i] == pisk[2][i] and pisk[1][i] != ' ':
|
||||
print('Player ' + player + ' is the winner!!!')
|
||||
return True
|
||||
for i in range(1): # range(1).. hmm, tady to nesedi, vysral bych se na loop
|
||||
# kdybys delal cykly cyklu a mel misto `1` nejakou promennou pak pohoda
|
||||
if pisk[i][i] == pisk[i + 1][i + 1] and pisk[i + 1][i + 1] == pisk[i + 2][i + 2] and pisk[i + 1][i + 1] != ' ':
|
||||
print('Player ' + player + ' is the winner!!!')
|
||||
return True
|
||||
for i in range(1):
|
||||
if pisk[i][i + 2] == pisk[i + 1][i + 1] and pisk[i + 1][i + 1] == pisk[i + 2][i] and pisk[i + 1][i + 1] != ' ':
|
||||
print('Player ' + player + ' is the winner!!!')
|
||||
return True
|
||||
if pisk[0][0] != ' ' and pisk[0][1] != ' ' and pisk[0][2] != ' ' and pisk[1][0] != ' ' and pisk[1][1] != ' ' and pisk[1][2] != ' ' and pisk[2][0] != ' ' and pisk[2][1] != ' ' and pisk[2][2] != ' ': # husty, ale slo by to vymyslet lip
|
||||
print('Draw') # printy - chytrejsi je vracet to co se ma vytisknout jako string
|
||||
# lepsi zvyk protoze printy jsou vedlejsi efekty
|
||||
return True
|
||||
return False
|
||||
|
||||
while True:
|
||||
print_board(pisk)
|
||||
print('Now plays player ' + player) # "now plays player" lol
|
||||
print('Enter coordinates: ')
|
||||
r = input('Row (0,1,2):')
|
||||
c = input('Column(0,1,2): ')
|
||||
if r == '0' or r == '1' or r == '2' and c == '0' or c == '1' or c == '2':
|
||||
if pisk[int(r)][int(c)] == ' ':
|
||||
pisk[int(r)][int(c)] = player
|
||||
if check(): # chezky ze sis uvedomil ze `check` vraci bool
|
||||
break
|
||||
if player == 'x': # jde udelat chytreji, ale to jeste neumite
|
||||
player = 'o'
|
||||
elif player == 'o': # zbytecnej elif, staci else
|
||||
player = 'x'
|
||||
else:
|
||||
print('Kill yourself! That position is already taken!') # lol nice
|
||||
else:
|
||||
print('Wrong input you idiot!')
|
||||
print('End of the game')
|
||||
# jinak vsechno funguje - super
|
||||
```
|
@ -1,100 +0,0 @@
|
||||
# vlasta.py
|
||||
```python
|
||||
#Jupyter je lepsi
|
||||
# ^-- ok
|
||||
import numpy as np # podle me zbytecny jelikoz jsi stejne nepouzil vsechny moznosti numpy
|
||||
# jako treba ten matrix rotation
|
||||
# takhle je tvuj kod jenom dependent na jeste jedny veci, coz je
|
||||
# zbytecny; musis si uvedomit ze kdybys tohle nekomu posilal,
|
||||
# tak ten clovek musi mit nejenom python ale i numpy
|
||||
ikonky = [" "," X "," O "]
|
||||
def render(board): # board jako argument - super
|
||||
text = "+---+---+---+\n"
|
||||
for row in board:
|
||||
text += "|"
|
||||
for column in row:
|
||||
text += ikonky[column] + "|"
|
||||
text += "\n+---+---+---+\n"
|
||||
print(text)
|
||||
print("""+---+---+---+
|
||||
| 0 | 1 | 2 |
|
||||
+---+---+---+
|
||||
| 3 | 4 | 5 |
|
||||
+---+---+---+
|
||||
| 6 | 7 | 8 |
|
||||
+---+---+---+""")
|
||||
|
||||
def compare3(a,b,c): # obecne vyjadreni, nice
|
||||
return a == b and b == c and a != 0
|
||||
|
||||
def check(board, move): # elegantni reseni, ale jde to i snadneji :D
|
||||
#print(board, move)
|
||||
end = False
|
||||
#kontrola řádku
|
||||
end = end or compare3(board[0, move[1]],board[1, move[1]],board[2, move[1]])
|
||||
#kontrola sloupce
|
||||
end = end or compare3(board[move[0], 0],board[move[0], 1],board[move[0], 2])
|
||||
#kontrola diagnálně
|
||||
end = end or compare3(board[0, 0],board[1, 1],board[2, 2])
|
||||
end = end or compare3(board[0, 2],board[1, 1],board[2, 0])
|
||||
|
||||
return (end, 0 in board)
|
||||
|
||||
def inputMove():
|
||||
x = ""
|
||||
OK = False
|
||||
while not OK:
|
||||
x = input("Zadejte tah od 0 do 8 \n > ") # eeh, input ve funkci - vedlejsi efekt
|
||||
OK = x.isnumeric() # nice, hezky reseni problemu vstupu
|
||||
if OK:
|
||||
OK = int(x) >= 0 and int(x) <= 8
|
||||
if OK:
|
||||
X = int(x)//3
|
||||
Y = int(x)%3
|
||||
OK = move((X, Y),1)
|
||||
|
||||
def move(move,player):
|
||||
global board # fuj fuj
|
||||
global lastMove # bleh
|
||||
OK = board[move] == 0 # chytry ze sis to zapsal do promenny
|
||||
# diky tomu neprovadis stejny vypocet dvakrat
|
||||
if OK:
|
||||
board[move] = player
|
||||
lastMove = move
|
||||
return OK # vyuzivas return hodnot - nice
|
||||
|
||||
from random import randint
|
||||
def AImove():
|
||||
#vim ze to neni minmax
|
||||
#^-- to ne no, ale je to zajimavy ozvlastneni programu
|
||||
while not move((randint(0,2),randint(0,2)), 2):
|
||||
continue
|
||||
return move
|
||||
|
||||
|
||||
# LUKÁŠ - Tyhle module-level globaly by neměly fungovat, jsi si jistý, že jsi nahrál správný kód?
|
||||
# hra
|
||||
global board # wtf vlasto
|
||||
board = np.zeros((3, 3), dtype=np.int)
|
||||
global lastMove # wut; sice to nechazi chybu ale melo by
|
||||
lastMove = (0,0)
|
||||
player = 1
|
||||
render(board)
|
||||
while (not check(board, lastMove)[0]) and check(board, lastMove)[1]:
|
||||
if player == 1:
|
||||
inputMove()
|
||||
else:
|
||||
AImove()
|
||||
render(board)
|
||||
player = (player%2)+1 # Hraje další hráč; 1 => 2; 2 => 1
|
||||
# ^-- fajn ze komentujes
|
||||
if check(board, lastMove)[0]:
|
||||
print("Vyhrál: "+ikonky[board[lastMove]])
|
||||
else:
|
||||
print("Remíza")
|
||||
|
||||
# ma to divnou strukturu, na jednu stranu jsou nektery mista dobre napsany
|
||||
# jiny jsou gay a pouzivaj globaly
|
||||
|
||||
# jinak + za to AI
|
||||
```
|
Loading…
Reference in New Issue