如何用Python给游戏加防沉迷
又名:我杀我自己
重点参考
【实战案例】利用Python做出趣味版防沉迷小程序
Python3.7将代码打包成exe程序并添加图标,一分钟学会!
代码
#这是一个防沉迷程序
import psutil
import os
import tkinter
import tkinter.messagebox
import time
class Regulation:
def __init__(self):
self.ban_week=[i for i in range(1,6)] #周一至周五
self.ban_hour=[i for i in range(15)] #凌晨至下午2点
self.allow_duration=2 #可连续在线2小时
self.t_interval=60 #每隔60s监测一次
self.start_time={'hour':99,'minute':99} #记录开始游戏的时间
self.current_time={'hour':0,'minute':0} #记录当前时间
self.week=0 #记录当前星期
def show_warning(self):
root = tkinter.Tk()
root.withdraw() #为了隐藏tk窗口
root.wm_attributes('-topmost',1) #显示在最上层
tkinter.messagebox.showinfo('警告','垃圾!!!!!') #我骂我自己
def show_remind(self):
root = tkinter.Tk()
root.withdraw()
root.wm_attributes('-topmost',1)
tkinter.messagebox.showinfo('提醒','已经游戏两小时,请于5分钟内退出')
def get_time(self):
self.week=int(time.strftime('%w'))
self.current_time['hour']=int(time.strftime('%H'))
self.current_time['minute']=int(time.strftime('%M'))
def record_start_time(self):
self.start_time['hour']=self.current_time['hour']
self.start_time['minute']=self.current_time['minute']
def judge_time(self):
d_hour=self.current_time['hour']-self.start_time['hour']
d_minute=self.current_time['minute']-self.start_time['minute']
if d_hour>=self.allow_duration:
if d_minute>=0: #已达到可允许时长
self.show_remind()
if d_minute>=5: #数次提醒无效,强制退出
self.exit()
def exit(self):
cmd = 'taskkill /F /IM YuanShen.exe'
os.system(cmd) #杀死进程YuanShen.exe(这游戏该死的好玩),可更换为其他
self.show_warning()
def judge(self):
pids = psutil.pids() #获取当前所有进程
self.get_time()
for pid in pids:
p = psutil.Process(pid)
if p.name() == 'YuanShen.exe': #监测有无运行游戏,可更换为其他
if self.week in self.ban_week:
self.exit()
elif self.current_time['hour'] in self.ban_hour:
self.exit()
else:
if self.start_time['hour']==99:
self.record_start_time() #首次监测到游戏,记录时间
self.judge_time()
if __name__=='__main__':
R=Regulation()
while True:
R.judge()
time.sleep(R.t_interval) #监视官需要休息
#打包为.exe文件
#1.打开CMD
#2.准备一个.ico文件作为图标
# 可在线将.png转换为.ico,链接:https://www.easyicon.net/covert/
#3.输入 pyinstaller -F -w -i D:\xxx\.xxx.ico D:\xxx\xxx.py
# 运行成功会提示.exe文件位置
#4.可设为开机自启,WIN+R输入shell:startup,将.exe文件放入文件夹
# 倒也不必,会拖慢开机时间
#此程序运行无窗口,需从任务管理器中结束运行