Advertisement
oldnewbie

Guess_the_Word

Feb 20th, 2016
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 16.18 KB | None | 0 0
  1. local term = require("term")
  2. local event = require("event")
  3. local computer = require("computer")
  4. local component = require("component")
  5. local unicode = require("unicode")
  6. local fs = require("filesystem")
  7. local gpu = component.gpu
  8. local serialization = require("serialization")
  9. local xSize, ySize = gpu.getResolution()
  10. local width = 63
  11. local height = 25
  12. local xPosCells
  13. local tempXPosCells
  14. local xPosTitle
  15. local tempXPosTitle
  16. local yPosTitle = 8
  17. local yPosCells = 10
  18. local cellsXPos = {}
  19. local title
  20. local words = {}
  21. local word1 = {}
  22. local word2 = {'_','_','_','_','_','_','_','_','_'}
  23. local score = 0
  24. local point = 0
  25. local heard = 5
  26. local sameLetter = false
  27. local noWords = false
  28. local nicknames
  29. local records
  30. local name
  31. local count
  32. local heardPlus
  33. local tempRandom
  34. local record = 0
  35. local play = true
  36. local colors = {
  37.     background = 0x7A8B8B,
  38.     button = 0x00688B,
  39.     textButton = 0xE0FFFF,
  40.     input = 0xBBFFFF,
  41.     cell = 0x2F4F4F,
  42.     text = 0x000000,
  43.     heard = 0xFF0000,
  44.     correctLetter = 0x7CFC00,
  45.     incorrectLetter = 0xB22222,
  46.     defBg = 0x000000,
  47.     defText = 0xFFFFFF
  48. }
  49. --Наша клавиатура где (x,y,символ, надпись на клавиатуре)
  50. local keyboard = {
  51.     {8, 16,"й"," Й "},
  52.     {12, 16, "ц", " Ц "},
  53.     {16, 16, "у", " У "},
  54.     {20, 16 , "к", " К "},
  55.     {24, 16, "е", " Е "},
  56.     {28, 16, "н", " Н "},
  57.     {32, 16, "г", " Г "},
  58.     {36, 16, "ш", " Ш "},
  59.     {40, 16, "щ", " Щ "},
  60.     {44, 16, "з", " З "},
  61.     {48, 16, "х", " Х "},
  62.     {52, 16, "ъ", " Ъ "},
  63.     {10, 18, "ф", " Ф "},
  64.     {14, 18, "ы", " Ы "},
  65.     {18, 18, "в", " В "},
  66.     {22, 18, "а", " А "},
  67.     {26, 18, "п", " П "},
  68.     {30, 18, "р", " Р "},
  69.     {34, 18, "о", " О "},
  70.     {38, 18, "л", " Л "},
  71.     {42, 18, "д", " Д "},
  72.     {46, 18, "ж", " Ж "},
  73.     {50, 18, "э", " Э "},
  74.     {14, 20, "я", " Я "},
  75.     {18, 20, "ч", " Ч "},
  76.     {22, 20, "с", " С "},
  77.     {26, 20, "м", " М "},
  78.     {30, 20, "и", " И "},
  79.     {34, 20, "т", " Т "},
  80.     {38, 20, "ь", " Ь "},
  81.     {42, 20, "б", " Б "},
  82.     {46, 20, "ю", " Ю "}
  83. }
  84.  
  85. local selectKey
  86.  
  87. gpu.setResolution(width, height)
  88.  
  89. local pathToWords = "words.txt"
  90. local function loadWords() --Загружаем слова
  91.     local bool = true
  92.     gpu.setBackground(colors.background)
  93.     if fs.exists(pathToWords) then
  94.         local array = {}
  95.         local file = io.open(pathToWords, "r")
  96.         local str = file:read("*a")
  97.         array = serialization.unserialize(str)
  98.         file:close()
  99.         words = array
  100.     else
  101.         if component.isAvailable("internet") then
  102.         os.execute("wget -f http://pastebin.com/raw/rc7qrrHA words.txt -q")
  103.         term.clear()
  104.         gpu.set(18, 12, "Загружен файл со словами!")
  105.         os.sleep(5)
  106.         term.clear()
  107.         loadWords()
  108.         else
  109.             term.clear()
  110.             gpu.set(4,12, "Вставьте Интернет карту или скачайте words.txt вручную.")
  111.             gpu.set(10,13,"По ссылке http://pastebin.com/rc7qrrHA")
  112.             gpu.setBackground(colors.button)
  113.             gpu.setForeground(colors.textButton)
  114.             gpu.set(4,24,"[<<Назад]")
  115.             gpu.setBackground(colors.background)
  116.             gpu.setForeground(colors.text)
  117.             while bool do
  118.                 local e = {event.pull("touch")}
  119.                 if e[4] == 24 then
  120.                     if e[3]>3 and e[3]<14 then
  121.                         play = false
  122.                         noWords = true
  123.                         bool = false   
  124.                     end
  125.                 end
  126.             end
  127.         end
  128.     end
  129. end
  130. --Берем рандомное слово
  131. local function getRandomWord()
  132.     local randomN = math.modf(math.random(1,#words))
  133.     if tempRandom ~= randomN then --Проверка чтоб небыло 2 подряд
  134.     title = words[randomN].title
  135.     word1 = words[randomN].word
  136.     else
  137.         getRandomWord()
  138.     end
  139.     tempRandom = randomN
  140. end
  141.  
  142. local pathToRecords = "recordsGtW.txt" --путь к файлу с рекордами
  143. local function saveRecord() --Сохраняем рекорды
  144.     local file = io.open(pathToRecords, "w")
  145.     local array = {["nicknames"] = nicknames, ["records"] = records}
  146.     file:write(serialization.serialize(array))
  147.     file:close()
  148. end
  149. local function saveScore() --сохраняем наши заработанные очки
  150.     for i = 1, #nicknames do
  151.         if name == nicknames[i] then
  152.             if score >= record then
  153.                 records[i] = score
  154.             end
  155.         end
  156.     end
  157.     saveRecord()
  158. end
  159. local function loadRecord()  --Загружаем рекорды
  160.     if fs.exists(pathToRecords) then
  161.         local array = {}
  162.         local file = io.open(pathToRecords, "r")
  163.         local str = file:read("*a")
  164.         array = serialization.unserialize(str)
  165.         file:close()
  166.         nicknames = array.nicknames
  167.         records = array.records
  168.     else --или создаем новые дефолтные пустые таблицы
  169.         fs.makeDirectory(fs.path(pathToRecords))
  170.             nicknames = {}
  171.             records = {}
  172.             saveRecord()
  173.     end
  174. end
  175. local function checkName(name)  --Проверка на наличие имени в базе
  176.     for i =1, #nicknames do
  177.         if name == nicknames[i] then
  178.             record = records[i]
  179.             return false
  180.         end
  181.     end
  182.     return true
  183. end
  184. local function addPlayer()  --Создаем учетку пользователю если его нет в базе
  185.     if checkName(name) then
  186.         table.insert(nicknames, name)
  187.         table.insert(records, record)
  188.         saveRecord()
  189.     end
  190. end
  191. local function getXPosTitle() --Получаем х позицию вопроса
  192.     tempXPosTitle = unicode.len(title)
  193.     tempXPosTitle = width - tempXPosTitle
  194.     xPosTitle = math.modf(tempXPosTitle/2)
  195.     tempXPosTitle = xPosTitle
  196. end
  197.  
  198. local function getXPosCells() --Получаем х позицию ячеек
  199.     tempXPosCells = #word1
  200.     tempXPosCells = tempXPosCells*5 - 1
  201.     tempXPosCells = width - tempXPosCells
  202.     xPosCells = tempXPosCells/2
  203.     tempXPosCells = xPosCells
  204. end
  205.  
  206. getXPosCells()
  207.  
  208. local function paintMenu() --Отрисовываем меню
  209.     gpu.setResolution(width, height)
  210.     gpu.setBackground(colors.background)
  211.     term.clear()
  212.     gpu.setForeground(colors.text)
  213.    
  214.     gpu.set(27, 3, "Угадай-Ка")
  215.     gpu.setForeground(colors.textButton)
  216.     gpu.setBackground(colors.button)
  217.     gpu.set(25, 15, "[Начать игру]")
  218.     gpu.set(25, 17, "[Топ Лидеров]")
  219.     gpu.set(27, 19,"[Правила]")
  220.     gpu.set(28, 21, "[Выход]")
  221.     gpu.setForeground(colors.text)
  222. end
  223.  
  224. local function paintScene() --Отрисовываем игровой экран
  225.     getXPosCells()
  226.     getXPosTitle()
  227.     gpu.setBackground(colors.background)
  228.     term.clear()
  229.     gpu.set(xPosTitle, yPosTitle, title)
  230.     for i=1, #word1 do
  231.         table.insert(cellsXPos, tempXPosCells)
  232.         gpu.setBackground(colors.cell)
  233.         gpu.setForeground(colors.text)
  234.         gpu.set(tempXPosCells, yPosCells, "   ")
  235.         tempXPosCells = tempXPosCells + 5
  236.         gpu.setBackground(colors.background)
  237.     end
  238.  
  239.     for i=1, #keyboard do
  240.         gpu.setBackground(colors.button)
  241.         gpu.set(keyboard[i][1], keyboard[i][2], keyboard[i][4])
  242.         gpu.setBackground(colors.background)
  243.     end
  244.     local tempN = unicode.len(name)
  245.     tempN = width - (tempN + 17)
  246.     gpu.set(tempN,2,name.." :Текущий игрок")
  247.     gpu.set(2,2,"Ваш рекорд: "..record)
  248.     gpu.set(49,3, " :Ваши жизни")
  249.     gpu.setForeground(colors.heard)
  250.     gpu.set(44,3, "❤x"..heard)
  251.     gpu.setForeground(colors.text)
  252.     gpu.set(2,3,"Текущий счет: "..score)
  253.  
  254. end
  255.  
  256. local function paintRules() --Отрисовываем правила
  257.     local bool = true
  258.     gpu.setBackground(colors.background)
  259.     term.clear()
  260.     gpu.setForeground(colors.text)
  261.     gpu.set(25,7,"Правила игры!")
  262.     gpu.set(4,11,"        Доброго времени суток, уважаемый игрок!")
  263.     gpu.set(4,12,"   Правила <<Угадай-Ки>> очень просты, перед вами будет")
  264.     gpu.set(4,13,"n-количество   ячеек    за   которыми   буквы.   Сверху")
  265.     gpu.set(4,14,"подсказка. Чтоб  выбрать букву  нажмите  ее на экранной")
  266.     gpu.set(4,15,"клавиатуре.  Если  угадаете она  появится  в поле и  на")
  267.     gpu.set(4,16,"ЭК станет зеленной, не угадаете - красной. Есть 4  режима.")
  268.     gpu.set(4,17,"Если не угадали букву - минус жизнь. Каждое угаданное слово")
  269.     gpu.set(4,18,"дает свое количество очков в зависимости от режима игры.")
  270.     gpu.set(4,19,"Каждая  угаданая  подряд буква умножает очки на  кол-во")
  271.     gpu.set(4,20,"угаданых букв подряд. Удачи в игре!!")
  272.     gpu.setBackground(colors.button)
  273.     gpu.setForeground(colors.textButton)
  274.     gpu.set(4,24,"[<<Назад]")
  275.     gpu.setBackground(colors.background)
  276.     gpu.setForeground(colors.text)
  277.     while bool do
  278.         local e = {event.pull("touch")}
  279.         if e[4] == 24 then
  280.             if e[3]>3 and e[3]<14 then
  281.                 bool = false   
  282.                 guessTW()
  283.             end
  284.         end
  285.     end
  286. end
  287.  
  288. local function clearLine(a) --Просто отчиистка линии для сокращения кода
  289.     term.setCursor(1,a)
  290.     term.clearLine()
  291. end
  292.  
  293. local function guessTheWord() --Наш алгоритм для сранения букв и работа с нимм
  294.     local goodLetter = false
  295.     local haveSpace = false
  296.     local key = selectKey
  297.     local letter = key[3]
  298.     local tempScore
  299.     local bool = true
  300.  
  301.     for i = 1, #word1 do
  302.         if word1[i] == letter then
  303.             if word1[i] ~= word2[i] then
  304.                 point = point + 1
  305.                 tempScore = point*count
  306.                 score = score + tempScore
  307.                 gpu.set(16,3, tostring(score))
  308.                 if record>=score then
  309.                     gpu.set(14,2, tostring(record))
  310.                 else
  311.                     record = score
  312.                     gpu.set(14,2, tostring(record))
  313.                 end
  314.                 goodLetter = true
  315.                 gpu.set(25,12,"Верная буква!")
  316.             elseif word1[i] == word2[i] then
  317.                 sameLetter = true
  318.             end
  319.             word2[i] = letter
  320.             gpu.setBackground(colors.cell)
  321.             gpu.setForeground(colors.textButton)
  322.             gpu.set(cellsXPos[i],10, key[4])
  323.             gpu.setForeground(colors.text)
  324.             gpu.setBackground(colors.correctLetter)
  325.             gpu.set(key[1],key[2],key[4])
  326.             gpu.setBackground(colors.background)
  327.             gpu.setForeground(colors.text)
  328.             clearLine(12)
  329.             gpu.set(25,12,"Верная буква!")
  330.         end
  331.         if word2[i] == "_" then
  332.             haveSpace = true
  333.         end
  334.     end
  335.  
  336.     if goodLetter then
  337.         if not haveSpace then
  338.             heard = heard + heardPlus
  339.             gpu.setForeground(colors.heard)
  340.             gpu.set(47,3,"   ")
  341.             gpu.set(47,3, tostring(heard))
  342.             gpu.setForeground(colors.text)
  343.             clearLine(12)
  344.             if heardPlus == 0 then
  345.                 gpu.set(18, 12,"Слово отгадано, продолжим?")
  346.             elseif heardPlus == 2 then
  347.                 gpu.set(7, 12,"Слово отгадано, вы получили две жизни, продолжим?")
  348.             else
  349.                 gpu.set(6, 12,"Слово отгадано, вы получили одну жизнь, продолжим?")
  350.             end
  351.             gpu.setForeground(colors.textButton)
  352.             gpu.setBackground(colors.button)
  353.             gpu.set(35,14,"[Далее >>]")
  354.             gpu.set(18,14,"[Выход]")
  355.             gpu.setForeground(colors.text)
  356.             while bool do
  357.                 local e = {event.pull("touch")}
  358.                 if e[4] == 14 then
  359.                     if e[3]>17 and e[3]<26 then
  360.                         play = false
  361.                         bool = false
  362.                         heardScore = heard * count * point
  363.                         score = score + heardScore
  364.                         saveScore()
  365.                         score = 0
  366.                         guessTW()
  367.                        
  368.                     elseif e[3]>34 and e[3]<44 then
  369.                         bool = false
  370.                         saveScore()
  371.                         game()
  372.                        
  373.                     end
  374.                 end
  375.             end
  376.         end
  377.     elseif sameLetter then
  378.         clearLine(12)
  379.         gpu.set(21,12,"Эта буква уже введена")
  380.         sameLetter = false
  381.     else
  382.         point = 0
  383.         clearLine(12)
  384.         gpu.set(24,12,"Неверная буква!")
  385.         gpu.setBackground(colors.incorrectLetter)
  386.         gpu.set(key[1],key[2],key[4])
  387.         gpu.setBackground(colors.background)
  388.         heard = heard - 1
  389.         if heard ~= 0 then
  390.             gpu.setForeground(colors.heard)
  391.             gpu.set(47,3,"   ")
  392.             gpu.set(47,3, tostring(heard))
  393.             gpu.setForeground(colors.text)
  394.         else
  395.             term.clear()
  396.             gpu.set(15,11,"Игра окончена!!! Ваш счет: "..tostring(score))
  397.             score = 0
  398.             os.sleep(8)
  399.             play = false
  400.             guessTW()
  401.         end
  402.     end
  403. end
  404.  
  405.  
  406. local function sortTop() --Сортируем Топ игроков
  407.     for i=1, #records do
  408.       for j=1, #records-1 do
  409.         if records[j] < records[j+1] then
  410.           local r = records[j+1]
  411.           local n = nicknames[j+1]
  412.           records[j+1] = records[j]
  413.           nicknames[j+1] = nicknames[j]
  414.           records[j] = r
  415.           nicknames[j] = n
  416.         end
  417.       end
  418.     end
  419.     saveRecord()
  420. end
  421. function printRecords()  --Выводим рекорды на экран
  422.     local bool = true
  423.     sortTop()
  424.     gpu.setBackground(colors.background)
  425.     term.clear()
  426.     local xPosName = 15
  427.     local xPosRecord = 40
  428.     local yPos = 2
  429.     loadRecord()
  430.         gpu.setForeground(colors.text)
  431.         gpu.set(25,2,"Toп Лидеров")
  432.         gpu.setForeground(colors.textButton)
  433.     if #nicknames <= 15 then
  434.     for i = 1, #nicknames do
  435.         yPos= yPos+1
  436.         gpu.set(xPosName, yPos, nicknames[i] )
  437.         gpu.set(xPosRecord, yPos, tostring(records[i]))
  438.     end
  439.     else
  440.         for i = 1, 15 do
  441.         yPos= yPos+1
  442.         gpu.set(xPosName, yPos, nicknames[i] )
  443.         gpu.set(xPosRecord, yPos, tostring(records[i]))
  444.         end
  445.     end
  446.     gpu.setBackground(colors.button)
  447.     gpu.set(4,24,"[<<Назад]")
  448.     gpu.setBackground(colors.background)
  449.     while bool do
  450.         local e = {event.pull("touch")}
  451.         if e[4] == 24 then
  452.             if e[3]>3 and e[3]<14 then
  453.                 bool = false   
  454.                 guessTW()
  455.             end
  456.         end
  457.     end
  458. end
  459.  
  460. function game() --Наша игра
  461.     cellsXPos = {}
  462.     word2 = {'_','_','_','_','_','_','_','_','_'}
  463.     term.clear()
  464.     getRandomWord()
  465.     paintScene()
  466.     while play do
  467.         local e = {event.pull("touch")}
  468.         for i=1, #keyboard do
  469.             if e[4] == keyboard[i][2] then
  470.                 if e[3] > keyboard[i][1]-1 and e[3] < keyboard[i][1]+3 then
  471.                     selectKey = keyboard[i]
  472.                     guessTheWord()
  473.                 end
  474.             end
  475.         end
  476.     end
  477. end
  478.  
  479. local function selectComplexity() --Выбор уровня сложности
  480.     local bool = true
  481.     gpu.setBackground(colors.background)
  482.     term.clear()
  483.     gpu.setBackground(colors.button)
  484.     gpu.setForeground(colors.textButton)
  485.     gpu.set(27,10,"[Хардкор]")
  486.     gpu.set(27,13,"[Сложная]")
  487.     gpu.set(27,16,"[Средняя]")
  488.     gpu.set(28,19,"[Легко]")
  489.     gpu.set(4,24,"[<<Назад]")
  490.     gpu.setBackground(colors.background)
  491.     gpu.setForeground(colors.text)
  492.     gpu.set(22,8,"Выберите сложность:")
  493.     gpu.set(9,11,"Всего 10 жизней на игру и за букву 100 очков!")
  494.     gpu.set(5,14,"2 жизни в начале и за букву 50 очков, за слово жизнь!")
  495.     gpu.set(6,17,"5 жизней в начале и за букву 10 очков, за слово жизнь!")
  496.     gpu.set(6,20,"10 жизней в начале и за букву 2 очка, за слово 2 жизни!")
  497.  
  498.     while bool do
  499.         local e = {event.pull("touch")}
  500.         if e[4] == 10 then
  501.             if e[3]>26 and e[3]<36 then
  502.                 bool = false
  503.                 heard = 10
  504.                 heardPlus = 0
  505.                 count = 100
  506.                 game()
  507.             end
  508.         elseif e[4] == 13 then
  509.             if e[3]>26 and e[3]<36 then
  510.                 bool = false
  511.                 heard = 2
  512.                 heardPlus = 1
  513.                 count = 50
  514.                 game()
  515.             end
  516.         elseif e[4] == 16 then
  517.             if e[3]>26 and e[3]<36 then
  518.                 bool = false
  519.                 heard = 5
  520.                 heardPlus = 1
  521.                 count = 10
  522.                 game()
  523.             end
  524.         elseif e[4] == 19 then
  525.             if e[3]>27 and e[3]<35 then
  526.                 bool = false
  527.                 heard = 10
  528.                 heardPlus = 2
  529.                 count = 2
  530.                 game()
  531.             end
  532.         elseif e[4] == 24 then
  533.             if e[3]>3 and e[3]<14 then
  534.                 bool = false
  535.  
  536.                 guessTW()
  537.             end
  538.         end
  539.     end
  540. end
  541.  
  542. function guessTW() -- Запуск нашей игры
  543.     record = 0
  544.     loadRecord()
  545.     loadWords()
  546.     paintMenu()
  547.     while true do
  548.         local e = {event.pull("touch")}
  549.         if e[4] == 15 then
  550.             if e[3]>24 and e[3]<33 then
  551.                 if not noWords then
  552.                     name = e[6]
  553.                     addPlayer(name)
  554.                     for i = 1, #nicknames do
  555.                         if name == nicknames[i] then
  556.                             record = records[i]
  557.                         end
  558.                     end
  559.                     play = true
  560.                     point = 0
  561.                     selectComplexity()
  562.                 end
  563.             end
  564.         elseif e[4] == 17 then
  565.             if e[3]>24 and e[3]<37 then
  566.                 sortTop()
  567.                 printRecords()
  568.             end
  569.         elseif e[4] == 19 then
  570.             if e[3]>26 and e[3]<36 then
  571.                 paintRules()
  572.             end
  573.         elseif e[4] == 21 then
  574.             if e[3]>27 and e[3]<35 then
  575.                 gpu.setForeground(colors.defText)
  576.                 gpu.setBackground(colors.defBg)
  577.                 gpu.setResolution(xSize,ySize)
  578.                 term.clear()
  579.                 quit = true
  580.                 break
  581.             end
  582.         end
  583.         if quit then break end
  584.     end
  585. end
  586.  
  587. guessTW()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement