Advertisement
Guest User

CellularAutomaton.py

a guest
May 20th, 2018
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.67 KB | None | 0 0
  1. import pygame, random, re, colorsys
  2. from tkinter import *
  3. #from Classes.ButtonClass import Button
  4. pygame.init();
  5. width, height = 250, 200
  6. screen1 = pygame.display.set_mode((width, height))
  7. pygame.display.set_caption('Cellular Automata')
  8. clock = pygame.time.Clock()
  9. crashed = False
  10. quitted = False
  11. first = True
  12. #fontPath = 'C:/Users/Moist/Desktop/CACA/Fonts/Little Conquest.ttf'
  13. fontPath = 'F:/CACA/Fonts/Little Conquest.ttf'
  14. fontPath2 = 'F:/CACA/Fonts/Nineteen Ninety Three.otf'
  15. small = pygame.font.Font(fontPath, 15)
  16. small2 = pygame.font.Font(fontPath2, 15)
  17. medium = pygame.font.Font(fontPath, 30)
  18. large = pygame.font.Font(fontPath, 60)
  19. buttons = []
  20.  
  21. mode = "menu"
  22. loggedIn = False
  23.  
  24. white = (255, 255, 255)
  25. black = (0, 0, 0)
  26. red = (255, 0, 0)
  27. green = (0, 255, 0);
  28. blue = (0, 0, 255)
  29. light_grey = (240, 240, 240)
  30. grey = (127, 127, 127)
  31.  
  32. #python -m cProfile -o temp.dat F:\CACA\CellularAutomata.py
  33.  
  34.    ###    ##           ##      ####    ####   ######   ####
  35.  ###  ##  ##          ####    ##   #  ##   #  ##      ##   #
  36. ##        ##         ##  ##    ###     ###    #####    ###
  37. ##        ##         ######       ##      ##  ##          ##
  38.  ###  ##  ##        ##    ##  #   ##  #   ##  ##      #   ##
  39.    ###    ########  ##    ##   ###     ###    ######   ###
  40.  
  41. ######################## BUTTON ########################
  42.  
  43. class PGButton:
  44.     def __init__(self, xt, yt, wt, ht, name, valuet):
  45.         self.x = xt
  46.         self.y = yt
  47.         self.w = wt
  48.         self.h = ht
  49.         self.rect = pygame.Rect(xt, yt, wt, ht)
  50.         self.value = valuet
  51.         self.text = small.render(name, False, black)
  52.        
  53.     def display(self):
  54.         #Could have a value to say which screen to draw to
  55.         if self.rect.collidepoint((mouseX, mouseY)):
  56.             pygame.draw.rect(screen1, (210, 210, 210), self.rect, 0)
  57.         else:
  58.             pygame.draw.rect(screen1, light_grey, self.rect, 0)
  59.            
  60.         pygame.draw.line(screen1, black, (self.x, self.y), (self.x + self.w, self.y), 1)
  61.         pygame.draw.line(screen1, black, (self.x + self.w, self.y), (self.x + self.w, self.y + self.h), 1)
  62.         pygame.draw.line(screen1, black, (self.x + self.w, self.y + self.h), (self.x, self.y + self.h), 1)
  63.         pygame.draw.line(screen1, black, (self.x, self.y + self.h), (self.x, self.y), 1)
  64.        
  65.         screen1.blit(self.text, (self.x + 3, self.y + 3))
  66.     def pressed(self):
  67.         self.b = False
  68.         if self.rect.collidepoint((mouseX, mouseY)):
  69.             if event.type == pygame.MOUSEBUTTONDOWN:
  70.                 self.b = True
  71.         return self.b
  72.  
  73.     def val(self):
  74.         return self.value
  75.  
  76. ######################## Log In Class ########################
  77.  
  78. class login:
  79.     def __init__(self, master, errorMsg):
  80.         self.submitted = False
  81.        
  82.         self.master = master
  83.         master.title("Log In")
  84.  
  85.         #master.geometry("200x150")
  86.        
  87.         self.label = Label(master, text = "Enter log in details.")
  88.         self.label.pack()
  89.  
  90.         if errorMsg != "":
  91.             self.errorMsgLab = Label(master, text = errorMsg, fg = "red")
  92.             self.errorMsgLab.pack()
  93.            
  94.         self.uNameB = Entry(master)
  95.         self.labelU = Label(master, text = "Username:")
  96.         self.labelU.pack() #side = LEFT)
  97.         self.uNameB.pack(padx = 10)
  98.        
  99.         self.pWordB = Entry(master)
  100.         self.labelP = Label(master, text = "Password:")
  101.         self.labelP.pack() #side = LEFT)
  102.         self.pWordB.pack(padx = 10)
  103.  
  104.         self.submitButt = Button(master, text = "Submit", command = self.submit)
  105.         self.submitButt.pack(pady = 5)
  106.    
  107.     def submit(self):
  108.         self.submitted = True
  109.         info = [self.uNameB.get(), self.pWordB.get()]
  110.         self.master.destroy()
  111.         logIn(True, info)
  112.        
  113.     def getInfo(self):
  114.         if self.submitted:
  115.             return info
  116.  
  117. ######################## Sign Up Class ########################
  118.  
  119. class signup:
  120.     def __init__(self, master, errorMsg):
  121.         self.submitted = False
  122.        
  123.         self.master = master
  124.         master.title("Sign Up")
  125.         self.label = Label(master, text = "Fill out this form to sign up.")
  126.         self.label.pack()
  127.  
  128.         if errorMsg != "":
  129.             self.errorMsgLab = Label(master, text = errorMsg, fg = "red")
  130.             self.errorMsgLab.pack()
  131.            
  132.         self.uNameB = Entry(master)
  133.         self.labelU = Label(master, text = "Username:")
  134.         self.labelU.pack() #side = LEFT)
  135.         self.uNameB.pack(padx = 10)
  136.        
  137.         self.pWordB = Entry(master)
  138.         self.labelP = Label(master, text = "Password:")
  139.         self.labelP.pack() #side = LEFT)
  140.         self.pWordB.pack(padx = 10)
  141.  
  142.         self.submitButt = Button(master, text = "Submit", command = self.submit)
  143.         self.submitButt.pack(pady = 5)
  144.    
  145.     def submit(self):
  146.         self.submitted = True
  147.         info = [self.uNameB.get(), self.pWordB.get()]
  148.         self.master.destroy()
  149.         signUp(True, info)
  150.        
  151.     def getInfo(self):
  152.         if self.submitted:
  153.             return info
  154.        
  155. ######################## Pixel Class ########################
  156.  
  157. class pixel():
  158.     def __init__(self, idt): #, xt, yt, colt):
  159.         self.x = random.randrange(width) #xt
  160.         self.y = random.randrange(height) #yt
  161.         self.px = self.x
  162.         self.py = self.y
  163.         self.pos = int(self.y * width + self.x)
  164.         self.id = idt
  165.  
  166.         r, g, b = colorsys.hsv_to_rgb(self.id / 255, 1, 1)
  167.         self.col = (r * 255, g * 255, b * 255)
  168.        
  169.     def move(self):
  170.         s = self.surrounding()
  171.         surroundingBool = [False if i == None else True for i in s]
  172.  
  173.         r1 = random.random()
  174.         r2 = random.random()
  175.         r3 = random.random()
  176.        
  177.         if r1 <= 0.333:
  178.             if r3 < 0.5 and not surroundingBool[4]: self.x += 1
  179.             elif not surroundingBool[3]: self.x -= 1
  180.         elif r1 <= 0.666:
  181.             if r3 < 0.5 and not surroundingBool[6]: self.y += 1
  182.             elif not surroundingBool[1]: self.y -= 1
  183.         else:
  184.             if r2 < 0.25 and not surroundingBool[7]:
  185.                 self.x += 1
  186.                 self.y += 1
  187.             elif r2 < 0.5 and not surroundingBool[2]:
  188.                     self.x += 1
  189.                     self.y -= 1
  190.             elif r2 < 0.75 and not surroundingBool[5]:
  191.                     self.x -= 1
  192.                     self.y += 1
  193.             elif not surroundingBool[0]:
  194.                     self.x -= 1
  195.                     self.y -= 1
  196.                    
  197.         self.x %= width
  198.         self.y %= height
  199.         self.pos = self.y * width + self.x
  200.  
  201.     def surrounding(self):
  202.         self.surr = [None, None, None, None, None, None, None, None]
  203.  
  204.         for i in range(9):
  205.         #for x in range(-1, 2):
  206.             #for y in range(-1, 2):
  207.                 if i != 5:
  208.                     x = i % 3 - 2
  209.                     y = int((i % 3) / 3) - 1
  210.                        
  211.                 if x == 0 and y == 0:
  212.                     pass
  213.                 else:
  214.                     PAI = allPixels[(self.x + x) % width][(self.y + y) % height] if allPixels[(self.x + x) % width][(self.y + y) % height] != None else None
  215.                    
  216.                     self.surr[(y * 3) + x] = (PAI)
  217.        
  218.         return self.surr
  219.  
  220. ######################## Cellular Automata Class ########################
  221.    
  222. class CellularAuto:
  223.     def __init__(self, idt):
  224.         self.pixels = []
  225.         self.id = idt
  226.         self.pixels.append(pixel(self.id))
  227.  
  228.     def display(self):
  229.         for pix in self.pixels:
  230.             screen2.set_at((pix.x, pix.y), pix.col)
  231.        
  232.     def update(self):
  233.         for pix in self.pixels:
  234.             pix.px = pix.x
  235.             pix.py = pix.y
  236.             pix.move()
  237.  
  238.     def addPix(self):
  239.         self.pixels.append(pixel(self.id))
  240.  
  241. ######  ##     ##  ##    ##     ###    ##########  ##   #####   ##    ##   ####
  242. ##      ##     ##  ####  ##   ###  ##      ##      ##  ##   ##  ####  ##  ##   #
  243. #####   ##     ##  ## ## ##  ##            ##      ##  ##   ##  ## ## ##   ###
  244. ##      ##     ##  ##  ####  ##            ##      ##  ##   ##  ##  ####      ##
  245. ##       ##   ##   ##   ###   ###  ##      ##      ##  ##   ##  ##   ###  #   ##
  246. ##        #####    ##    ##     ###        ##      ##   #####   ##    ##   ###
  247.  
  248. ######################## LOG OUT ########################
  249.  
  250. def logout():
  251.     global first, loggedIn, USERNAME
  252.     loggedIn = False
  253.     USERNAME = ""
  254.     first = True
  255.    
  256. ######################## MENU ########################
  257.  
  258. def menu():
  259.     global first, screen1, buttons, mode
  260.     if first:
  261.         first = False
  262.         buttons = []
  263.         if not loggedIn:
  264.             width, height = 250, 230
  265.             buttons.append(PGButton(10, 80, 40, 20, "Start", "start"))
  266.             buttons.append(PGButton(10, 110, 135, 20, "Custom Automaton", "custom"))
  267.             buttons.append(PGButton(10, 140, 55, 20, "Log In", "login"))
  268.             buttons.append(PGButton(10, 170, 115, 20, "Create Account", "signup"))
  269.             buttons.append(PGButton(10, 200, 45, 20, "Quit", "quit"))
  270.         else:
  271.             sw, sh = large.size(USERNAME)
  272.             if sw > 250:
  273.                 w = sw
  274.             else:
  275.                 w = 250
  276.             width, height = w, 280
  277.             buttons.append(PGButton(10, 130, 40, 20, "Start", "start"))
  278.             buttons.append(PGButton(10, 160, 135, 20, "Custom Automaton", "custom"))
  279.             buttons.append(PGButton(10, 190, 110, 20, "Your Automata", "yours"))
  280.             buttons.append(PGButton(10, 220, 60, 20, "Log Out", "logout"))
  281.             buttons.append(PGButton(10, 250, 45, 20, "Quit", "quit"))
  282.  
  283.         screen1 = pygame.display.set_mode((width, height))
  284.  
  285.     screen1.fill((white));
  286.  
  287.    
  288.     if not loggedIn:
  289.         screen1.blit(large.render("Welcome", False, black), (10, 10))
  290.     else:
  291.         screen1.blit(large.render("Welcome", False, black), (10, 10))
  292.         screen1.blit(large.render(USERNAME, False, black), (10, 60))
  293.        
  294.     but = doButtons()
  295.    
  296.     if but != "":
  297.         if but == "start":
  298.             mode = "startmenu"
  299.             first = True
  300.             startMenu()
  301.         elif but == "custom":
  302.             mode = "CA"
  303.             first = True
  304.             CustomA()
  305.         elif but == "login":
  306.             mode = "login"
  307.             first = True
  308.             logIn(False, "")
  309.         elif but == "signup":
  310.             mode = "signup"
  311.             first = True
  312.             signUp(False, "")
  313.         elif but == "quit":
  314.             global quitted
  315.             quitted = True
  316.         elif but == "yours":
  317.             mode = "YA"
  318.             first = True
  319.             YA()
  320.         elif but == "logout":
  321.             mode = "menu"
  322.             logout()
  323.            
  324. ######################## Log In Function ########################
  325.  
  326. def logIn(parsed, loginDetails):
  327.     global first, loggedIn
  328.     if first:
  329.         first = False
  330.         root = Tk()
  331.         if parsed == False and loginDetails != "":
  332.             gui = login(root, loginDetails)
  333.         else:
  334.             gui = login(root, "")
  335.         root.mainloop()
  336.     if parsed:
  337.         if loginDetails[0] == "" or loginDetails[1] == "":
  338.             first = True
  339.             logIn(False, "Please fill both fields.")
  340.         elif len(loginDetails[1]) < 8:
  341.             first = True
  342.             logIn(False, "Password is too short")
  343.         else:
  344.             users = eval(open("F:/CACA/Users.txt").read())
  345.             uNameTrue = False
  346.             for uName in users:
  347.                 if not loggedIn:
  348.                     if loginDetails[0] == uName and loginDetails[1] == users[uName]:
  349.                         loggedIn = True
  350.                         global USERNAME
  351.                         USERNAME = uName
  352.                         first = True
  353.                     elif loginDetails[0] == uName:
  354.                         uNameTrue == True
  355.                    
  356.             if not loggedIn:
  357.                 if uNameTrue:
  358.                     first = True
  359.                     logIn(False, "Incorrect Password")
  360.                 else:
  361.                     first = True
  362.                     logIn(False, "Incorrect Username")
  363.  
  364. ######################## Sign Up Function ########################
  365.  
  366. def signUp(parsed, signUpDetails):
  367.     global first, loggedIn
  368.     problem = False
  369.     if first:
  370.         first = False
  371.         root = Tk()
  372.         if parsed == False and signUpDetails != "":
  373.             gui = signup(root, signUpDetails)
  374.         else:
  375.             gui = signup(root, "")
  376.         root.mainloop()
  377.     if parsed:
  378.         if len(signUpDetails[1]) < 8:
  379.             first = True
  380.             signUp(False, "Your password is too short.")
  381.         else:
  382.             users = eval(open("F:/CACA/Users.txt").read())
  383.             for uName in users:
  384.                 if not problem:
  385.                     if signUpDetails[0] == uName:
  386.                         problem = True
  387.                         first = True
  388.                         signUp(False, "Existing username")
  389.             if not problem:
  390.                 if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', signUpDetails[1]):
  391.                     usersfile = open("F:/CACA/Users.txt", "w")
  392.                     usersfile.seek(0)
  393.                     usersfile.truncate()
  394.                     usersfile.write("{")
  395.                     for uName in users:
  396.                         usersfile.write("\"" + uName + "\":\"" + users[uName] + "\", ")
  397.                     users[signUpDetails[0]] = signUpDetails[1]
  398.                     usersfile.write("\"" + signUpDetails[0] + "\":\"" + signUpDetails[1] + "\"}")
  399.                     loggedIn = True
  400.                     global USERNAME
  401.                     USERNAME = signUpDetails[0]
  402.                     first = True
  403.                 else:
  404.                     first = True
  405.                     signUp(False, "Invalid characters in password")
  406.  
  407. def startMenu():
  408.     global first, screen1, buttons, mode
  409.     if first:
  410.         first = False
  411.         buttons = []
  412.         buttons.append(PGButton(10, 220, 60, 20, "Go Back", "back"))
  413.         buttons.append(PGButton(75, 220, 120, 20, "Start simulation", "startSim"))
  414.         width, height = 205, 250
  415.  
  416.         screen1 = pygame.display.set_mode((width, height))
  417.  
  418.     screen1.fill((white))
  419.  
  420.     screen1.blit(small2.render("This will do shit yanno", False, black), (15, 10))
  421.     screen1.blit(small2.render("More damned lines", False, black), (15, 26))
  422.     screen1.blit(small2.render("More linezzzzzzzzzzz", False, black), (15, 42))
  423.     screen1.blit(small2.render("Line number four", False, black), (15, 58))
  424.     screen1.blit(small2.render("This will have more ", False, black), (15, 74))
  425.     screen1.blit(small2.render("informative stuff in", False, black), (15, 90))
  426.     screen1.blit(small2.render("the end i promise lol", False, black), (15, 106))
  427.  
  428.     but = doButtons()
  429.    
  430.     if but == "back":
  431.         mode = "menu"
  432.         first = True
  433.         menu()
  434.     elif but == "startSim":
  435.         mode = "CA"
  436.         first = True
  437.         CA()
  438.  
  439. def CA():
  440.     global first, buttons, allPixels, CAs, screen2, width, height
  441.     if first:
  442.         first = False
  443.         width, height = 1200, 600
  444.         buttons = []
  445.         allPixels = []
  446.         CAs = []
  447.         CAs.append(CellularAuto(int(random.random() * 255)))
  448.         CAs.append(CellularAuto(int(random.random() * 255)))
  449.         for x in range(width):
  450.             allPixels.append([])
  451.             for y in range(height):
  452.                 allPixels[x].append(None)
  453.         screen2 = pygame.display.set_mode((width, height))
  454.        
  455.     screen2.fill(white)
  456.     for i in range(10):
  457.         CAs[0].addPix()
  458.         CAs[1].addPix()
  459.     for CellularAutomata in CAs:
  460.         for pix in CellularAutomata.pixels:
  461.             allPixels[pix.px][pix.py] = None
  462.     for CellularAutomata in CAs:
  463.         for pix in CellularAutomata.pixels:
  464.             allPixels[pix.x][pix.y] = pix
  465.  
  466.  
  467.         CellularAutomata.update()
  468.         CellularAutomata.display()
  469.  
  470. def doButtons():
  471.     but = ""
  472.     for b in buttons:
  473.         b.display()
  474.         if b.pressed():
  475.             but = b.val()
  476.     return but
  477.  
  478. ######################## Main Loop ########################
  479.  
  480. while not quitted:  
  481.     for event in pygame.event.get():
  482.         if event.type == pygame.QUIT:
  483.             quitted = True
  484.         mouseX, mouseY = pygame.mouse.get_pos()
  485.  
  486.     pygame.display.update()
  487.     if mode == "menu":
  488.         menu()
  489.     elif mode == "startmenu":
  490.         startMenu()
  491.     elif mode == "CA":
  492.         CA()
  493.     elif mode == "login":
  494.         logIn(False, "")
  495.     elif mode == "signup":
  496.         signUp(False, "")
  497.     elif mode == "run":
  498.         run()
  499.  
  500.     clock.tick(60)
  501.  
  502. pygame.quit()
  503. quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement