Advertisement
noctual

Hockey scoreboard Server

Apr 12th, 2021
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.95 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import threading, socket, json, os, time
  4. from tkinter import *
  5.  
  6. LISTEN_PORT = 1111
  7. COUNT_MAX_PEER = 5
  8.  
  9. class Peer(object):
  10.     def __init__(self, server, sock):
  11.         self._sock = sock
  12.         self._server = server
  13.  
  14.     def send(self, data):
  15.         try:
  16.             return self._sock.send(data)
  17.         except IOError:
  18.             self._server.remove(self)            
  19.  
  20. class HockeyScoreboardServer(Tk):
  21.     def __init__(self, port, max_peer):
  22.         super().__init__()
  23.         # init timer
  24.         self.stop = True
  25.         self.timerTime = 0
  26.         self.startTime = 0
  27.         #init server
  28.         self._serv_sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
  29.         #self._serv_sock.setblocking(0)
  30.         self._serv_sock.bind(('', port))
  31.         self._serv_sock.listen(max_peer)
  32.         self._peers = []
  33.         rcv = threading.Thread(target=self._server)
  34.         rcv.start()
  35.         #tk
  36.         self.initUI()
  37.         self.update()
  38.         self.mainloop()
  39.    
  40.     # Server
  41.     def _compress(self, data):
  42.         return (json.dumps(data)+'\n').encode('utf8')
  43.  
  44.     def remove(self, peer):
  45.         self._peers.remove(peer)
  46.  
  47.     def sendAllPeers(self, data):
  48.         message = self._compress(data)
  49.         for peer in self._peers:
  50.             peer.send(message)
  51.  
  52.     def _server(self):
  53.         while True:
  54.             peer_sock, peer_name = self._serv_sock.accept()
  55.             peer = Peer(self, peer_sock)
  56.             self._peers.append(peer)
  57.             peer.send(self._compress({
  58.                 'names': {
  59.                     'team_1': self.sv_team1_name.get(),
  60.                     'team_2': self.sv_team2_name.get()
  61.                  },
  62.                 'score': {
  63.                     'team_1': self.score1.get(),
  64.                     'team_2': self.score2.get()
  65.                  },
  66.                 'timer': {
  67.                     'sec': self.timerTime,
  68.                     'start': self.startTime,
  69.                     'work': not self.stop
  70.                  }
  71.             }))
  72.    
  73.     # Window
  74.     def initUI(self):
  75.         self.title("Хоккейное табло")
  76.         self.configure(background='#1b191a')
  77.         self.resizable(width=False, height=False)
  78.  
  79.         self.frameScoreboard = Frame(self, background="#1b191a")
  80.         self.frameScoreboard.pack(fill=BOTH, padx=10, pady=(10, 10))
  81.  
  82.         # home team entry field
  83.         self.sv_team1_name = StringVar(value="Команда 1")
  84.         self.entry1 = Entry(self.frameScoreboard, textvariable=self.sv_team1_name, font=('Calibri', 16), fg="#ad0304", bg="black", width=10, bd=0)
  85.         self.sv_team1_name.trace("w", lambda name, index, mode, sv=self.sv_team1_name: self.controlStr(self.entry1, 10, "team_1"))
  86.         self.entry1.grid(row=0, column=0, columnspan=2)
  87.  
  88.         # guest team entry field
  89.         self.sv_team2_name = StringVar(value="Команда 2")
  90.         self.entry2 = Entry(self.frameScoreboard, textvariable=self.sv_team2_name, font=('Calibri', 16), fg="#ad0304", bg="black", width=10, bd=0, justify=RIGHT)
  91.         self.sv_team2_name.trace("w", lambda name, index, mode, sv=self.sv_team2_name: self.controlStr(self.entry2, 10, "team_2"))
  92.         self.entry2.grid(row=0, column=2, columnspan=2)
  93.        
  94.         # labels
  95.         Label(self.frameScoreboard, text="Счет", fg="white", bg="#1b191a").grid(row=1, column=0)
  96.         Label(self.frameScoreboard, text="Счет", fg="white", bg="#1b191a").grid(row=1, column=3)
  97.  
  98.         # timer
  99.         self.frameTime = Frame(self.frameScoreboard, background="#1b191a")
  100.         self.frameTime.grid(row=1, column=1, rowspan=2, columnspan=2)
  101.  
  102.         self.labelTimeTitle = Label(self.frameTime, text="Время", fg="white", bg="#1b191a")
  103.         self.labelTimeTitle.pack(side=TOP, fill=X)
  104.  
  105.         self.svMin = StringVar(value="00")
  106.         self.entryMin = Entry(self.frameTime, textvariable=self.svMin, font=('Calibri', 16), foreground="#ad0304", disabledforeground="#ad0304", background="black", disabledbackground="black", width=2, bd=0, justify=RIGHT)
  107.         self.svMin.trace("w", lambda name, index, mode, sv=self.svMin: self.controlStr(self.entryMin, 2, None))
  108.         self.entryMin.pack(side=LEFT, fill=Y)
  109.  
  110.         Label(self.frameTime, text=":", font=('Calibri', 16), fg="#ad0304", bg="black").pack(side=LEFT)
  111.  
  112.         self.svSec = StringVar(value="00")
  113.         self.entrySec = Entry(self.frameTime, textvariable=self.svSec, font=('Calibri', 16), foreground="#ad0304", disabledforeground="#ad0304", background="black", disabledbackground="black", width=2, bd=0)
  114.         self.svSec.trace("w", lambda name, index, mode, sv=self.svSec: self.controlStr(self.entrySec, 2, None))
  115.         self.entrySec.pack(side=LEFT, fill=Y)
  116.        
  117.         # score labels
  118.         self.labelScore1 = Label(self.frameScoreboard, text="00", font=('Calibri', 30), fg="#ad0304", bg="black")
  119.         self.labelScore1.grid(row=2, column=0)
  120.  
  121.         self.labelScore2 = Label(self.frameScoreboard, text="00", font=('Calibri', 30), fg="#ad0304", bg="black")
  122.         self.labelScore2.grid(row=2, column=3)
  123.        
  124.         # managing score home team
  125.         self.frameManagement1 = Frame(self.frameScoreboard, background="#1b191a")
  126.         self.frameManagement1.grid(row=3, column=0)
  127.  
  128.         self.score1 = self.score(self, self.labelScore1, "team_1")
  129.         Button(self.frameManagement1, text="+",
  130.                background="#1b191a", activebackground="#ad0304",
  131.                foreground="#ad0304", activeforeground="#1b191a",        
  132.                padx="3", command=self.score1.Increase).grid(row=0, column=0, pady=5)
  133.         Button(self.frameManagement1, text="-",
  134.                background="#1b191a", activebackground="#ad0304",
  135.                foreground="#ad0304", activeforeground="#1b191a",        
  136.                padx="3", command=self.score1.Decrease).grid(row=0, column=1, pady=5)
  137.  
  138.         # managing timer
  139.         self.frameManagementTime = Frame(self.frameScoreboard, background="#1b191a")
  140.         self.frameManagementTime.grid(row=3, column=1, columnspan=2)
  141.        
  142.         self.buttonTextStartStop = StringVar(value="Старт")
  143.         Button(self.frameManagementTime, textvariable=self.buttonTextStartStop,
  144.                background="#1b191a", activebackground="#ad0304",
  145.                foreground="#ad0304", activeforeground="#1b191a",        
  146.                padx="3", command=self.startstopTimer
  147.         ).grid(row=0, column=0, ipady=5)
  148.        
  149.         # managing score guest team
  150.         self.frameManagement2 = Frame(self.frameScoreboard, background="#1b191a")
  151.         self.frameManagement2.grid(row=3, column=3)
  152.  
  153.         self.score2 = self.score(self, self.labelScore2, "team_2")
  154.         Button(self.frameManagement2, text="+",
  155.                background="#1b191a", activebackground="#ad0304",
  156.                foreground="#ad0304", activeforeground="#1b191a",        
  157.                padx="3", command=self.score2.Increase).grid(row=0, column=0, pady=5)
  158.         Button(self.frameManagement2, text="-",
  159.                background="#1b191a", activebackground="#ad0304",
  160.                foreground="#ad0304", activeforeground="#1b191a",        
  161.                padx="3", command=self.score2.Decrease).grid(row=0, column=1, pady=5)
  162.  
  163.     def update(self):
  164.         if not self.stop:
  165.             deltaTime = self.timerTime - (time.time() - self.startTime)
  166.             if deltaTime > 0:
  167.                 self.setTime(deltaTime)
  168.             else:
  169.                 self.startstopTimer()
  170.                 self.setTime(0)
  171.         self.after(1000, self.update)
  172.  
  173.     def startstopTimer(self):
  174.         if self.stop:
  175.             tempTime = self.getTime()
  176.             if tempTime != None and tempTime > 0:
  177.                self.timerTime = tempTime
  178.                self.buttonTextStartStop.set("Стоп")
  179.                self.entryMin.config(state='disabled')
  180.                self.entrySec.config(state='disabled')
  181.                self.startTime = time.time()
  182.             else:
  183.                self.timerTime = 0
  184.                return
  185.         else:
  186.             self.buttonTextStartStop.set("Старт")
  187.             self.entryMin.config(state='normal')
  188.             self.entrySec.config(state='normal')
  189.             self.timerTime -= (time.time() - self.startTime)
  190.         self.setTime(self.timerTime)
  191.         self.stop = not self.stop
  192.         self.sendAllPeers({
  193.             'timer': {
  194.                 'sec': self.timerTime,
  195.                 'start': self.startTime,
  196.                 'work': not self.stop
  197.             }
  198.         })
  199.  
  200.     def setTime(self, timeInSec):
  201.         self.svMin.set(f'{(timeInSec//60):02.0f}')
  202.         self.svSec.set(f'{(timeInSec%60):02.0f}')
  203.        
  204.     def getTime(self):
  205.         minutes, seconds = self.svMin.get(), self.svSec.get()
  206.         if minutes.isdigit() and seconds.isdigit():
  207.             minutes, seconds = int(minutes), int(seconds)
  208.             if minutes >= 0 and minutes <= 99 and seconds >= 0 and seconds <= 59:
  209.                 return minutes * 60 + seconds
  210.  
  211.     def controlStr(self, entry, max, team):
  212.         text = entry.get()
  213.         if len(text) > max:
  214.             entry.delete(max,END)
  215.         if team != None:
  216.             self.sendAllPeers({'names': {team: entry.get()}})
  217.  
  218.     class score:
  219.         def __init__(self, server, label, team):
  220.             self.server = server
  221.             self.label = label
  222.             self.team = team
  223.             self.scope = 0
  224.  
  225.         def Increase(self):
  226.             if self.scope < 99:
  227.                 self.scope += 1
  228.                 self.__update()
  229.  
  230.         def Decrease(self):
  231.             if self.scope > 0:
  232.                 self.scope -= 1
  233.                 self.__update()
  234.  
  235.         def get(self):
  236.             return self.scope
  237.  
  238.         def __update(self):
  239.             self.label.configure(text=f'{self.scope:02.0f}')
  240.             self.server.sendAllPeers({'score':{self.team: self.scope}})
  241.  
  242. def main():
  243.     HockeyScoreboardServer(LISTEN_PORT, COUNT_MAX_PEER)
  244.  
  245. if __name__ == '__main__':
  246.     main()
  247.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement