Advertisement
Leeeo

CinemaSeater2000.0 - 31/08/2015 2:38pm

Aug 30th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.91 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name:        Cinema Seater 2000.0
  3. # Purpose:     Software Assignment
  4. #
  5. # Author:      Leo Carnovale
  6. #
  7. # Created:     04/08/2015
  8. # Copyright:   (c) L.Carnovale 2015
  9. # Licence:     Learner's Permit
  10. #-------------------------------------------------------------------------------
  11. KEY = 4
  12. from math import log
  13. def BaseConvert(number, StartBase, EndBase):
  14.     try:
  15.         n = int(str(StartBase)) + int(str(EndBase))
  16.     except ValueError:
  17.         return "Bad Base input"
  18.     StartBase, EndBase = int(StartBase), int(EndBase)
  19.     letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P']
  20.     StartLength = len(str(number))
  21.     for i in str(number):
  22.         if i not in letters:
  23.             try:
  24.                 a = int(i)
  25.             except ValueError:
  26.                 return "Bad input"
  27.     total = 0
  28.     for i in range(StartLength):
  29.         n = StartLength - i - 1
  30.         X = str(number)[n]
  31.         if X in letters:
  32.             X = letters.index(X) + 10
  33.         X = int(X)
  34.         if X > StartBase:
  35.             return "Bad start base"
  36.         total += int(X) * (StartBase ** i)
  37.     number = total
  38.     if EndBase > 1:
  39.         n2 = int(log(number, EndBase))
  40.     elif EndBase == 1:
  41.         n2 = number
  42.     else:
  43.         print("Unable to complete base conversion")
  44.         return
  45.     total = number
  46.     numbers = []
  47.     for i in range(n2 + 1):
  48.         X = int(total/(EndBase ** (n2 - i)))
  49.         if X > 9:
  50.             X = str(X)
  51.         numbers.append(str(X))
  52.         total = total % EndBase ** (n2 - i)
  53.     EndNumber = '|'.join(numbers)
  54.     Time = EndNumber.split("|")
  55.     if int(Time[0]) < 12:
  56.         part = "am"
  57.         NewTime1 = int(Time[0])
  58.     else:
  59.         part = "pm"
  60.         NewTime1 = int(Time[0]) - 12
  61.         if NewTime1 == 0:
  62.             NewTime1 = 12
  63.     if len(Time[1]) == 1:
  64.         NewTime2 = "0" + Time[1]
  65.     else:
  66.         NewTime2 = Time[1]
  67.     Time = str(NewTime1) + ":" + str(NewTime2) + part
  68.  
  69.     return Time
  70. def StripNumber(Number, Places):
  71.     if Places == -1:
  72.         Number = str(Number)
  73.         count = 0
  74.         for char in Number:
  75.             if char != 0:
  76.                 return int(Number[count:])
  77.             count += 1
  78.     if type(Number) != float:
  79.         try:
  80.             Number = float(Number)
  81.         except ValueError:
  82.             return Number
  83.     Number = str(Number)
  84.     Decimals = Number.split(".")[1]
  85.     Decimals = Decimals[0:Places]
  86.     Decimals = ''.join(reversed([x for x in str(int(''.join(reversed([x for x in Decimals]))))]))
  87.     Number = int(Number.split(".")[0])
  88.     return str(Number) + "." + str(Decimals)
  89.  
  90.  
  91.  
  92. def PrintTimeTable(cinema):
  93.     global BaseConvert
  94.     tab = max([len(x) for x in cinema if x[0] != "!"])
  95.     tab = max(tab, max([len(x[0]) for x in cinema["!movies"]]))
  96.     tab += 3
  97.     if tab > 30:
  98.         tab = 30
  99.     print("Theatre:|", end = "")
  100.     for theatre in sorted(cinema):
  101.         if theatre[0] != "!":
  102.             if len(theatre) > tab:
  103.                 theatre = theatre[0:27] + "..."
  104.             print(str(theatre).ljust(tab, " "), end = "|")
  105.     print()
  106.     for time in sorted(cinema["!timetable"]):
  107.         Time = BaseConvert(time, 10, 60)
  108.         print(Time.ljust(8, "-") + "|", end = "")
  109.         for theatre in sorted(cinema):
  110.             if theatre[0] != "!":
  111.                 x = cinema["!timetable"][time][theatre]
  112.                 if len(x) > tab:
  113.                     x = x[0:27] + "..."
  114.                 print(x.ljust(tab, "-") +"|", end = "")
  115.         print()
  116.     print()
  117.  
  118. def SeatTranslator(Number_Or_SeatLabel, Total_Seats):
  119.     Seats = [int(x) for x in Total_Seats.split("*")]
  120.     Seats.append(Seats[0] * Seats[1])
  121.     alphabet = ["a", 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
  122.     try:
  123.         Number_Or_SeatLabel = int(Number_Or_SeatLabel)
  124.     except ValueError:
  125.         try:
  126.             N = Number_Or_SeatLabel.split(",")[1]
  127.         except IndexError:
  128.             print("Seating script error")
  129.         else:
  130.             coord = [x for x in Number_Or_SeatLabel.split(",")]
  131.             if coord[0].lower() in alphabet:
  132.                 coord = [alphabet.index(coord[0].lower()) + 1, coord[1]]
  133.             coord = [int(x) for x in coord]
  134.             for i in range(2):
  135.                 if coord[i] > Seats[i]:
  136.                     return False
  137.             num = Seats[1] * (coord[0] - 1) + coord[1]
  138.             return num
  139.     else:
  140.         num = Number_Or_SeatLabel
  141.         col = num % Seats[1]
  142.         row = int(num / Seats[1]) + 1
  143.         if Seats[0] <= 26:
  144.             row = alphabet[row - 1]
  145.         coord = [str(row), str(col)]
  146.         return coord
  147.  
  148. def get_input(prompt,typ, bad_input,good_input):
  149.     if good_input:
  150.         SpecGood = True
  151.     else:
  152.         SpecGood = False
  153.     Sign = ""
  154.     if bad_input:
  155.         SpecBad = True
  156.         if typ == int or typ == float:
  157.             if bad_input[0] == "-":
  158.                 Sign = 1
  159.             elif bad_input[0] == "+":
  160.                 Sign = -1
  161.     else:
  162.         SpecBad = False
  163.     go = True
  164.     while go:
  165.         inp = input(prompt)
  166.         try:
  167.             inp = typ(inp)
  168.         except ValueError:
  169.             continue
  170.         else:
  171.             if SpecGood:
  172.                 if inp in good_input:
  173.                     if SpecBad:
  174.                         if inp not in bad_input:
  175.                             go = False
  176.                     else:
  177.                         go = False
  178.             else:
  179.                 go = False
  180.         if Sign and inp != 0:
  181.             if abs(inp) / inp != Sign:
  182.                 go = True
  183.     return inp
  184.  
  185. def EncryptInt(String, Key):
  186.     x = str(String)
  187.     x = [ord(i) for i in x]
  188.     Key = int(Key)
  189.     c = ''.join([chr((int(i if i != 10 else 11) ** Key) % 128) for i in x])
  190.     return c
  191.  
  192. def Input2Coords(Input):
  193.     if "," in Input:
  194.         coords = Input
  195.     else:
  196.         coords = Input[0] + "," + Input[1:]
  197.     return coords
  198. def SignIn():
  199.     global Member
  200.     global KEY
  201.     print("Enter your pin number:")
  202.     pin_enter = get_input(">>> ", str, [], [])
  203.     for member in members:
  204.         pin = EncryptInt(pin_enter, KEY)
  205.         if pin == members[member][0]:
  206.             print("Welcome {}!".format(member))
  207.             Member = member
  208.     if not Member:
  209.         print("User not found, please try again.")
  210. def AddMember(Name, Pin):
  211.     global KEY
  212.     global EncryptInt
  213.     global members
  214.     Pin = EncryptInt(Pin, KEY)
  215.     members[Name] = [Pin]
  216. def AddSessionToMember(member, session): # [Password, [<Session number>, Seat1, Seat2, Seat3, ..., SeatN]]
  217.     members[member].append(session)
  218. def UpdateMembers():
  219.     f = open("members.rtf", "w")
  220.     for member in members:
  221.         line = member + ", " + members[member][0]
  222.         if len(members[member]) > 1:
  223.             line += ", " + str(members[member][1])
  224.         line += "\n"
  225.         f.write(line)
  226.     f.close()
  227. def MakeTimetable():
  228.     for cinema in cinemas_all:
  229.         sessions = [] #Sessions{[Movie, theatre, start time, end time, [seats])
  230.         TimeTable = {}#                                               seats: [A[1, 2, 3, 4, ...], B[1, 2, 3, ...]]
  231.         Theatres = [theatre for theatre in cinemas_all[cinema] if theatre[0] != "!"]
  232.  
  233.         for i in range(540, 1381, 5):
  234.             if len(str(i)) == 3:
  235.                 i = '0' + str(i)
  236.             TimeTable[str(i)] = {}
  237.             for theatre in Theatres:
  238.                 TimeTable[str(i)][theatre] = ""
  239.         N_Theatres = len(cinemas_all[cinema]) - 2
  240.         N_Movies = len(cinemas_all[cinema]["!movies"])
  241.  
  242.         Movies = [movie[0] for movie in cinemas_all[cinema]["!movies"]]
  243.         count = 0
  244.         for theatre in Theatres:
  245.             if count >= N_Movies:
  246.                 count = 0
  247.             TimeTable['0540'][theatre] = Movies[count]
  248.             for time in range(540, 545 + cinemas_all[cinema]["!movies"][count][1], 5):
  249.                 if len(str(time)) == 3:
  250.                     time = '0' + str(time)
  251.                 TimeTable[str(time)][theatre] = Movies[count]
  252.             sessions.append([Movies[count], theatre, '0540', time, cinemas_all[cinema][theatre][1],[]])
  253.             count += 1
  254.         for time in sorted(TimeTable):
  255.             for theatre in TimeTable[time]:
  256.                 time_in_20 = str(int(time) + 20)
  257.                 if int(time_in_20) >= 1380:
  258.                     time_in_20 = time
  259.                 if len(time_in_20) == 3:
  260.                     time_in_20 = "0" + str(time_in_20)
  261.  
  262.                 if TimeTable[time][theatre] == "" and TimeTable[time_in_20][theatre] == "":
  263.  
  264.                     start = count
  265.                     skip = False
  266.                     if count >= N_Movies:
  267.                         count = 0
  268.                     while 1360 - cinemas_all[cinema]["!movies"][count][1] < int(time):
  269.                         if count == start:
  270.                             skip = True
  271.                             break
  272.                         count += 1
  273.                         if count >= N_Movies:
  274.                             count = 0
  275.                     if not skip:
  276.                         if TimeTable[str(time)][theatre] == "":
  277.                             for Ttime in range(int(time) + 20, int(time) + cinemas_all[cinema]["!movies"][count][1] + 20, 5):
  278.                                 if len(str(Ttime)) == 3:
  279.                                     Ttime = '0' + str(Ttime)
  280.                                 TimeTable[str(Ttime)][theatre] = Movies[count]
  281.                             sessions.append([Movies[count], theatre, time, Ttime, cinemas_all[cinema][theatre][1] ,[]])
  282.  
  283.                     count += 1
  284.                     if count >= N_Movies:
  285.                         count = 0
  286.         cinemas_all[cinema]["!timetable"] = TimeTable
  287.         cinemas_all[cinema]["!sessions"] = sessions
  288.         print("flag!!")
  289.         for session in sessions:
  290.             new_session = [cinema]
  291.             for p in session:
  292.                 new_session.append(p)
  293.             sessions_all.append(new_session)
  294.         # Session--> N:[Cinema, Movie name, Theatre, Start Time, End Time, Seat type, [Used Seats]]
  295.     f = open("timetable.txt","w")
  296.     for session in sessions_all:
  297.         line = str(sessions_all.index(session)) + "::" + str(session)
  298.         f.write(line)
  299.         f.write("\n")
  300.     f.close()
  301. def ParseToArray(ArrayAsString):
  302.     ArrayAsString = ArrayAsString.strip()
  303.     NewArray = []
  304.     ##AllParts = ArrayAsString.split(",")
  305.     level = -1
  306.     ##First = True
  307.     InString = False
  308.     count = 0
  309.     index = 0
  310.     index_start = 0
  311.     ##index_end = 0
  312.     for Char in ArrayAsString: # Goes through each character, if a ' is found, InString = 1, if a " is found, InString = 2,
  313.         if Char == "[" and InString == 0: # If InString is not 0, then brackets will be ignored.
  314.             level += 1
  315.             if level == 1:
  316.                 Start = count
  317.         elif Char == "]" and InString == 0:
  318.             level -= 1
  319.             if level == 0:
  320.                 End = count
  321.                 NewArray.append(ParseToArray(ArrayAsString[Start:End + 1]))
  322.                 index_start = count + 1
  323. ##                continue
  324.         elif Char == "'":
  325.             if InString == 1:
  326.                 InString = 0
  327.             elif InString == 0:
  328.                 InString = 1
  329.         elif Char == '"':
  330.             if InString == 2:
  331.                 InString = 0
  332.             elif InString == 0:
  333.                 InString = 2
  334.         if level == -1 and Char == "]" and InString == 0 and index_start != count:
  335.             index += 1
  336.             NewArray.append(ArrayAsString[index_start + 1:count].strip())
  337.             index_start = count
  338.         if level == 0 and Char == "," and InString == 0 and index_start != count:
  339.             index += 1
  340.             NewArray.append(ArrayAsString[index_start + 1:count].strip())
  341.             index_start = count
  342.         count += 1
  343. ##    count = 0
  344. ##    for item in NewArray:
  345. ##        if item:
  346. ##            if item.strip()[0] == item.strip()[-1]:
  347. ##                if item[0] == "'" or item[0] == '"':
  348. ##                    NewArray[count] = str(item[1:-1])
  349.     NewArray = CleanUp(NewArray)
  350.     return NewArray
  351.  
  352. def CleanUp(Mess):
  353.     count = 0
  354.     for item in Mess:
  355.         if item:
  356.             if type(item) == list:
  357.                 Mess[count] = CleanUp(item)
  358.             elif item.strip()[0] == item.strip()[-1]:
  359.                 if item[0] == "'" or item[0] == '"':
  360.                     Mess[count] = str(item[1:-1])
  361.         count += 1
  362.     Clean = Mess
  363.     return Clean
  364. def ReadTimetable():
  365.     print("Starting (0)")
  366.     global sessions_all
  367.     try:
  368.         with open("timetable.txt","r") as f:
  369.             print("Starting (1)")
  370.             for line in f:
  371.                 if line:
  372.                     array = line.split("::")[1]
  373.                     sessions_all.append(ParseToArray(array))
  374.             print("Done (1)")
  375.         print("Starting (2)")
  376.         for cinema in cinemas_all:
  377.             cinemas_all[cinema]["!sessions"] = []
  378.         print("Done (2)")
  379.         print("Starting (3)")
  380.         for session in sessions_all:
  381.             cinema = session[0]# Session--> N:[Cinema, Movie name, Theatre, Start Time, End Time, Seat type, [Used Seats]]
  382.             cinemas_all[cinema]["!sessions"].append(session[1:])
  383.         print("Done (3)")
  384.         print("Starting (4)")
  385.         for cinema in cinemas_all:
  386.             data = cinemas_all[cinema]
  387.             cinemas_all[cinema]["!timetable"] = {}
  388.             print("Starting (5)")
  389. ##            for session in data["!sessions"]:
  390.             RUNNING = [] #[[Name, Theatre]]
  391.             print("Starting (6)")
  392.             for i in range(540, 1381, 5):
  393.                 print("Starting (7)")
  394.                 for session in data["!sessions"]:
  395.                     if int(StripNumber(session[2], -1)) == i:
  396.                         RUNNING.append([session[0], session[1]])
  397.                     if len(str(i)) == 3:
  398.                         time = '0' + str(i)
  399.                     else:
  400.                         time = str(i)
  401.                     cinemas_all[cinema]["!timetable"][time] = {}
  402.                     for Movie in RUNNING:
  403. ##                            print("Starting (8)")
  404.                         cinemas_all[cinema]["!timetable"][time][Movie[1]] = Movie[0]
  405.                     if int(StripNumber(session[3], -1)) == i:
  406.                         RUNNING.remove([session[0], session[1]])
  407.             print("Done (5-8)")
  408.         print("Done (4)")
  409.  
  410.  
  411.     except FileNotFoundError:
  412.         print("The file doesn't exist, but I tried looking for it anyway. I shouldn't\nhave done that and you shouldn't bee seeing this but oh well.")
  413.     except ValueError:
  414.         print("A ValueError occured, meaning I found some letters where ther should be nuimbers.\nThe timetable file is probably corrupt. If you can't fix it, delete the timetable file.")
  415.     except IndexError:
  416.         print("Index Flag!")
  417.     print("Done (0)")
  418. # ######################################################################################################################################################################################################
  419. # Log book: https://docs.google.com/document/d/1w21Rvb-Z3PomSWipWrbKzBwybN_JN6yUL4h8mY5CD2s/edit?usp=sharing
  420. print("Cinema Seater 2000.0")
  421. print("Loading cinemas...")
  422. import glob, os
  423. rates = {}#                      Rates: {Ticket: Price, ...}
  424. cinemas_list = []
  425. cinemas_all = {}#              Cinemas: {Cinema: [Movies: [[movie 1, length], [movie 2, length], ...], Theatre 1: [N.of seats, Seats type], Theatre 2: [.., ..], ..., Seats: [[seat type, percentage], ...], ...}
  426. for file in glob.glob("*.txt"):
  427.     if file != "rates.txt":
  428.         cinemas_list.append(file)
  429.     else:
  430.         f = open(file, 'r')
  431.         ratesFILE = f.read()
  432.         f.close()
  433.  
  434. for rate in ratesFILE.split("\n"):
  435.     try:
  436.         if rate:
  437.             ticket = rate.split("=")[0].strip()
  438.             price = rate.split("=")[1].strip()
  439.             rates[ticket] = int(price)
  440.     except ValueError:
  441.         print("Rates file not formatted correctly. Please create one before using the program.")
  442.  
  443. ##theatres_sorted = {} #[cinema[theatre, ...]]
  444. print("Organising Data...")
  445. for cinema in cinemas_list:   #Goes through cinemas in directory and loads movies and seats into cinemas_all
  446.     f = open(cinema, "r")
  447.     name = cinema[:-4]
  448.     FILE = f.read()
  449.     f.close()
  450.     CINEMA = {}
  451.     cont = False
  452.     if FILE[0:17].lower() != "available movies:":
  453.         continue
  454.     else:
  455.         SplitFILE = FILE.split(";")
  456.         CINEMA["!movies"] = []
  457.         CINEMA["!prices"] = {}
  458.         for movie in SplitFILE[1].split("\n"):# Loads movies into temp CINEMA["!movies"] ( = [...])
  459.             if movie:
  460.                 try:
  461.                     length = movie.split(",")[1]
  462.                     length = length.strip()
  463.                     movie = movie.split(",")[0]
  464.                     if movie[0] == '"' and movie[-1] == '"':
  465.                         length = int(length)
  466.                     CINEMA["!movies"].append([movie[1:-1], length])
  467.                 except IndexError:
  468.                     print("'" + cinema + "'" + " is not formatted correctly! (Available movie list, IndexError)")
  469.                     cont = True
  470.                     break
  471.                 except ValueError:
  472.                     print("'" + cinema + "'" + " is not formatted correctly! (Available movie list, ValueError)")
  473.                     cont = True
  474.                     break
  475.  
  476.  
  477.         if cont:
  478.             cont = False
  479.             continue
  480.         for theatre in SplitFILE[3].split("\n"):# Loads seats into temp CINEMA[<theatre>] ( = [N. of seats, seats type])
  481.             if theatre:
  482.                 try:
  483.                     theatre_name = theatre.split(") ")[0]
  484.                     NumSeats = theatre.split(" ")[1]
  485.                     seat_type = theatre.split(", ")[1]
  486.                     CINEMA[theatre_name] = [NumSeats, seat_type]
  487.                 except IndexError:
  488.                     print("'" + cinema + "'" + " is not formatted correctly! (Theatres list, IndexError)")
  489.                     cont = True
  490.                     break
  491.                 except ValueError:
  492.                     print("'" + cinema + "'" + " is not formatted correctly! (Theatres list, ValueError)")
  493.                     cont = True
  494.                     break
  495.  
  496.         if cont:
  497.             cont = False
  498.             continue
  499.         for seat in SplitFILE[5].split("\n"):
  500.             try:
  501.                 if seat:
  502.                     seat_price = seat.split("= ")[1][:-1]
  503.                     seat_name = seat.split("=")[0].strip()
  504.                     seat_price = float(seat_price)
  505.                     CINEMA["!prices"][seat_name] = seat_price/100
  506.             except IndexError:
  507.                 print("'" + cinema + "'" + " is not formatted correctly! (Prices, IndexError)")
  508.                 cont = True
  509.                 break
  510.             except ValueError:
  511.                 print("'" + cinema + "'" + " is not formatted correctly! (Prices, ValueError)")
  512.                 cont = True
  513.                 break
  514.         if cont:
  515.             cont = False
  516.             continue
  517.         cinemas_all[name] = CINEMA
  518. #                                   All cinemas, movies, seats and rates are loaded.
  519. for cinema in cinemas_all:
  520.     for movie in cinemas_all[cinema]["!movies"]:
  521.         A = movie
  522.         for Bcinema in cinemas_all:
  523.             for Bmovie in cinemas_all[Bcinema]["!movies"]:
  524.                 B = Bmovie
  525.                 if A[0] == B[0] and A[1] != B[1]:
  526.                     print("The movie '%s' occurs in more than one place with different time lengths.\nPlease ensure that both have the same name and time length if they are the same movie.\nIf they are different movies, make sure the names are different.\nThey will excluded from the program until fixed." %(A[0]))
  527.                     cinemas_all[cinema]["!movies"].remove(A)
  528.                     cinemas_all[Bcinema]["!movies"].remove(B)
  529. # Organising Timetable for movies:
  530.  
  531. print("Organising a timetable...")
  532. sessions_all = []
  533. try:
  534.     f = open("timetable.txt", "r")
  535.     ## ###############################################################
  536.     ##                                                               #
  537.     ##          (Really Big Obvious Bookmark kinda thing)            #
  538.     ##                                                               #
  539.     ## ###############################################################
  540. except FileNotFoundError:
  541.     MakeTimetable()
  542. else:
  543.     ReadTimetable()
  544.  
  545.  
  546.  
  547.  
  548.  
  549. members = {}
  550. # Load Members
  551. try:
  552.     with open("members.rtf","r") as f:
  553.         for line in f:
  554.             if not line.strip():
  555.                 continue
  556.             parts = line.split(",")
  557.             name = parts[0].strip(' ')
  558.             pas = parts[1].strip(' ')
  559.             members[name] = [pas]
  560. except FileNotFoundError:
  561.     print("Members file not found, making new one.")
  562.     f = open("members.rtf","w")
  563.     f.close()
  564. # Everything is sorted by now
  565.  
  566. print("Ready!")
  567. # ###########################################################
  568. print("\n")
  569. choice = -1
  570. Member = False
  571. while choice != 0:
  572.     print("What would you like to do?:")
  573.     print("0) Exit")
  574.     print("1) Book a movie")
  575.     print("2) Look at session times")
  576.     print("3) Settings")
  577.     if Member:
  578.         print("4) Review movies/Sign out")
  579.     else:
  580.         print("4) Sign in as Member")
  581.     print("Enter a number:")
  582.     choice = get_input(">>> ", int, [-1], [0, 1, 2, 3, 4])
  583.     if choice == 1:#                                                                                       Choosing a movie                 #################
  584.         searching = True
  585.         while searching:
  586.             print("Enter a search term to search for movies, or leave blank to show all movies")
  587.             search = input(">>> ")
  588.             if search:
  589.                 results = []
  590.                 for cinema in cinemas_all:
  591.                     for movie in cinemas_all[cinema]["!movies"]:
  592.                         if search.lower() in movie[0].lower() and movie[0] not in results:
  593.                             results.append(movie[0])
  594.                 if results:
  595.                     count = 1
  596.                     for result in results:
  597.                         print(str(count) + ")", result)
  598.                         count += 1
  599.                     print("Enter the number of the movie to select it or enter 0 to search again:")
  600.                     movie_choice = get_input(">>> ", int, [-1], [x for x in range(count + 1)])
  601.                     if movie_choice != 0:
  602.                         searching = False
  603.                         movie_choice = results[movie_choice - 1]
  604.                 else:
  605.                     print("No results found")
  606.             else:
  607.                 for cinema in sorted(cinemas_all):
  608.                     print(cinema + ":")
  609.                     for movie in cinemas_all[cinema]["!movies"]:
  610.                         print("\t" + movie[0] + " (" + str(movie[1]) + " mins)")
  611.         #  Movie name chosen
  612.         available_cinemas = []
  613.         for cinema in cinemas_all:
  614.             for movie in cinemas_all[cinema]["!movies"]:
  615.                 if movie[0] == movie_choice:
  616.                     available_cinemas.append(cinema)
  617.         if len(available_cinemas) == 1:
  618.             print("Your movie is currently only available in '%s', please select a time to continue." %(available_cinemas[0]))
  619.             cinema_choice = available_cinemas[0]
  620.         else:
  621.             print("Your movie is available in the following cinemas:")
  622.             count = 1
  623.             for cinema in sorted(available_cinemas):
  624.                 print("\t" + str(count) + ")", cinema)
  625.                 count += 1
  626.             print("Choose one:")
  627.             cinema_choice = sorted(available_cinemas)[get_input(">>> ", int, [-1], [int(x) for x in range(1, len(available_cinemas) +1)]) - 1]
  628.             print(cinema_choice)
  629.         count = 1
  630.         available_sessions = []
  631.         for session in cinemas_all[cinema_choice]["!sessions"]:
  632.             if session[0] == movie_choice:
  633.                 print("%i) %s - %s (theatre: %s, %s seats)" %(count, BaseConvert(session[2], 10, 60), BaseConvert(session[3], 10, 60), session[1], session[4]))
  634.                 count += 1
  635.                 available_sessions.append(session)
  636.         session_choie = get_input(">>> ", int, [-1],[x for x in range(1, count)])
  637.         session_choie -= 1
  638.         session_choie = available_sessions[session_choie]
  639.         # If member, Prices are all at 80%
  640.         if not Member:
  641.             print("Are you a member? (Y/N): ")
  642.             if_member = get_input(">>> ", str, [], ["y","Y","yes","Yes","no","No","n","N"])
  643.             if if_member in ["y","Y","yes","Yes"]:
  644.                 SignIn()
  645.             else:
  646.                 print("Sign up as a member for discounts on all your movies!")
  647.         print("Choose tickets:")
  648.         count = 0
  649.         session_rates = [rates[x] * cinemas_all[cinema_choice]["!prices"][session_choie[4]] for x in sorted(rates)]
  650.         cost = 0
  651.         tickets = 0
  652.         for rate in sorted(rates):
  653.             Price = rates[rate] * cinemas_all[cinema_choice]["!prices"][session_choie[4]]
  654.             if Member:
  655.                 Price = Price * 0.8
  656.             print("%s, $%s" %(rate, StripNumber(Price, 2)))
  657.             quant = get_input("Quantity: ", int, ["-"], [])
  658.             cost += quant * session_rates[count]
  659.             tickets += quant
  660.             count += 1
  661.         print("Total: %f" %(cost))
  662.         print("Choose your seats: ")
  663.         Seat_Area = [x for x in cinemas_all[cinema_choice][session_choie[1]][0].split("*")]
  664.         nRows = int(Seat_Area[0])
  665.         nCols = int(Seat_Area[1])
  666.         nSeats = nRows * nCols
  667.         print("   " + "Screen".center(nCols * 3, "-"))
  668.         print("    " + ''.join([str(x+1).ljust(3, " ") for x in range(nCols)]))
  669.         number = 1
  670.         for seatR in range(1, nRows + 1):
  671.             print(" " + SeatTranslator(number, "*".join(Seat_Area))[0].upper(), end = ' ')
  672.             for seatC in range(1, nCols + 1):
  673.                 if number in session_choie[5]:
  674.                     print(" X ", end = "")
  675.                 else:
  676.                     print(" O ", end = "")
  677.                 number += 1
  678.             print()
  679.         print("You have {0} ticket(s), please select {0} seat(s):".format(tickets))
  680. ##        chosen_seats = []
  681.         print("To choose seats, type in either letter-number coordinates (eg. A3, H4),\nor if the rows are numbered (and not lettered) use Row,Column (eg. 1,3 or 15,21) ")
  682.         selected_seats = []
  683.         for i in range(tickets):
  684.             seat_choice = SeatTranslator(Input2Coords(get_input(">>> ", str, [], [])), "{}*{}".format(nRows, nCols))
  685.             while not seat_choice or seat_choice in session_choie[5]:
  686.                 if not seat_choice:
  687.                     print("Invalid seat number")
  688.                 elif seat_choice in session_choie[5]:
  689.                     print("Seat is already taken. Please choose another.")
  690.                 seat_choice = SeatTranslator(Input2Coords(get_input(">>> ", str, [], [])), "{}*{}".format(nRows, nCols))
  691.             session_choie[5].append(seat_choice)# Lookie Lookie
  692.             selected_seats.append(seat_choice - 1)
  693.         if Member:
  694.             SessionToAdd = [sessions_all.index([cinema_choice] + session_choie)]
  695.             for seat in selected_seats:
  696.                 SessionToAdd.append(seat)
  697.             AddSessionToMember(Member, SessionToAdd)
  698.  
  699.  
  700.     elif choice == 4:
  701.         if Member:
  702.  
  703.             print("Sign out? (Y/N)")
  704.             confirm = get_input(">>> ", str, [], ["y","Y","yes","Yes","no","No","n","N"])
  705.             if confirm in ["y","Y","yes","Yes"]:
  706.                 print("Signing out, catchya later {}.".format(Member))
  707.                 Member = False
  708.         else:
  709.             if_member = get_input("Are you a member? (Y/N) ", str, [], ["y","Y","yes","Yes","no","No","n","N"])
  710.             if if_member in ["y","Y","yes","Yes"]:
  711.                 SignIn()
  712.             else:
  713.                 print("Enter your details, becoming a member is free, quick and easy and only costs $35.99!!")
  714.                 nam = get_input("Username: ",str, [], [])
  715.                 while nam in members:
  716.                     print("Username is being used, please select a different one")
  717.                     nam = get_input("Username: ",str, [], [])
  718.                 pin = get_input("Pin number (at least 4 digits): ", int, [], [])
  719.                 while len(str(pin)) < 4:
  720.                     print("Pin must be at least 4 digits.")
  721.                     pin = get_input("Pin number: ", int, [], [])
  722.                 members[nam] = str(pin)
  723.                 AddMember(nam, pin)
  724.  
  725.     elif choice == 3:
  726.         print("Settings:")
  727.         print("")
  728.     elif choice == 2:
  729.         print("Printing times for all cinemas:")
  730.         for cinema in cinemas_all:
  731.             print("Cinema:", cinema)
  732.             PrintTimeTable(cinemas_all[cinema])
  733.     UpdateMembers()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement