Вы находитесь на странице: 1из 11

ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ АВТОНОМНОЕ ОБРАЗОВАТЕЛЬНОЕ

УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ


«НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ ИТМО»

Факультет безопасности информационных технологий


Дисциплина:
«Технологии и методы программирования»

Отчет по лабораторной работе 2

Выполнил:
Студент гр.N33461
Нгуен Тхань Чунг

Проверил:
Ищенко Алексей Петрович

Санкт-Петербург

2022
1. Цель работы:
Разработать простейшую программу, запрашивающую ФИО пользователя и заносящую эту
информацию в текстовый файл. Если такое ФИО имеется в файле, то выдавать об этом
сообщение. После ввода информации программа должна завершать работу и сообщать
пользователю о лимитах ее использования (временнОго или количества запусков). По
достижении лимита запусков программа должна предложить пользователю приобрести ее
полную версию или деинсталлировать себя. При повторной установке программы, она
должна сообщать о своем предыдущем нахождении на этом компьютере и сверяться с
прошлыми лимитами пользования (т.е. не давать их суммарно превысить). На защиту
принимается инсталлятор, программа и деинсталлятор (программа регистрируется в
системе, и Вы знаете, где это посмотреть и как ее «взломать»). Выполняются две версии
программы (можно сочетать в одной)
а) Time-limited (ограничение по времени сделать не более 3 минут, чтобы можно
было проследить в момент сдачи достижение лимита).
б) Start-limited (ограничение на количество запусков тоже должно быть наглядным,
например – 4-5)

2. Порядок выполнения работы


а) Time-limited (ограничение по времени сделать не более 3 минут, чтобы можно
было проследить в момент сдачи достижение лимита)
from datetime import datetime
import time
import os
import pygame, sys
from pygame.locals import *
from pygame import mixer

# Initialize the pygame


pygame.init()

# Create the screen (width, height)


screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("TBZ24's game")

# Background image and Background music


background = pygame.image.load('./assets/background.jpg')
pygame.display.set_icon(pygame.image.load('./assets/name.png'))
mixer.music.load('./assets/background music.mp3')
mixer.music.play(-1)

# ID
idImg = pygame.image.load('./assets/id.png')
idX = 240
idY = 93

startTime = datetime.now()

def id(x, y):


screen.blit(idImg, (x, y))

def printMsg(msg, height, color):


txt_surface = font.render(msg, True, color)
width = txt_surface.get_width()
screen.blit(txt_surface, ((800-width)/2, height))

def process(input):
endTime = datetime.now()
totalTime = endTime - startTime
totalTime = int(totalTime.total_seconds())
with open("info.txt",'r+') as f:
timeLive = int(f.readline().replace('\n',''))
timeLive -= totalTime
message1 = ''
if (timeLive <= 0):
message1 = 'Trial is over, please buy the official version!'
else:
message1 = 'Time trail left - ' + str(timeLive) + 's'
with open("info.txt",'r+') as f:
f.write(str(timeLive) + '\n')
f.write(path)

names = []
isExistingName = 0
if os.path.isfile("names.txt"):
f = open("names.txt",'r+')
tmp = f.readline().replace('\n','')
while (tmp != ''):
names.append(tmp)
tmp = f.readline().replace('\n','')
else:
f = open("names.txt",'a+')

for x in names:
if (input == x):
isExistingName = 1
break
message2 = ''
if (isExistingName == 0):
f.write(input+'\n')
message2 = 'Name has been added'
else:
message2 = 'Name already exists'
f.close
return [message2, message1]

path = os.getcwd()
font = pygame.font.SysFont('varsity_regular.ttf', 32)

def main():
os.chdir(r'/home/mh2107/Documents/')
if not os.path.isdir('.Lab2'):
os.mkdir('.Lab2')
os.chdir('.Lab2')

timeLive = 20
oldPath = ''
if os.path.isfile('info.txt'):
os.system("chmod -v 700 info.txt > /dev/null 2>&1")
with open("info.txt",mode='r') as f:
timeLive = int(str(f.readline().replace('\n','')))
oldPath = f.readline().replace('\n','')
else:
with open("info.txt",mode='w') as f:
f.write(str(timeLive) + '\n')
f.write(path)

# Create user interface 1


messagePath = ''
if ((path != oldPath) & (oldPath != '')):
messagePath = 'OldPath: ' + oldPath

# Create input box


input_box = pygame.Rect(240, 140, 200, 34) #x, y, width, height
input_Name = ''
nameTyped = False
running = True
message = []
while running:
# Background image
screen.blit(background, (0,0))

# Trial is over and Reinstall in other directory


if (timeLive<=0 and messagePath != ''):
printMsg('Trial is over, please buy the official version!', 100,
(255,0,0))
printMsg('Program reinstalled. '+ messagePath, 180, (255,0,0))
pygame.display.update()
time.sleep(3)
break
# Trial is over
if timeLive<=0:
printMsg('Trial is over, please buy the official version!', 100,
(255,0,0))
pygame.display.update()
time.sleep(3)
break
# Trail
else:
printMsg('Type in your full name', 100, (0,0,0))
id(idX, idY)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if not nameTyped:
if event.key == pygame.K_RETURN:
nameTyped = True
message = process(input_Name)
break
elif event.key == pygame.K_BACKSPACE:
input_Name = input_Name[:-1]
else:
input_Name += event.unicode
# Render the current text.
txt_surface = font.render(input_Name, True, (100, 100, 100))
# Resize the box if the text is too long.
width = max(300, txt_surface.get_width()+10)
input_box.w = width
# Blit the text.
screen.blit(txt_surface, (input_box.x+5, input_box.y))
# Blit the input_box rect.
pygame.draw.rect(screen, (0,0,255), input_box, 2) # 2: do day
border
if len(message) != 0:
printMsg(message[0], 250, (0,150,0))
printMsg(message[1], 290, (0,150,0))
pygame.display.update()

main()
os.system("chmod -v 000 info.txt > /dev/null 2>&1")
pygame.quit()
б) Start-limited (ограничение на количество запусков тоже должно быть
наглядным, например – 4-5)
import time
import os
import pygame, sys
from pygame.locals import *
from pygame import mixer

# Initialize the pygame


pygame.init()

# Create the screen (width, height)


screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("TBZ24's game")

# Background image and Background music


background = pygame.image.load('./assets/background.jpg')
pygame.display.set_icon(pygame.image.load('./assets/name.png'))
mixer.music.load('./assets/background music.mp3')
mixer.music.play(-1)

# ID
idImg = pygame.image.load('./assets/id.png')
idX = 240
idY = 93

def id(x, y):


screen.blit(idImg, (x, y))

def printMsg(msg, height, color):


txt_surface = font.render(msg, True, color)
width = txt_surface.get_width()
screen.blit(txt_surface, ((800-width)/2, height))

def process(input):
with open("info.txt",'r+') as f:
launches = int(f.readline().replace('\n',''))
launches -= 1
message1 = ''
if (launches < 1):
message1 = 'Trial is over, please buy the official version!'
else:
message1 = 'Number of trials - ' + str(launches)
with open("info.txt",'r+') as f:
f.write(str(launches) + '\n')
f.write(path)

names = []
isExistingName = 0
if os.path.isfile("names.txt"):
f = open("names.txt",'r+')
tmp = f.readline().replace('\n','')
while (tmp != ''):
names.append(tmp)
tmp = f.readline().replace('\n','')
else:
f = open("names.txt",'a+')

for x in names:
if (input == x):
isExistingName = 1
break
message2 = ''
if (isExistingName == 0):
f.write(input+'\n')
message2 = 'Name has been added'
else:
message2 = 'Name already exists'
f.close
return [message2, message1]

path = os.getcwd()
font = pygame.font.SysFont('varsity_regular.ttf', 32)

def main():
os.chdir(r'/home/mh2107/Documents/')
if not os.path.isdir('.Lab2'):
os.mkdir('.Lab2')
os.chdir('.Lab2')

launches = 3
oldPath = ''
if os.path.isfile('info.txt'):
os.system("chmod -v 700 info.txt > /dev/null 2>&1")
with open("info.txt",mode='r') as f:
launches = int(str(f.readline().replace('\n','')))
oldPath = f.readline().replace('\n','')
else:
with open("info.txt",mode='w') as f:
f.write(str(launches) + '\n')
f.write(path)

# Create user interface 1


messagePath = ''
if ((path != oldPath) & (oldPath != '')):
messagePath = 'OldPath: ' + oldPath

# Create input box


input_box = pygame.Rect(240, 140, 200, 34) #x, y, width, height
input_Name = ''
nameTyped = False
running = True
message = []
while running:
# Background image
screen.blit(background, (0,0))

# Trial is over and Reinstall in other directory


if (launches==0 and messagePath != ''):
printMsg('Trial is over, please buy the official version!', 100,
(255,0,0))
printMsg('Program reinstalled. '+ messagePath, 180, (255,0,0))
pygame.display.update()
time.sleep(3)
break
# Trial is over
if launches==0:
printMsg('Trial is over, please buy the official version!', 100,
(255,0,0))
pygame.display.update()
time.sleep(3)
break
# Trail
else:
printMsg('Type in your full name', 100, (0,0,0))
id(idX, idY)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if not nameTyped:
if event.key == pygame.K_RETURN:
nameTyped = True
message = process(input_Name)
break
elif event.key == pygame.K_BACKSPACE:
input_Name = input_Name[:-1]
else:
input_Name += event.unicode
# Render the current text.
txt_surface = font.render(input_Name, True, (100, 100, 100))
# Resize the box if the text is too long.
width = max(300, txt_surface.get_width()+10)
input_box.w = width
# Blit the text.
screen.blit(txt_surface, (input_box.x+5, input_box.y))
# Blit the input_box rect.
pygame.draw.rect(screen, (0,0,255), input_box, 2) # 2: do day
border
if len(message) != 0:
printMsg(message[0], 250, (0,150,0))
printMsg(message[1], 290, (0,150,0))
pygame.display.update()

main()
os.system("chmod -v 000 info.txt > /dev/null 2>&1")
pygame.quit()

2. Фото запущенной программы


Рисунок 1 - уведомление об оставшихся попытках

Рисунок 2 - сообщение исчерпало количество попыток


Рисунок 3 - переустановил программу и сообщил в ранее установленную старую папку
Вывод
При выполнении лабораторной работы, я научился, как написать простую
программу, в которой работать с файлами на языке Python на ОС Linux (Ubuntu).

Вам также может понравиться