Robarry

RF Code (No GUI)

Dec 19th, 2017
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.80 KB | None | 0 0
  1. #A-Level Courswork
  2. #Resultant Forces Calculator
  3. import datetime
  4. import math
  5. import sqlite3
  6. import string
  7. import random
  8. conn = sqlite3.connect('UserBaseV3.db')
  9. conn.execute("PRAGMA foreign_keys=ON")
  10. #turn on foreign keys
  11.  
  12. # change this for what you are modifying
  13. c = conn.cursor()
  14.  
  15.  
  16. """Creates tables for the database"""
  17. ##c.execute('''CREATE TABLE Users
  18. ## (UserID INTEGER PRIMARY KEY AUTOINCREMENT,
  19. ## FirstName TEXT NOT NULL,
  20. ## Surname TEXT NOT NULL,
  21. ## UserName TEXT NOT NULL)''')
  22. ###Autoincrement automatically assigns a chronological number for the userID
  23. ##
  24. ##c.execute('''CREATE TABLE Passwords
  25. ## (PasswordID INTEGER PRIMARY KEY AUTOINCREMENT,
  26. ## PasswordKey TEXT NOT NULL,
  27. ## Password TEXT NOT NULL,
  28. ## UserID INTEGER,
  29. ## FOREIGN KEY(UserID) REFERENCES Users(UserID) ON DELETE CASCADE)''')
  30. ## #Delete on cascade ereases all user info if one piece of data is lost
  31. ##
  32. ##c.execute('''CREATE TABLE Saves
  33. ## (SaveID INTEGER PRIMARY KEY AUTOINCREMENT,
  34. ## SaveName TEXT NOT NULL,
  35. ## UserID INTEGER,
  36. ## FOREIGN KEY(UserID) REFERENCES Users(UserID) ON DELETE CASCADE)''' )
  37. ##
  38. ##c.execute('''CREATE TABLE SaveInfo
  39. ## (SimID INTEGER PRIMARY KEY AUTOINCREMENT,
  40. ## Force1 INTEGER NOT NULL,
  41. ## Bearing1 INTEGER NOT NULL,
  42. ## Force2 INTEGER NOT NULL,
  43. ## Bearing2 INTEGER NOT NULL,
  44. ## Force3 INTEGER NOT NULL,
  45. ## Bearing3 INTEGER NOT NULL,
  46. ## Force4 INTEGER NOT NULL,
  47. ## Bearing4 INTEGER NOT NULL,
  48. ## SaveID INTEGER,
  49. ## FOREIGN KEY(SaveID) REFERENCES Saves(SaveID) ON DELETE CASCADE)''' )
  50. ##
  51. ##conn.commit()
  52. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  53.  
  54. """Create New Account"""
  55. def CreateAccount():
  56. from datetime import datetime
  57. import time
  58. NewUser = True
  59. print("Please fill all of the fields")
  60. FirstName = input("First Name: ").format(str)
  61. Surname = input("Surname: ").format(str)
  62. UserNameCheck = False
  63. """While loop prevents multiple users with the same User Name"""
  64. while UserNameCheck == False:
  65. UserName = input("User Name: ").format(str)
  66. c.execute("SELECT * FROM Users WHERE UserName = '"+UserName+"'")
  67. fetch = c.fetchall()
  68. if len(fetch)>0:
  69. print("That user name is already taken :(")
  70. print("Please enter a new username: ")
  71. else:
  72. UserNameCheck = True
  73. date_entry = input("Please enter your Date of Birth in the format DD/MM/YYYY")
  74. #print(date_entry)
  75. Day, Month, Year = map(int, date_entry.split("/"))
  76. DOB = Day,Month,Year
  77. #print(DOB)
  78. #DOB = datetime.date(Year, Month, Day)
  79. #print(DOB)
  80. """Check the Password is correct"""
  81. check = False
  82. while check == False:
  83. password = input("\nPassword: ").upper()
  84. passcheck = input("\nPlease re-enter your password: ").upper()
  85. if passcheck == password:
  86. check = True
  87. else:
  88. print("Passwords did not match")
  89. username = 0
  90. EncryptedPassword, key = EncryptPassword(password,username,NewUser)
  91. #print(EncryptedPassword, key)
  92.  
  93.  
  94. """Insert the four fields into the table"""
  95.  
  96. c.execute("INSERT INTO Users VALUES (NULL,?,?,?)", (FirstName,Surname,UserName))
  97. conn.commit()
  98. data = c.execute("SELECT UserID FROM Users WHERE UserName=?",(UserName,))
  99. UserID = c.fetchone()[0]
  100. #print(UserID)
  101. c.execute("INSERT INTO Passwords VALUES (NULL,?,?,?)", (key, EncryptedPassword, UserID))
  102. print("Account Created!")
  103. time1 = time.strftime("%H:%M")
  104. date1 = time.strftime("%d/%b/%Y")
  105. f = open("Log.txt",'a')
  106. #Records which user logged in and the time and ate of their login
  107. f.write(("User: {0}\n"
  108. +"Created account at: {1}\n"
  109. +"Date: {2}\n\n").format(UserName, time1, date1))
  110. f.close()
  111. conn.commit()
  112. #conn.close()
  113. CurrentUser = UserName
  114. return CurrentUser
  115.  
  116. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  117. """Encrypts users password with a key"""
  118.  
  119. def EncryptPassword(word,username,NewUser):
  120. if NewUser == True:
  121. key = id_generator()
  122. else:
  123. #print(username)
  124. GetUID = c.execute("SELECT UserID FROM Users WHERE UserName =?",(username,))
  125. #print(GetUID)
  126. UserID = c.fetchone()[0]
  127. #print(UserID)
  128. GetKey = c.execute("SELECT PasswordKey FROM Passwords WHERE UserID =?",(UserID,))
  129. key = c.fetchone()[0]
  130. #uses a 26 character key
  131. #print(key)
  132. EncryptedPassword = "" # the Cypher text
  133. p = 0 # pointer for the key
  134. for char in word:
  135. EncryptedPassword += chr(ord(char) ^ ord(key[p]))
  136. p += 1
  137. if p==len(word):
  138. p = 0
  139. return EncryptedPassword, key
  140.  
  141. def id_generator(size=26, chars=string.ascii_uppercase + string.digits):
  142. return ''.join(random.choice(chars) for _ in range(size))
  143.  
  144. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  145. """Existing user Login function"""
  146. def Login():
  147. import time
  148. LogPass = False
  149. NewUser = False
  150. while LogPass == False:
  151. username = input("Username: ")
  152. password = input("\nPassword: ").upper()
  153. #print(username,password,shiftPass)
  154.  
  155. shiftPass = EncryptPassword(password,username,NewUser)
  156. #print(shiftPass[0])
  157. GetID = c.execute("SELECT UserID FROM Users WHERE UserName =?",(username,))
  158. UserID = str(c.fetchone()[0])
  159. #print(UserID)
  160. GetPword = c.execute("SELECT Password FROM Passwords WHERE UserID =?",(UserID,))
  161. PwordCheck = c.fetchone()[0]
  162. #print(PwordCheck)
  163. #Checks User info against database info
  164. #print(shiftPass[0])
  165. #print(PwordCheck)
  166. if PwordCheck == shiftPass[0]:
  167. print("login Successfull!")
  168. LogPass = True
  169. time1 = time.strftime("%H:%M")
  170. date1 = time.strftime("%d/%b/%Y")
  171. f = open("Log.txt",'a')
  172. #Records which user logged in and the time and ate of their login
  173. f.write(("User: {0}\n"
  174. +"logged in at: {1}\n"
  175. +"Date: {2}\n\n").format(username, time1, date1))
  176. f.close()
  177. """if the login is sucessful, the Current User' username is
  178. kept in the system for further use"""
  179. CurrentUser = username
  180. return CurrentUser
  181.  
  182. else:
  183. print("Login not successful, please try again")
  184.  
  185. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  186.  
  187. def GetValues():
  188. ForceCheck = False
  189. while ForceCheck == False:
  190. try:
  191. Force1 = int(input("Enter the magnitude of Force 1: "))
  192. Force2 = int(input("Enter the magnitude of Force 2: "))
  193. Force3 = int(input("Enter the magnitude of Force 3: "))
  194. Force4 = int(input("Enter the magnitude of Force 4: "))
  195. Forces = [Force1,Force2,Force3,Force4]
  196. ForceCheck = True
  197. except ValueError:
  198. print("That is not a number!")
  199.  
  200.  
  201. BearingCheck = False
  202. while BearingCheck == False:
  203. ExceptBearing1 = False
  204. while ExceptBearing1 == False:
  205. try:
  206. Bearing1 = int(input("Enter the bearing of Force 1 (0 =< x =< 360)"))
  207. if Bearing1 > 360:
  208. print("Bearing 1 is too big")
  209. elif Bearing1 < 0:
  210. print("Bearing 1 is too small")
  211. else:
  212. ExceptBearing1 = True
  213. except ValueError:
  214. print("That is not a number!")
  215.  
  216. ExceptBearing2 = False
  217. while ExceptBearing2 == False:
  218. try:
  219. Bearing2 = int(input("Enter the bearing of Force 2 (0 =< x =< 360)"))
  220. if Bearing2 > 360:
  221. print("Bearing 2 is too big")
  222. elif Bearing2 < 0:
  223. print("Bearing 2 is too small")
  224. else:
  225. ExceptBearing2 = True
  226. except ValueError:
  227. print("That is not a number!")
  228.  
  229. ExceptBearing3 = False
  230. while ExceptBearing3 == False:
  231. try:
  232. Bearing3 = int(input("Enter the bearing of Force 3 (0 =< x =< 360)"))
  233. if Bearing3 > 360:
  234. print("Bearing 3 is too big")
  235. elif Bearing3 < 0:
  236. print("Bearing 3 is too small")
  237. else:
  238. ExceptBearing3 = True
  239. except ValueError:
  240. print("That is not a number!")
  241.  
  242. ExceptBearing4 = False
  243. while ExceptBearing4 == False:
  244. try:
  245. Bearing4 = int(input("Enter the bearing of Force 4 (0 =< x =< 360)"))
  246. if Bearing4 > 360:
  247. print("Bearing 4 is too big")
  248. elif Bearing4 < 0:
  249. print("Bearing 4 is too small")
  250. else:
  251. ExceptBearing4 = True
  252. except ValueError:
  253. print("That is not a number!")
  254.  
  255. Bearings = [Bearing1,Bearing2,Bearing3,Bearing4]
  256. BearingCheck = True
  257. Calculations(Forces,Bearings)
  258.  
  259. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  260.  
  261. def Calculations(Forces, Bearings):
  262. F = Forces
  263. B = Bearings
  264. V1 = [F[0]*math.degrees(math.cos(B[0])),F[0]*math.degrees(math.sin(B[0]))]
  265. V2 = [F[1]*math.degrees(math.cos(B[1])),F[1]*math.degrees(math.sin(B[1]))]
  266. V3 = [F[2]*math.degrees(math.cos(B[2])),F[2]*math.degrees(math.sin(B[2]))]
  267. V4 = [F[3]*math.degrees(math.cos(B[3])),F[3]*math.degrees(math.sin(B[3]))]
  268. VR = [(V1[0]+V2[0]+V3[0]+V4[0]),(V1[0]+V2[1]+V3[1]+V4[1])]
  269. RFMagnitude = round(math.sqrt((VR[0]**2)+(VR[1]**2)),2)
  270. RFBearing = round(math.degrees(math.atan(VR[1]/VR[0])),2)
  271. print(RFMagnitude)
  272. print(RFBearing)
  273.  
  274. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  275.  
  276. def SaveSim(CurrentUserID):
  277. complete = False
  278. """While loop stops a program crash for save errors (e.g Poor save names)"""
  279. while complete == False:
  280. print("Would you like to save your simulation?")
  281. save = input("Save Simulation? (Y/N)").upper()
  282. if save == 'N':
  283. print("Simulation not saved")
  284. complete = True
  285. elif save == 'Y':
  286. print("Please name your save")
  287. NameOk = False
  288. """While loop prevents multiple saves with the same name"""
  289. while NameOk == False:
  290. SaveName = input("Save Name: ")
  291. """Checks new save name with prexisting saves of current user"""
  292. c.execute("SELECT * FROM Saves WHERE UserID = (?) AND SaveName = (?)",(CurrentUserID, SaveName))
  293. fetch = fetchall()
  294. if len(fetch)>0:
  295. print("You already have a simulation with that name\n")
  296. print("Would you like to overwrite?\n")
  297. """User chooses which simulation to save"""
  298. Overwrite = input("Overwrite? (Y/N)").upper()
  299. if Overwrite == 'Y':
  300. print("Saving Simulation")
  301. """Deletes old save and writes new one"""
  302. c.execute("DELETE FROM Saves WHERE UserID = (?) AND SaveName = (?)",(CurrentUserID, SaveName))
  303. c.execute("INSERT INTO Saves VALUES (NULL,?,?)",(SaveName,CurrentUserID))
  304. c.execute("INSERT INTO SaveInfo VALUES (NULL,?,?,?,?,?,?,?,?,?)",(Forces[0],Bearing[0],Forces[1],Bearing[1],Forces[2],Bearing[2],Forces[3],Bearing[3],))
  305. print("Simulation saved!")
  306. conn.commit()
  307. #conn.close()
  308. NameOk = True
  309. complete = True
  310.  
  311. elif Overwrite == 'N':
  312. Discard = input("Discard save? (Y/N)").upper()
  313. if Discard == 'Y':
  314. NameOk = True
  315. else:
  316. print("Please change the save name:")
  317. else:
  318. print("input not recogonised")
  319.  
  320.  
  321.  
  322. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  323. def loadSim(CurrentUserID):
  324. load = False
  325. while load == False:
  326. print("Please enter the save name: ")
  327. savename = input("Save name: ").title()
  328. """Takes user save name and cross references it in the database against the current user's name"""
  329. c.execute("SELECT * FROM Saves WHERE UserID = '"+CurrentUserID+"' AND SaveName = '"+savename+"'")
  330. fetch = c.fetchall()
  331. if len(fetch) >0:
  332. conn.commit()
  333. Forces = c.execute("SELECT Force1, Force2, Force3 AND Force4 FROM SaveInfo WHERE UserID = (?)",(CurrentUserID))
  334. Bearings = c.execute("SELECT Bearing1, Bearing2, Bearing3, Bearing4 FROM SaveInfo Where UserID = (?)",(CurrentUserID))
  335. return Forces, Bearings
  336. load = True
  337. else:
  338. print("Save name not recogonised, would you like to try again?")
  339. TryAgain = input("Y/N")
  340. if TryAgain == 'N':
  341. load = True
  342. if TryAgain == 'Y':
  343. print("")
  344. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Add Comment
Please, Sign In to add comment