diff --git a/Floyds_pattern.cpp b/Floyds_pattern.cpp new file mode 100644 index 000000000..dcfb256e5 --- /dev/null +++ b/Floyds_pattern.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + + +int main(){ + + int n,num=1; + cin>>n; + + + + + for (int i=1;i<=n;i++){ + for(int j=1;j<=i;j++){ + cout< + +using namespace std; + +class Mammals { + public: + void fn1() { + cout << "I am mammal" << endl; + } +}; + +class MarineAnimals { + public: + void fn2() { + cout << "I am a marine animal" << endl; + } +}; + +class BlueWhale : public Mammals, public MarineAnimals { + public: + void fn3() { + cout << "I belong to both the categories: Mammals as well as Marine Animals" << endl; + } +}; + +int main() +{ + Mammals mm; + MarineAnimals ma; + BlueWhale bw; + mm.fn1(); /* func of Mammals by obj of Mammals */ + ma.fn2(); /* func of MarineAnimals by obj of MarineAnimals */ + bw.fn3(); /* func of BlueWhale by obj of BlueWhale */ + bw.fn1(); /* func of Mammals by obj of BlueWhale */ + bw.fn2(); /* func of MarineAnimals by obj of BlueWhale */ + return 0; +} diff --git a/README.md b/README.md index 4d3592283..549764bf3 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Geek Week: Local will run from 14/03/21 to 21/03/21. During this time, you can expect challenges for all skill levels. These challenges can be completed on your own time, and new ones will be released each day on our website! Once the daily challenges are announced, you’ll have 24 hours to complete and submit them in order to earn those points on the leader-board. -If the daily challenges aren’t quite your speed, there will also be plenty of week-long challenges you can complete at any time. These will range from quick technical challenges to tasks you can complete with your guild-mates (guild=team), both beginner-friendly and technically advanced so there is something for everyone. +If the daily challenges aren’t quite your speed, there will also be plenty of week-long challenges you can complete at any time. These will range from quick technical challenges to tasks you can complete with your guild-mates (guild=team), both beginner-friendly and technically advanced , so there is something for everyone. ![](assets/banner2(1).png) diff --git a/Sakalya100-Day4/Day4-Problem1.py b/Sakalya100-Day4/Day4-Problem1.py new file mode 100644 index 000000000..07155acf7 --- /dev/null +++ b/Sakalya100-Day4/Day4-Problem1.py @@ -0,0 +1,11 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + m = '' # Memory to remember a palindrome + for i in range(len(s)): # i = start, O = n + for j in range(len(s), i, -1): # j = end, O = n^2 + if len(m) >= j-i: # To reduce time + break + elif s[i:j] == s[i:j][::-1]: + m = s[i:j] + break + return m diff --git a/Sakalya100-Day4/Day4-Problem2.py b/Sakalya100-Day4/Day4-Problem2.py new file mode 100644 index 000000000..0e0ba83d4 --- /dev/null +++ b/Sakalya100-Day4/Day4-Problem2.py @@ -0,0 +1,19 @@ +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + result = ListNode(0) + result_tail = result + carry = 0 + + while l1 or l2 or carry: + val1 = (l1.val if l1 else 0) + val2 = (l2.val if l2 else 0) + carry, out = divmod(val1+val2 + carry, 10) + + result_tail.next = ListNode(out) + result_tail = result_tail.next + + l1 = (l1.next if l1 else None) + l2 = (l2.next if l2 else None) + + return result.next + diff --git a/Sakalya100-Day4/Day4-Problem3.py b/Sakalya100-Day4/Day4-Problem3.py new file mode 100644 index 000000000..16facc822 --- /dev/null +++ b/Sakalya100-Day4/Day4-Problem3.py @@ -0,0 +1,15 @@ +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + n = len(s) + cycle = 2*numRows - 2 + strlist = [] + for i in range(numRows): + for j in range(i, n, cycle): + strlist.append(s[j]) + if i != numRows-1 and i != 0 and j+cycle-2*i < n: + strlist.append(s[j+cycle-2*i]) + newstr = ''.join(strlist) + return newstr + diff --git a/Sakalya100-Day4/Day4-Problem4.py b/Sakalya100-Day4/Day4-Problem4.py new file mode 100644 index 000000000..b29eaafb6 --- /dev/null +++ b/Sakalya100-Day4/Day4-Problem4.py @@ -0,0 +1,30 @@ +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + # If the input is empty, immediately return an empty answer array + if len(digits) == 0: + return [] + + # Map all the digits to their corresponding letters + letters = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", + "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} + + def backtrack(index, path): + # If the path is the same length as digits, we have a complete combination + if len(path) == len(digits): + combinations.append("".join(path)) + return # Backtrack + + # Get the letters that the current digit maps to, and loop through them + possible_letters = letters[digits[index]] + for letter in possible_letters: + # Add the letter to our current path + path.append(letter) + # Move on to the next digit + backtrack(index + 1, path) + # Backtrack by removing the letter before moving onto the next + path.pop() + + # Initiate backtracking with an empty path and starting index of 0 + combinations = [] + backtrack(0, []) + return combinations diff --git a/Sakalya100-Day4/Day4-Problem5.py b/Sakalya100-Day4/Day4-Problem5.py new file mode 100644 index 000000000..c7543dece --- /dev/null +++ b/Sakalya100-Day4/Day4-Problem5.py @@ -0,0 +1,7 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + ans = collections.defaultdict(list) + for s in strs: + ans[tuple(sorted(s))].append(s) + return ans.values() + diff --git a/Sakalya100-Day4/Redesigned-Website/GWL.jpg b/Sakalya100-Day4/Redesigned-Website/GWL.jpg new file mode 100644 index 000000000..5365f1547 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/GWL.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/avatar1.png b/Sakalya100-Day4/Redesigned-Website/avatar1.png new file mode 100644 index 000000000..6684932b4 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/avatar1.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/avatar2.png b/Sakalya100-Day4/Redesigned-Website/avatar2.png new file mode 100644 index 000000000..87b0eb13a Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/avatar2.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/avatar3.png b/Sakalya100-Day4/Redesigned-Website/avatar3.png new file mode 100644 index 000000000..ffba410c0 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/avatar3.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/avatar4.png b/Sakalya100-Day4/Redesigned-Website/avatar4.png new file mode 100644 index 000000000..660c35604 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/avatar4.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/avatar5.png b/Sakalya100-Day4/Redesigned-Website/avatar5.png new file mode 100644 index 000000000..4f41152c2 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/avatar5.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/bill.jpg b/Sakalya100-Day4/Redesigned-Website/bill.jpg new file mode 100644 index 000000000..b92aca341 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/bill.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/codersbite.png b/Sakalya100-Day4/Redesigned-Website/codersbite.png new file mode 100644 index 000000000..b17832ccc Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/codersbite.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/covid.png b/Sakalya100-Day4/Redesigned-Website/covid.png new file mode 100644 index 000000000..628a0c9e1 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/covid.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/dp.jpg b/Sakalya100-Day4/Redesigned-Website/dp.jpg new file mode 100644 index 000000000..2b9ca95c1 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/dp.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/elon.jpg b/Sakalya100-Day4/Redesigned-Website/elon.jpg new file mode 100644 index 000000000..0333fa4c9 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/elon.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/emoji_angry.png b/Sakalya100-Day4/Redesigned-Website/emoji_angry.png new file mode 100644 index 000000000..a01526d76 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/emoji_angry.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/emoji_like.png b/Sakalya100-Day4/Redesigned-Website/emoji_like.png new file mode 100644 index 000000000..cfed8a1df Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/emoji_like.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/emoji_surprised.png b/Sakalya100-Day4/Redesigned-Website/emoji_surprised.png new file mode 100644 index 000000000..248eacb93 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/emoji_surprised.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/events.png b/Sakalya100-Day4/Redesigned-Website/events.png new file mode 100644 index 000000000..07527c976 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/events.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/facebook.png b/Sakalya100-Day4/Redesigned-Website/facebook.png new file mode 100644 index 000000000..6a1912647 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/facebook.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/friends.png b/Sakalya100-Day4/Redesigned-Website/friends.png new file mode 100644 index 000000000..1aa2cb3de Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/friends.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/gfg.jpg b/Sakalya100-Day4/Redesigned-Website/gfg.jpg new file mode 100644 index 000000000..ec3c23f8d Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/gfg.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/gift-box.png b/Sakalya100-Day4/Redesigned-Website/gift-box.png new file mode 100644 index 000000000..d68060592 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/gift-box.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/groups.png b/Sakalya100-Day4/Redesigned-Website/groups.png new file mode 100644 index 000000000..011fbbf31 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/groups.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/hilary.jpg b/Sakalya100-Day4/Redesigned-Website/hilary.jpg new file mode 100644 index 000000000..d6f171a02 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/hilary.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/index.html b/Sakalya100-Day4/Redesigned-Website/index.html new file mode 100644 index 000000000..4758210fa --- /dev/null +++ b/Sakalya100-Day4/Redesigned-Website/index.html @@ -0,0 +1,306 @@ + + + + + + FaceBook Redsigned + + + + + + + +
+ + +
+
+ + + + + + +
+
+ + +
+
+ user +
+

Geeks for Geek VIT Bhopal Student Chapter

+ 9h . +
+
+
+

+ Day 4 of Geek Week Local Live. Indulge in the challenge and imrpove your web developmet skills. + We are waiting for some great responses. +

+ sunflower +
+ YOUTUBE /GEEKS FOR GEEKS VIT BHOPAL +

+ We conduct 3 sessions daily filled with fun and excitement. + Session 1 is explanantion event followed by session 2 of mini event. + Come join us + Like.Share & Subscribe +

+
+
+ + + +

+ +
+
+
+ + +
+ + diff --git a/Sakalya100-Day4/Redesigned-Website/jeff.jpg b/Sakalya100-Day4/Redesigned-Website/jeff.jpg new file mode 100644 index 000000000..3817765c2 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/jeff.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/marketplace.png b/Sakalya100-Day4/Redesigned-Website/marketplace.png new file mode 100644 index 000000000..e82cc0f0c Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/marketplace.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/memories.png b/Sakalya100-Day4/Redesigned-Website/memories.png new file mode 100644 index 000000000..d81741f43 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/memories.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/profile.png b/Sakalya100-Day4/Redesigned-Website/profile.png new file mode 100644 index 000000000..b2547e34d Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/profile.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/readme.md b/Sakalya100-Day4/Redesigned-Website/readme.md new file mode 100644 index 000000000..7b860117d --- /dev/null +++ b/Sakalya100-Day4/Redesigned-Website/readme.md @@ -0,0 +1,5 @@ +

Facebook Redesigned by Sakalya mitra

+

Do visit and you will enjoy this

+
+ + diff --git a/Sakalya100-Day4/Redesigned-Website/saved.png b/Sakalya100-Day4/Redesigned-Website/saved.png new file mode 100644 index 000000000..3c1d44874 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/saved.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/screenshot.jpg b/Sakalya100-Day4/Redesigned-Website/screenshot.jpg new file mode 100644 index 000000000..5dac567b9 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/screenshot.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/session.jpg b/Sakalya100-Day4/Redesigned-Website/session.jpg new file mode 100644 index 000000000..c8e9b5a9b Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/session.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/shortcuts.jpg b/Sakalya100-Day4/Redesigned-Website/shortcuts.jpg new file mode 100644 index 000000000..f803679d7 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/shortcuts.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/styles.css b/Sakalya100-Day4/Redesigned-Website/styles.css new file mode 100644 index 000000000..a00d8ab8b --- /dev/null +++ b/Sakalya100-Day4/Redesigned-Website/styles.css @@ -0,0 +1,581 @@ +* { + margin: 0; +} + +body { + font-family: "Segoe UI"; + box-sizing: border-box; + background: #18191a; + overflow-x: hidden; +} + +.navbar { + background: #242526; + width: 100vw; + padding: 0 20px 0 20px; + height: 60px; + display: flex; + justify-content: space-between; + align-items: center; + box-shadow: 0 2px 2px -2px rgba(255, 255, 255, 0.4); +} + +.navbar_left { + width: 25%; + display: flex; + align-items: center; +} + +.navbar_logo { + width: 45px; + height: 45px; + margin-right: 5px; +} + +.input-icons i { + position: absolute; +} + +.input-icons { + width: 100%; +} + +.icon { + padding: 13px 10px; + color: #a8abaf; + min-width: 20px; + text-align: center; + margin-right: 20px; +} + +.input-field { + width: 50%; + padding: 12px 0 12px 35px; + background: #3a3b3c; + border: none; + border-radius: 25px; + font-size: 15px; + color: #a8abaf; +} + +.input-field:focus { + outline: none; +} + +::placeholder { + color: #a8abaf; +} + +.navbar_center { + width: 50%; + text-align: center; + display: flex; + justify-content: center; + align-items: center; +} + +.navbar_center a { + width: 150px; + height: 60px; + display: flex; + justify-content: center; + align-items: center; + transition: 0.2s; +} + +.navbar_center a:hover { + background: #3a3b3c; + border-radius: 10px; + height: 55px; + border: none; +} + +.active_icon { + border-bottom: 3px solid #2d88ff; +} +.active_icon i { + color: #2d88ff !important; +} + +.navbar a, +.navbar a i { + text-decoration: none; + color: #b8bbbf; + font-size: 23px; +} + +.navbar_right { + width: 25%; + text-align: right; + display: flex; + justify-content: flex-end; + align-items: center; + margin-right: 45px; +} + +.navbar_right_profile { + display: flex; + align-items: center; + height: 40px; + margin-right: 20px; + transition: 0.2s; +} + +.navbar_right_profile:hover { + background: #3a3b3c; + border-radius: 25px; + padding: 0 5px; +} + +.navbar_right_profile img { + width: 30px; + height: 30px; + margin-right: 5px; +} + +.navbar_right_profile span { + color: #e7e9ed; + font-size: 15px; + font-weight: 500; +} + +.navbar_right_links i { + margin-right: 5px; + background: #404041; + padding: 12px; + border-radius: 100%; + color: #e7e9ed; + cursor: pointer; + transition: 0.3s; + font-size: 16px; +} + +.navbar_right_links i:hover { + background: #4e4f50; +} + +/* navbar ends here */ + +.content { + display: flex; + justify-content: space-between; + align-items: center; +} + +.content_left { + width: 25%; + height: 100vh; + padding-left: 10px; +} + +.content_center { + width: 50%; + text-align: center; + height: 100vh; +} + +.content_right { + width: 25%; + height: 100vh; + display: flex; + justify-content: flex-end; +} + +.content_left ul { + margin: 0; + list-style: none; + padding: 25px 0; +} + +.content_left ul li { + padding: 0 15px; + margin-bottom: 15px; +} + +.content_left ul li a { + text-decoration: none; + display: flex; + align-items: center; + color: #e7e9ed; + font-weight: 500; + font-size: 15px; +} + +.content_left ul li i { + background: #404041; + padding: 10px; + border-radius: 100%; + color: #e7e9ed; + cursor: pointer; + transition: 0.3s; + font-size: 16px; + margin-right: 10px; +} + +.see_more { + color: #e7e9ed; + cursor: pointer; + font-size: 15px; + font-weight: 500; +} + +.content_left ul li a img { + width: 37px; + margin-right: 10px; +} + +.border { + margin-left: 20px; + width: 320px; + border-style: solid; + border-color: rgba(255, 255, 255, 0.08); + border-width: 1px; +} + +.shortcut_title { + margin: 15px 20px; + color: #e7e9ed; + font-size: 17px; + font-weight: 500; +} + +.shortcuts_wrapper { + padding: 0 15px; +} + +.shortcuts_wrapper a { + display: flex; + align-items: center; + text-decoration: none; + color: #e7e9ed; + font-weight: 500; + font-size: 15px; +} + +.shortcuts_wrapper a img { + width: 37px; + margin-right: 10px; + border-radius: 50%; +} + +/* content center starts here */ + +.stories { + padding: 25px 0; + display: flex; + justify-content: center; + align-items: center; +} + +.stories img { + border-radius: 10px; + margin-right: 10px; +} + +.media_container { + padding: 5px 115px; +} + +.share { + background-color: #242526; + border-radius: 10px; + padding: 15px; +} + +.share_upSide { + display: flex; + align-items: center; + margin-bottom: 15px; +} + +.share_upSide img { + margin-right: 7px; + width: 38px; +} + +.share_upSide input { + flex: 1; + padding: 12px 0 12px 12px; + background: #3a3b3c; + border: none; + border-radius: 25px; + font-size: 16px; + color: #a8abaf; +} + +.share_upSide input:focus { + outline: none; +} + +.media_container hr { + border-style: solid; + border-color: rgba(255, 255, 255, 0.08); + border-width: 1px; +} + +.share_downSide { + display: flex; + align-items: center; + justify-content: center; + padding-top: 15px; + height: 40px; +} + +.share_downSide_link { + width: 33.3%; + display: flex; + align-items: center; + justify-content: center; +} + +.share_downSide_link:hover { + background: #3a3b3c; + border-radius: 10px; + height: 40px; + display: flex; + justify-content: center; + align-items: center; +} + +.share_downSide_link i { + font-size: 25px; + margin-right: 5px; +} + +.share_downSide_link span { + color: #b7babe; + font-size: 15px; + font-weight: 500; +} + +.live-video-icon { + color: #f23e5c; +} + +.photo-video-icon { + color: #58c472; +} + +.feeling-icon { + color: #f8c03e; +} + +.news_feed { + background-color: #242526; + border-radius: 10px; + margin: 15px 0; +} + +.news_feed_title { + padding: 15px; + display: flex; + justify-content: start; + align-items: center; +} + +.news_feed_title img { + width: 40px; + margin-right: 7px; +} + +.news_feed_title_content { + text-align: left; +} + +.news_feed_title_content p { + color: #e4e6eb; + font-weight: 500; +} + +.news_feed_title_content span { + color: #b7babe; + font-size: 12px; +} + +.news_feed_description { + min-height: 400px; +} + +.news_feed_subtitle { + padding: 0 15px; + color: #e4e6eb; + font-size: 15px; + text-align: left; + margin-bottom: 15px; +} + +.news_feed_description img { + object-fit: cover; + width: 100%; + height: 400px; +} + +.news_feed_description_title { + margin-top: -5px; + padding: 10px 15px; + background-color: #3a3b3c; + text-align: left; +} + +.news_feed_description_title span { + color: #b7babe; + font-size: 13px; +} + +.news_feed_description_title p { + font-weight: 500; + color: #e4e6eb; + font-size: 15px; +} + +.likes_area { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 15px; +} + +.emojis { + display: flex; + align-items: center; +} + +.emojis img { + width: 25px; + margin-right: -3px; +} + +.emojis span { + color: #b7babe; + margin-left: 10px; +} + +.comment_counts { + color: #b7babe; +} + +.divider { + padding: 0 15px 0 15px; +} + +.likes_buttons { + display: flex; + align-items: center; + justify-content: center; + padding: 5px 15px; + height: 35px; +} + +.likes_buttons_links { + width: 33.3%; + display: flex; + align-items: center; + justify-content: center; + color: #b4b7bb; + font-weight: 500; +} + +.likes_buttons_links:hover { + background: #3a3b3c; + border-radius: 5px; + height: 35px; + display: flex; + justify-content: center; + align-items: center; +} + +.likes_buttons_links i { + font-size: 18px; + margin-right: 10px; +} + +/* content right starts here */ + +.content_right_inner { + width: 70%; + padding-right: 10px; +} + +.your_pages { + display: flex; + justify-content: space-between; + align-items: center; + margin: 15px 0; + color: #a1a4a9; +} + +.your_pages h3 { + font-size: 18px; + font-weight: 500; +} + +.content_right ul { + margin: 0; + list-style: none; + padding-left: 0; +} + +.content_right ul li { + margin-bottom: 15px; +} + +.content_right ul li a { + text-decoration: none; + display: flex; + align-items: center; + color: #e5e7eb; + font-weight: 500; +} + +.content_right ul li a img { + width: 37px; + margin-right: 10px; + border-radius: 100%; +} + +.content_right_small_text { + font-size: 13px; + color: #b0b2b6; + padding-top: 0; +} + +.content_right_small_text a { + padding-left: 20px; +} + +.content_right_small_text a i { + margin-right: 15px; +} + +.content_right_divider { + border-style: solid; + border-color: rgba(255, 255, 255, 0.08); + border-width: 1px; +} + +.birthdays { + margin: 15px 0; + color: #a1a4a9; +} + +.birthdays h3 { + font-size: 18px; + font-weight: 500; +} + +.contacts { + display: flex; + justify-content: space-between; + align-items: center; + margin: 15px 0; + color: #a1a4a9; +} + +.contacts h3 { + font-size: 18px; + font-weight: 500; +} + +.contacts i { + margin-left: 15px; +} diff --git a/Sakalya100-Day4/Redesigned-Website/sunflower.jpg b/Sakalya100-Day4/Redesigned-Website/sunflower.jpg new file mode 100644 index 000000000..2160f8f27 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/sunflower.jpg differ diff --git a/Sakalya100-Day4/Redesigned-Website/user.png b/Sakalya100-Day4/Redesigned-Website/user.png new file mode 100644 index 000000000..8b46c4810 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/user.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/videos.png b/Sakalya100-Day4/Redesigned-Website/videos.png new file mode 100644 index 000000000..170c73926 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/videos.png differ diff --git a/Sakalya100-Day4/Redesigned-Website/warren.jfif b/Sakalya100-Day4/Redesigned-Website/warren.jfif new file mode 100644 index 000000000..3a2db4465 Binary files /dev/null and b/Sakalya100-Day4/Redesigned-Website/warren.jfif differ diff --git a/Sakalya100-Day4/web_dev/Web.html b/Sakalya100-Day4/web_dev/Web.html new file mode 100644 index 000000000..b07c4f6b3 --- /dev/null +++ b/Sakalya100-Day4/web_dev/Web.html @@ -0,0 +1,132 @@ + + + + + + GFG Challenge + + + +
+
+

+ LOGO +                     +                     +                     +                     + + HOME     + VIDEOS     + PORTFOLIO     + BLOG     + CONTACT US + +

+












+

+ + Geeky Coders + +

+

+ + #geekweeklocal + +

+
+

+ + Join Geek Week Local +      + + Follow Me + +

+
+ + +









+ +





+
+
+

PORTFOLIO

+
+

+ + + + + + + + + + + + + + +
+ + + + + +
+ + + + + +
LOAD MORE
+
+ + + +









+
+
+

CONTACT US

+
+

+
+ + + + + + + + + + + + + + + +
+ + + +
+ +
+ +
+
+
+




+
+

+ LOGO +

+

+ + Proudly made by fullyworld web tutorials. Free to use. + +

+ + \ No newline at end of file diff --git a/Sakalya100-Day4/web_dev/app.js b/Sakalya100-Day4/web_dev/app.js new file mode 100644 index 000000000..9c253a2b7 --- /dev/null +++ b/Sakalya100-Day4/web_dev/app.js @@ -0,0 +1,27 @@ +const http = require('http') +const fs = require('fs') +const port = 3722 + +const server = http.createServer(function(req,res){ + res.writeHead(200, {'Content-Type': 'text/html'}) + fs.readFile('Web.html', function(error,data){ + if(error){ + res.writeHead(404) + res.write('Error:File Not Found') + } + else{ + res.write(data) + } + res.end() + + }) +}) + +server.listen(port, function(error){ + if(error){ + console.log('Something Went Wrong') + } + else{ + console.log('Server is listening on port' + port) + } +}) diff --git a/Sakalya100-WeekEnd/DSA1-Codechef.cpp b/Sakalya100-WeekEnd/DSA1-Codechef.cpp new file mode 100644 index 000000000..f8173dbbc --- /dev/null +++ b/Sakalya100-WeekEnd/DSA1-Codechef.cpp @@ -0,0 +1,57 @@ +//Problem Name-Greedy Students +#include +using namespace std;const int N=125,V=N*N*N;typedef long long ll;struct P{int x,y;}a[N];inline void in(P&a){scanf("%d%d",&a.x,&a.y);} +inline P operator-(const P&a,const P&b){return (P){a.x-b.x,a.y-b.y};}inline ll cross(const P&a,const P&b){return 1ll*a.x*b.y-1ll*b.x*a.y;} +P X;inline int getqua(const P&a){if(a.x>0 && a.y>=0)return 1;if(a.x<=0 && a.y>0)return 2;if(a.x<0 && a.y<=0)return 3;return 4;} +inline bool cmp1(const P&a,const P&b){int oa=getqua(a-X),ob=getqua(b-X);return oa==ob?cross(a-X,b-X)>0:oat[t[z].l].d)swap(t[z].l,t[z].r);t[z].d=t[t[z].r].d+1;return z; +} +ll dis[V];int rt[V],vcnt=1,id[N][N]; +struct info{int u;ll w1,w2;}; +inline bool operator<(const info&a,const info&b){return a.w1+a.w2q; +int main(){ + scanf("%d%d",&n,&K);for(i=1;i<=n;++i)in(a[i]),aa[i]=i; + for(i=1;i<=n;++i){ + int xb=0;for(j=1;j<=n;++j)if(i!=j)rk[i][++xb]=j; + X=a[i];sort(rk[i]+1,rk[i]+xb+1,[&](int x,int y){return cmp1(a[x],a[y]);}); + } + sort(aa+1,aa+n+1,[&](int x,int y){return cmp2(a[x],a[y]);}); + for(i=1;i<=n;++i){ + int u=aa[i]; + for(k=1;k0)R[++cr]=w; + } + t[++tcnt]=node{0,0,1,1,0,0};int z=tcnt; + for(l=r=1;r<=cr;++r){ + id[v][R[r]]=++vcnt; + for(;l<=cl && cross(a[R[r]]-a[v],a[L[l]]-a[v])>0;++l) + t[++tcnt]=node{0,0,1,id[L[l]][v],dis[id[L[l]][v]],0},z=merge(z,tcnt,0,0); + dis[vcnt]=t[z].w+t[z].tg;rt[vcnt]=merge(t[z].l,t[z].r,0,0); + if(rt[vcnt])t[rt[vcnt]].tg-=dis[vcnt]; + rt[vcnt]=merge(rt[vcnt],rt[t[z].v],0,0); + dis[vcnt]+=cross(a[v]-a[u],a[R[r]]-a[u]); + q.push(info{-vcnt,dis[vcnt],0}); + } + } + bb[u]=1; + } + for(;!q.empty() && K--;){ + info u=q.top();printf("%lld ",u.w1+u.w2);q.pop();i=u.u; + if(i<0){i=-i;if(rt[i])q.push(info{rt[i],dis[i],t[rt[i]].w+t[rt[i]].tg});}else{ + j=t[i].v;if(rt[j])q.push(info{rt[j],u.w1+u.w2,t[rt[j]].w+t[rt[j]].tg}); + j=merge(t[i].l,t[i].r,0,0);if(j)t[j].tg+=t[i].tg,q.push(info{j,u.w1,t[j].w+t[j].tg}); + } + } + for(;K-->0;)printf("-1 ");puts(""); +} diff --git a/Sakalya100-WeekEnd/DSA2-Codechef.cpp b/Sakalya100-WeekEnd/DSA2-Codechef.cpp new file mode 100644 index 000000000..46f5bfa36 --- /dev/null +++ b/Sakalya100-WeekEnd/DSA2-Codechef.cpp @@ -0,0 +1,110 @@ +//problem Name- Chef and edge flipping +#include + +using namespace std; + +class dsu { + public: + vector p; + int n; + + dsu(int _n) : n(_n) {p.resize(n);iota(p.begin(), p.end(), 0);} + + inline int get(int x) {return (x == p[x] ? x : (p[x] = get(p[x])));} + + inline bool unite(int x, int y) { + x = get(x); + y = get(y); + if (x != y) { + p[x] = y; + return true; + } + return false; + } +}; + +int main() { + ios::sync_with_stdio(false); + cin.tie(0); + int tt; + cin >> tt; + while (tt--) { + int n, m; + cin >> n >> m; + dsu d1(n); + dsu d2(n); + vector> flip(m); + vector mark(n, false); + int comps = n; + bool in_first = true; + int cnt_first = 0; + for (int i = 0; i < m; i++) { + int x, y; + cin >> x >> y; + --x; --y; + flip[i] = make_pair(x, y); + if (in_first) { + if (d1.get(x) == d1.get(y) || comps > 2) { + if (d1.unite(x, y)) --comps; + ++cnt_first; + } else in_first = false; + } + if (!in_first)d2.unite(x, y); + } + vector> c(n); + for (int i = 0; i < n; i++)c[d2.get(i)].push_back(i); + + vector A,B,C; + for (auto& v : c) { + if (!v.empty()) { + int val = d1.get(v[0]); + bool ok = true; + for (int i = 1; i < (int) v.size(); i++) { + int cur = d1.get(v[i]); + if (cur != val) { + ok = false; + break; + } + } + if (ok) { + A = v; + for (int i = 0; i < n; i++) { + if (find(v.begin(), v.end(), i) == v.end()) { + if (d1.get(i) == val)B.push_back(i); + else C.push_back(i); + } + } + break; + } + } + } + assert(!A.empty()); + vector order,pos(n); + for (int x : A) order.push_back(x); + for (int x : B) order.push_back(x); + for (int x : C) order.push_back(x); + for (int i = 0; i < n; i++) pos[order[i]] = i; + + vector> g(n, vector(n)); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (pos[i] < pos[j]) g[i][j] = 1; + else g[j][i] = 1; + } + } + for (int i = 0; i < cnt_first; i++) { + int x = flip[i].first; + int y = flip[i].second; + g[x][y] ^= 1; + g[y][x] ^= 1; + } + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + if (j > i + 1) cout << " "; + cout << g[i][j]; + } + cout << '\n'; + } + } + return 0; +} diff --git a/Sakalya100-WeekEnd/DSA3-Codechef.cpp b/Sakalya100-WeekEnd/DSA3-Codechef.cpp new file mode 100644 index 000000000..a35f54600 --- /dev/null +++ b/Sakalya100-WeekEnd/DSA3-Codechef.cpp @@ -0,0 +1,114 @@ +//Problem Name- Chef at the river +#include +using namespace std; +#define ll long long +#define ui unsigned int +#define ull unsigned long long +#define db double +#define ld long double +#define pii pair +#define X first +#define Y second +#define mp make_pair +#define pb push_back +#define vi vector +#define vii vector +#define lb lower_bound +#define rep(i,a,b) for(int i=(a);i<=(b);++i) +#define per(i,b,a) for(int i=(b);i>=(a);--i) +#define rep0(i,a,b) for(int i=(a);i<(b);++i) +#define fore(i,a) for(int i=0;isz[hs[x]])hs[x]=y; + } +} +inline void up(int x) +{ + if(ls[x]&&rs[x])T[x]=T[ls[x]]+w[x]+T[rs[x]]; + else if(ls[x])T[x]=T[ls[x]]+w[x]; + else if(rs[x])T[x]=w[x]+T[rs[x]]; + else T[x]=w[x]; +} +int cbuild(int l,int r) +{ + if(l>r)return 0;int m=lower_bound(s+l,s+r+1,(s[l-1]+s[r])>>1)-s,x=q[m]; + ls[x]=cbuild(l,m-1);if(ls[x])f[ls[x]]=x; + rs[x]=cbuild(m+1,r);if(rs[x])f[rs[x]]=x; + up(x);return x; +} +int tbuild(int x) +{ + for(int i=x;i;i=hs[i])vis[i]=1; + for(int i=x;i;i=hs[i]) + { + w[i].a[0][0]=0;w[i].a[0][1]=0; + w[i].a[1][0]=(i==1?1:0);w[i].a[1][1]=-inf; + for(int j=hd[i],y;j;j=e[j].nxt)if(!vis[y=e[j].v]) + { + int t=tbuild(y);f[t]=i; + int s=gtmx(T[t]);w[i].a[0][0]+=s;w[i].a[0][1]+=s; + w[i].a[1][0]+=max(T[t].a[0][0],T[t].a[0][1]); + } + } + int nn=0; + for(int i=x;i;i=hs[i])q[++nn]=i,s[nn]=s[nn-1]+sz[i]-sz[hs[i]]; + int t=cbuild(1,nn);return t; +} +inline void upd(int x) +{ + while(x) + { + int t=f[x]; + if(t&&ls[t]!=x&&rs[t]!=x) + { + int s=gtmx(T[x]);w[t].a[0][0]-=s;w[t].a[0][1]-=s; + w[t].a[1][0]-=max(T[x].a[0][0],T[x].a[0][1]); + up(x); + s=gtmx(T[x]);w[t].a[0][0]+=s;w[t].a[0][1]+=s; + w[t].a[1][0]+=max(T[x].a[0][0],T[x].a[0][1]); + } + else up(x); + x=t; + } +} +void sol() +{ + n=rd();cc=0; + rep(i,1,n)hd[i]=d[i]=vis[i]=f[i]=ls[i]=rs[i]=0; + rep(i,2,n)fa[i]=rd(),add(fa[i],i); + pre(1,0);int rt=tbuild(1),lf=2; + rep(i,2,n) + { + if(i>2)lf+=1-(d[fa[i]]==1); + w[i].a[0][0]=0;w[i].a[0][1]=0; + w[i].a[1][0]=1;w[i].a[1][1]=-inf; + upd(i);d[i]++;d[fa[i]]++; + if(i>3&&lf==i-1)printf("%d ",3); + else printf("%d ",i-gtmx(T[rt])+1); + } + puts(""); +} +int main(){int T=rd();while(T--)sol();return 0;} diff --git a/Sakalya100-WeekEnd/DSA4-Codechef.cpp b/Sakalya100-WeekEnd/DSA4-Codechef.cpp new file mode 100644 index 000000000..cad48b8ba --- /dev/null +++ b/Sakalya100-WeekEnd/DSA4-Codechef.cpp @@ -0,0 +1,116 @@ +//Problem Name- Longest Article +#include +#include +#include +#include +#include +using namespace std; +#define rep(i,a,n) for (int i=a;if[p^1]) t=f[p^1]; + for (int p=pre[T];p;p=pre[y[p]]) f[p]+=t,f[p^1]-=t; + flow+=t;u=0; + } + } else { + if (!(--g[d[u]])) break; + d[u]=T+1;c[u]=fst[u]; + for (int j=fst[u];j;j=nxt[j]) if (f[j]&&d[y[j]]+1m||n==0||m==0) { + printf("0\n0\n"); + continue; + } + rep(i,n+1,m+1) rep(j,1,m+1) val[i][j]=inf; + int l=0,r=inf; + while (l+1>1; + if (check(md)) l=md; else r=md; + } + printf("%d\n",l); + check(l); + clr(val); + rep(i,1,m+1) for (int j=fst[i];j;j=nxt[j]) + if (y[j]>m&&y[j] +#include +#include +#include +#include + +#define LL long long +using namespace std; + +LL rot[555555]; +int rotSize; + +int binarySearchLeft(int st,int ed,LL val){// cout< val ) return binarySearchLeft(st,m,val); + else return binarySearchLeft(m,ed,val); +} + +int binarySearchRight(int st,int ed,LL val){ //cout<=val ) return st; return st-1; } + if( st+1==ed ){ + if( val >= rot[ed] ) return ed; + if( val >= rot[st] ) return st; + return st-1; + } + int m=(st+ed)/2; + if( rot[m] > val ) return binarySearchRight(st,m,val); + else return binarySearchRight(m,ed,val); +} + +struct tri{ + int size,*list; + tri *child[11]; +}*head,*headc; + +void insert(tri *&head,char *s,int val){ + if( head==NULL ){ + head=(tri*)malloc(sizeof(tri)); + head->size=0; + for(int i=0;i<11;i++) head->child[i]=NULL; + } + + if( *s=='\0' ){ + if( head->size==0 ) head->list=(int*)malloc(sizeof(int)*150); + head->list[ (head->size)++]=val; + return ; + } + insert(head->child[ *s - '0' ],s+1,val); +} + +void find(tri*h,char *s,LL val){ + if( h==NULL ) return; + if( *s=='\0'){ + for(int i=0;isize;i++) rot[rotSize++]=val+h->list[i]; + return ; + } + find(h->child[ *s-'0'],s+1,val); +} + +void make(int end,int len){ + head=headc=NULL; int sz,b; char a[12]; + for(int i=0;i=0;j--) + while( d[j]>0 ) { d[j]--; a[ sz++]='0'+j;} + a[sz++]=':'; + + for(int j=9;j>=0;j--) + while( d[j]<0 ) { d[j]++; a[ sz++]='0'+j;} + a[sz]='\0'; + + if( b ) insert(headc,a,i); + else insert(head,a,i); + } +} + + + +int main (){ + int lenght=3; + for(int i=1000;i<1000000;i*=10){ + make(i,lenght); LL val=i; + int end=i/2,sz=0; char s[12]; + + for(int j=i/10;j=0;k--) + while( d[k]<0 ) { d[k]++; s[ sz++]='0'+k;} + s[sz++]=':'; + + for(int k=9;k>=0;k--) + while( d[k]>0 ) { d[k]--; s[ sz++]='0'+k;} + s[sz++]='\0'; + + find(head,s,j*val); + + + a=j; b=j*2+1;sz=0; memset(d,0,sizeof(d)); + while( a){ d[a%10]++; a/=10; d[ b%10]--; b/=10;} + + for(int k=9;k>=0;k--) + while( d[k]<0 ) { d[k]++; s[ sz++]='0'+k;} + s[sz++]=':'; + + for(int k=9;k>=0;k--) + while( d[k]>0 ) { d[k]--; s[ sz++]='0'+k;} + s[sz++]='\0'; + + find(headc,s,j*val); + + } + + if( lenght!=5 ) + for(int j=i/10;j=0;k--) + while( d[k]<0 ) { d[k]++; s[ sz++]='0'+k;} + s[sz++]=':'; + + for(int k=9;k>=0;k--) + while( d[k]>0 ) { d[k]--; s[ sz++]='0'+k;} + s[sz++]='\0'; + + find(head,s,(j*10+jj)*val); + + + a=jj; a=j*10+jj; b=j*20+jj*2+1; sz=0; memset(d,0,sizeof(d)); + while( a){ d[a%10]++; a/=10; d[ b%10]--; b/=10;} + + for(int k=9;k>=0;k--) + while( d[k]<0 ) { d[k]++; s[ sz++]='0'+k;} + s[sz++]=':'; + + for(int k=9;k>=0;k--) + while( d[k]>0 ) { d[k]--; s[ sz++]='0'+k;} + s[sz++]='\0'; + + find(headc,s,(j*10+jj)*val); + + } + + } + lenght++; + } + + int testCase; scanf("%d",&testCase); + while( testCase--){ + LL a,b;scanf("%lld %lld",&a,&b); + printf("%d\n",binarySearchRight(0,rotSize-1,b)-binarySearchLeft(0,rotSize-1,a)+1); + } + return 0; +} diff --git a/Sakalya100-WeekEnd/DSA6-Codechef.cpp b/Sakalya100-WeekEnd/DSA6-Codechef.cpp new file mode 100644 index 000000000..1d76022eb --- /dev/null +++ b/Sakalya100-WeekEnd/DSA6-Codechef.cpp @@ -0,0 +1,614 @@ +/* + * Chef Protection Plan + * Lexical analysis, Predictive parsing [LL(1)], regex + */ +#include +#include +#include +#include +#include +#include + +using namespace std; + +const int N = 12; +const int NL = 2; +const long long MID = 2000LL; + +enum Token +{ + _lpar, _rpar, _d, _l, _string, _num, _to, _or, _times, _digit, _digits, + _letter, _letters, _upto, _exactly, _optional, _eos +}; + +enum State +{ + __default, __keyword, __letter, __string, __num, __digit, __paren +}; + +/* + * DFA + */ +class Tokenizer +{ + string s; + int ifront, irear; + vector tokenStream; + vector lexemeStream; +public: + void init(string _s) + { + s = _s; + ifront = 0; + tokenStream.clear(); + lexemeStream.clear(); + } + Token getToken(int n) + { + return tokenStream[n]; + } + bool tokenize(); + string getString(int n) + { + return lexemeStream[n]; + } +}; + +bool Tokenizer::tokenize() +{ + State state; + bool accept; + while (ifront < s.length()) { + state = __default; + accept = false; + irear = ifront; + do { + switch (state) { + case __default: + if (islower(s[ifront])) { + state = __keyword; + } else if (isupper(s[ifront])) { + state = __letter; + } else if (isdigit(s[ifront])) { + state = __digit; + } else if (s[ifront] == '(' || s[ifront] == ')') { + state = __paren; + accept = true; + } else if (s[ifront] == '-') { + state = __string; + } else { + irear++; + } + ifront++; + break; + case __string: + if (s[ifront] == ' ' || s[ifront] == '(' || s[ifront] == ')') { + accept = true; + } else if (islower(s[ifront])) { + return false; + } else { + ifront++; + } + break; + case __keyword: + if (s[ifront] == ' ' || s[ifront] == '(' || s[ifront] == ')') { + accept = true; + } else if (islower(s[ifront])) { + ifront++; + } else { + return false; + } + break; + case __digit: + if (isdigit(s[ifront])) { + state = __num; + ifront++; + break; + } + case __letter: + if (s[ifront] == ' ' || s[ifront] == '(' || s[ifront] == ')') { + accept = true; + } else if (islower(s[ifront])) { + return false; + } else { + state = __string; + ifront++; + } + break; + case __num: + if (s[ifront] == ' ' || s[ifront] == '(' || s[ifront] == ')') { + accept = true; + } else if (islower(s[ifront])) { + return false; + } else if (isupper(s[ifront])) { + state = __string; + ifront++; + } else { + ifront++; + } + break; + }; + }while (!accept && ifront < s.length()); + + string lexeme = s.substr(irear, ifront - irear); + Token token; + switch (state) { + case __default: token = _eos; + break; + case __keyword: if (lexeme == "to") token = _to; + else if (lexeme == "or") token = _or; + else if (lexeme == "times") token = _times; + else if (lexeme == "digit") token = _digit; + else if (lexeme == "digits") token = _digits; + else if (lexeme == "letter") token = _letter; + else if (lexeme == "letters") token = _letters; + else if (lexeme == "upto") token = _upto; + else if (lexeme == "exactly") token = _exactly; + else if (lexeme == "optional") token = _optional; + break; + case __digit: token = _d; + break; + case __letter: token = _l; + break; + case __string: token = _string; + break; + case __num: token = _num; + break; + case __paren: if (lexeme == "(") token = _lpar; + else token = _rpar; + break; + } + tokenStream.push_back(token); + lexemeStream.push_back(lexeme); + } + tokenStream.push_back(_eos); + return true; +} + +struct pret //parser output +{ + long long idlen; + bool correct; + pret() : idlen(0), correct(false) + {} + pret(long long _idlen, bool _correct) : idlen(_idlen), correct(_correct) + {} +}; + +class Parser; + +typedef pret (Parser::*nonTerminal)(); + +class Parser +{ + string regex; + Tokenizer *tokenizer; + int index; + long long idlen; + bool NExceeded; + bool idLenExceeded; + + Token getToken(int n) + { + return tokenizer->getToken(n); + } + string getString(int n) + { + return tokenizer->getString(n); + } + /* + * NON-TERMINALS + * return true on success, false on error + */ + pret S(); //START : E S_ + pret S_(); //S factored : E S_ | e + pret E(); //EXPR : T E_ + pret E_(); //E factored : or E | e + pret T(); //TERM : F T_ + pret T_(); //T factored : num T__ | d T__ | optional T_ | e + pret T__(); //T_ factored : times T_ | e + pret F(); //FACTOR : d F1 | l F2 | upto num F3 | upto d F3 | + // exactly num F4 | exactly d F4 | digit | letter | + // string | num | ( S ) + pret F1(); //F factored : to d | e + pret F2(); //F factored : to l | e + pret F3(); //F factored : digits | letters + pret F4(); //F factored : digits | letters + + pret JOIN(nonTerminal f1, nonTerminal f2) + { + pret p1 = (this->*f1)(), p2; + if (p1.correct) { + p2 = (this->*f2)(); + return pret(p1.idlen + p2.idlen, p2.correct); + } + return pret(); + } + pret CHOOSEMAX(nonTerminal f1, nonTerminal f2) + { + pret p1 = (this->*f1)(), p2; + if (p1.correct) { + p2 = (this->*f2)(); + return pret(std::max(p1.idlen, p2.idlen), p2.correct); + } + return pret(); + } + +public: + void init(Tokenizer *_tokenizer) + { + tokenizer = _tokenizer; + idLenExceeded = false; + NExceeded = false; + } + string getRegex() + { + return regex; + } + bool isIDLenExceeded() + { + return (idLenExceeded || idlen > MID); + } + bool isNExceeded() + { + return NExceeded; + } + bool parse(); +}; + +bool Parser::parse() +{ + index = 0; + regex = "^"; + pret r = S(); + bool done = r.correct && (getToken(index) == _eos); + regex.append("$"); + idlen = r.idlen; + return done; +} + +pret Parser::S() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly) + { + return JOIN(&Parser::E, &Parser::S_); + } + return pret(); +} + +pret Parser::S_() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly) + { + return JOIN(&Parser::E, &Parser::S_); + } + return pret(0, tok == _rpar || tok == _eos); +} + +pret Parser::E() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly) + { + regex.append("("); + pret ret = CHOOSEMAX(&Parser::T, &Parser::E_); + regex.append(")"); + return ret; + } + return pret(); +} + +pret Parser::E_() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly + || tok == _rpar || tok == _eos) + { + return pret(0, true); + } + if (tok == _or) + { + regex.append("|"); + index++; + return E(); + } + return pret(); +} + +pret Parser::T() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly) + { + string saveRegex = regex; + regex = "("; + pret r1 = F(), r2; + regex.append(")"); + + if (r1.correct) + r2 = T_(); + + int lparc = 0; + for (int i = 0; i < regex.length(); i++) + if (regex[i] == '(') + lparc++; + else if (regex[i] == ')') + { + if (lparc) + lparc--; + else + saveRegex.append("("); + } + regex = saveRegex + regex; + if (r1.idlen * r2.idlen > MID) + idLenExceeded = true; + return pret(r1.idlen * r2.idlen, r2.correct); + } + return pret(); +} + +pret Parser::T_() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _upto || tok == _exactly + || tok == _rpar || tok == _eos || tok == _or) + { + return pret(1, true); //1 Because of multiplication + } + if (tok == _optional) + { + regex.append(")"); + regex.append("?"); + index++; + return T_(); + } + if (tok == _num || tok == _d) + { + index++; + return T__(); + } + return pret(); +} + +pret Parser::T__() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly + || tok == _rpar || tok == _eos || tok == _or + || tok == _optional || tok == _to) + { + index--; + return pret(1, true); + } + if (tok == _times) + { + string s = getString(index-1); + long long n = 0; + for (int i = 0; i < s.length(); i++) + n = n*10 + s[i] - '0'; + if (n > N || s.length() > NL || s[0] == '0') + { + NExceeded = true; + return pret(); + } + regex.append(")"); + regex.append("{" + s + "}"); + index++; + pret r = T_(); + if (n * r.idlen > MID) + idLenExceeded = true; + return pret(n * r.idlen, r.correct); + } + return pret(); +} + +pret Parser::F() +{ + Token tok = getToken(index); + pret ret; + switch (tok) + { + case _lpar: + regex.append("("); + index++; + ret = S(); + ret.correct = ret.correct && (getToken(index++) == _rpar); + regex.append(")"); + return ret; + case _d: + index++; + return F1(); + case _l: + index++; + return F2(); + case _num: + case _string: + regex.append(getString(index)); + return pret(getString(index++).length(), true); + case _digit: + regex.append("[0-9]"); + index++; + return pret(1, true); + case _letter: + regex.append("[A-Z]"); + index++; + return pret(1, true); + case _upto: + index++; + tok = getToken(index++); + if (tok == _num || tok == _d) + return F3(); + break; + case _exactly: + index++; + tok = getToken(index++); + if (tok == _num || tok == _d) + return F4(); + break; + } + return pret(); +} + +pret Parser::F1() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly + || tok == _rpar || tok == _eos || tok == _or || tok == _optional) + { + regex.append(getString(index-1)); + return pret(1, true); + } + string a, b; + if (tok == _to && getToken(++index) == _d && (a = getString(index-2)) <= (b = getString(index))) + { + regex.append("[" + a + "-" + b + "]"); + index++; + return pret(1, true); + } + return pret(); +} + +pret Parser::F2() +{ + Token tok = getToken(index); + if (tok == _lpar || tok == _d || tok == _l || tok == _digit || tok == _letter + || tok == _string || tok == _num || tok == _upto || tok == _exactly + || tok == _rpar || tok == _eos || tok == _or || tok == _optional) + { + regex.append(getString(index-1)); + return pret(1, true); + } + string a, b; + if (tok == _to && getToken(++index) == _l && (a = getString(index-2)) <= (b = getString(index))) + { + regex.append("[" + a + "-" + b + "]"); + index++; + return pret(1, true); + } + return pret(); +} + +pret Parser::F3() +{ + Token tok = getToken(index); + + string s = getString(index-1); + int n = 0; + for (int i = 0; i < s.length(); i++) + n = n*10 + s[i] - '0'; + if (n > N || s.length() > NL || s[0] == '0') + { + NExceeded = true; + return pret(); + } + + if (tok == _digits) + { + regex.append("[0-9]{," + s + "}"); + index++; + return pret(n, true); + } + if (tok == _letters) + { + regex.append("[A-Z]{," + s + "}"); + index++; + return pret(n, true); + } + return pret(); +} + +pret Parser::F4() +{ + Token tok = getToken(index); + + string s = getString(index-1); + int n = 0; + for (int i = 0; i < s.length(); i++) + n = n*10 + s[i] - '0'; + if (n > N || s.length() > NL || s[0] == '0') + { + NExceeded = true; + return pret(); + } + + if (tok == _digits) + { + regex.append("[0-9]{" + s + "}"); + index++; + return pret(n, true); + } + if (tok == _letters) + { + regex.append("[A-Z]{" + s + "}"); + index++; + return pret(n, true); + } + return pret(); +} + +void skiplines(int n) +{ + string s; + while (n--) { + do { + getline(cin, s); + }while (s == ""); + } +} + +int main() +{ + ios_base::sync_with_stdio(false); + int t, n; + Tokenizer tokenizer; + string expr, regex, s; + Parser parser; + regex_t reg; + + cin >> t; + while (t--) { + do { + getline(cin, expr); + }while (expr == ""); + cin >> n; + + tokenizer.init(expr); + if (!tokenizer.tokenize()) { + cout << "Format does not conform\n\n"; + skiplines(n); + continue; + } + parser.init(&tokenizer); + if (parser.parse() && !parser.isIDLenExceeded()) { + regex = parser.getRegex(); + regcomp(®, regex.c_str(), REG_EXTENDED); + } else { + if (parser.isIDLenExceeded() && !parser.isNExceeded()) + cout << "Matches too long ID\n\n"; + else + cout << "Format does not conform\n\n"; + skiplines(n); + continue; + } + while (n--) { + cin >> s; + if (regexec(®, s.c_str(), (size_t)0, NULL, 0) == 0) + cout << "Valid-ID\n"; + else + cout << "Invalid-ID\n"; + } + cout << '\n'; + regfree(®); + } + return 0; +} diff --git a/Sakalya100-WeekEnd/GUI_project.py b/Sakalya100-WeekEnd/GUI_project.py new file mode 100644 index 000000000..1506fe758 --- /dev/null +++ b/Sakalya100-WeekEnd/GUI_project.py @@ -0,0 +1,88 @@ +# import all functions / classes from the tkinter +from tkinter import * +from textblob import TextBlob + + +# Function to clear both the text entry boxes +def clearAll(): + # whole content of text entry area is deleted + word1_field.delete(0, END) + word2_field.delete(0, END) + + +# Function to get a corrected word +def correction(): + # get a content from entry box + input_word = word1_field.get() + + # create a TextBlob object + blob_obj = TextBlob(input_word) + + # get a corrected word + corrected_word = str(blob_obj.correct()) + + # insert method inserting the + # value in the text entry box. + word2_field.insert(10, corrected_word) + + +# Driver code +if __name__ == "__main__": + # Create a GUI window + root = Tk() + + # Set the background colour of GUI window + root.configure(background='light green') + + # Set the configuration of GUI window (WidthxHeight) + root.geometry("400x150") + + # set the name of tkinter GUI window + root.title("Spell Corrector by Sakalya") + + # Create Welcome to Spell Corrector Application: label + headlabel = Label(root, text='Welcome to Spell Corrector Application', + fg='black', bg="yellow") + + # Create a "Input Word": label + label1 = Label(root, text="Input Word", + fg='black', bg='white') + + # Create a "Corrected Word": label + label2 = Label(root, text="Corrected Word", + fg='black', bg='white') + + # grid method is used for placing + # the widgets at respective positions + # in table like structure . + # padx keyword argument used to set paading along x-axis . + headlabel.grid(row=0, column=1) + label1.grid(row=1, column=0) + label2.grid(row=3, column=0, padx=10) + + # Create a text entry box + # for filling or typing the information. + word1_field = Entry() + word2_field = Entry() + + # padx keyword argument used to set paading along x-axis . + # pady keyword argument used to set paading along y-axis . + word1_field.grid(row=1, column=1, padx=10, pady=10) + word2_field.grid(row=3, column=1, padx=10, pady=10) + + # Create a Correction Button and attached + # with correction function + button1 = Button(root, text="Correction", bg="red", fg="black", + command=correction) + + button1.grid(row=2, column=1) + + # Create a Clear Button and attached + # with clearAll function + button2 = Button(root, text="Clear", bg="red", + fg="black", command=clearAll) + + button2.grid(row=4, column=1) + + # Start the GUI + root.mainloop() diff --git a/Sakalya100-WeekEnd/JARVIS.py b/Sakalya100-WeekEnd/JARVIS.py new file mode 100644 index 000000000..e439d4116 --- /dev/null +++ b/Sakalya100-WeekEnd/JARVIS.py @@ -0,0 +1,60 @@ +import speech_recognition as sr +import pyttsx3 +import pywhatkit +import datetime +import wikipedia +import pyjokes + +listener = sr.Recognizer() +engine = pyttsx3.init() +voices = engine.getProperty('voices') +engine.setProperty('voice', voices[1].id) + + +def talk(text): + engine.say(text) + engine.runAndWait() + + +def take_command(): + try: + with sr.Microphone() as source: + print('listening...') + voice = listener.listen(source) + command = listener.recognize_google(voice) + command = command.lower() + if 'alexa' in command: + command = command.replace('alexa', '') + print(command) + except: + pass + return command + + +def run_alexa(): + command = take_command() + print(command) + if 'play' in command: + song = command.replace('play', '') + talk('playing ' + song) + pywhatkit.playonyt(song) + elif 'time' in command: + time = datetime.datetime.now().strftime('%I:%M %p') + talk('Current time is ' + time) + elif 'who the heck is' in command: + person = command.replace('who the heck is', '') + info = wikipedia.summary(person, 1) + print(info) + talk(info) + elif 'date' in command: + talk('sorry, I have a headache') + elif 'are you single' in command: + talk('I am in a relationship with wifi') + elif 'joke' in command: + talk(pyjokes.get_joke()) + else: + talk('Please say the command again.') + + +while True: + run_alexa() \ No newline at end of file diff --git a/Sakalya100/Day2-Problem1.cpp b/Sakalya100/Day2-Problem1.cpp new file mode 100644 index 000000000..ee911eb9a --- /dev/null +++ b/Sakalya100/Day2-Problem1.cpp @@ -0,0 +1,36 @@ +#include +#include + +int S1[256], S2[256], S[256]; + +void answer(string s1, string s2, string s) +{ + memset(S1, 0, sizeof S1); + memset(S2, 0, sizeof S2); + memset(S, 0, sizeof S); + + for (int i = 0; i < s1.size(); i++) + { + S1[s1[i]]++; + } + + for (int i = 0; i < s2.size(); i++) + { + S2[s2[i]]++; + } + + for (int i = 0; i < s.size(); i++) + { + S[s[i]]++; + } + for (int i = 0; i < 256; i++) + { + if (S[i] != S1[i] + S2[i]) + { + cout << "NO" << endl; + exit(0); + } + } + cout << "YES" << endl; + return; +} diff --git a/Sakalya100/Day2-Problem2.cpp b/Sakalya100/Day2-Problem2.cpp new file mode 100644 index 000000000..93a3b012a --- /dev/null +++ b/Sakalya100/Day2-Problem2.cpp @@ -0,0 +1,61 @@ +//Longest Bracket Sequence +void update(int tmp, int &len, int &cnt) +{ + if (tmp > len) + { + len = tmp; + cnt = 1; + } + else if (tmp == len) + { + cnt++; + } +} + +void solve(string s) +{ + int f[s.size() + 1], second[s.size() + 1], top; + + int n = s.size(); + int len = 0, cnt = 1; + if (n == 0) + { + puts("0 1"); + return; + } + + top = 0; + for (int i = 0; i < n; ++i) + { + if (s[i] == '(') + { + second[top++] = i; + f[i] = 0; + } + else + { + if (top == 0) + { + f[i] = 0; + } + else + { + int k = second[--top], tmp = 0; + if (k > 0) + { + tmp = i - k + 1 + f[k - 1]; + } + else + { + tmp = i - k + 1; + } + + f[i] = tmp; + + update(tmp, len, cnt); + } + } + } + + cout << len << " " << cnt; +} \ No newline at end of file diff --git a/Sakalya100/Day2-Problem3.cpp b/Sakalya100/Day2-Problem3.cpp new file mode 100644 index 000000000..acc85bdce --- /dev/null +++ b/Sakalya100/Day2-Problem3.cpp @@ -0,0 +1,39 @@ +//Compressed string +string getCompressedString(string s) +{ + int n = s.length(); + string answer = ""; + + if (n == 0) + { + return answer; + } + + int currentCharCount = 1; + answer += s[0]; + + for (int i = 1; i < n; ++i) + { + if (s[i] == s[i - 1]) + { + ++currentCharCount; + } + else + { + if (currentCharCount > 1) + { + answer += to_string(currentCharCount); + currentCharCount = 1; + } + + answer += s[i]; + } + } + + if (currentCharCount > 1) + { + answer += to_string(currentCharCount); + } + + return answer; +} \ No newline at end of file diff --git a/Sakalya100_Day3/API.py b/Sakalya100_Day3/API.py new file mode 100644 index 000000000..bdef6c21d --- /dev/null +++ b/Sakalya100_Day3/API.py @@ -0,0 +1,8 @@ +import requests +api_adress = 'http://api.openweathermap.org/data/2.5/weather?appid=1ff6c206dc85dfaa9483c118a661d090&q=' +city=input("City Name : " ) + +url= api_adress + city + +json_data = requests.get(url) +print(json_data) diff --git a/Sakalya100_Day3/Day3-Problem1.py b/Sakalya100_Day3/Day3-Problem1.py new file mode 100644 index 000000000..c42bf31e8 --- /dev/null +++ b/Sakalya100_Day3/Day3-Problem1.py @@ -0,0 +1,45 @@ +import math +import os +import random +import re +import sys + +# Complete the hourglassSum function below. +def hourglassSum(arr): + + # want to find the maximum hourglass sum + # minimum hourglass sum = -9 * 7 = -63 + maxSum = -63 + + for i in range(4): + for j in range(4): + + # sum of top 3 elements + top = sum(arr[i][j:j+3]) + + # sum of the mid element + mid = arr[i+1][j+1] + + # sum of bottom 3 elements + bottom = sum(arr[i+2][j:j+3]) + + hourglass = top + mid + bottom + + if hourglass > maxSum: + maxSum = hourglass + + return maxSum + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + arr = [] + + for _ in range(6): + arr.append(list(map(int, input().rstrip().split()))) + + result = hourglassSum(arr) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Sakalya100_Day3/Day3-Problem2.py b/Sakalya100_Day3/Day3-Problem2.py new file mode 100644 index 000000000..08c16100a --- /dev/null +++ b/Sakalya100_Day3/Day3-Problem2.py @@ -0,0 +1,47 @@ +import math +import os +import random +import re +import sys + +# Complete the matchingStrings function below. +def matchingStrings(strings, queries): + words = dict() + ans = [] + for w in strings: + if w in words: + words[w] += 1 + else: + words[w] = 1 + for q in queries: + if q in words: + ans.append(words[q]) + else: + ans.append(0) + return ans + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + strings_count = int(input()) + + strings = [] + + for _ in range(strings_count): + strings_item = input() + strings.append(strings_item) + + queries_count = int(input()) + + queries = [] + + for _ in range(queries_count): + queries_item = input() + queries.append(queries_item) + + res = matchingStrings(strings, queries) + + fptr.write('\n'.join(map(str, res))) + fptr.write('\n') + + fptr.close() diff --git a/Sakalya100_Day3/Day3-Problem3.py b/Sakalya100_Day3/Day3-Problem3.py new file mode 100644 index 000000000..44b15c032 --- /dev/null +++ b/Sakalya100_Day3/Day3-Problem3.py @@ -0,0 +1,45 @@ +import math +import os +import random +import re +import sys + +# Complete the arrayManipulation function below. +def arrayManipulation(n, queries): + arr = [0] * (n+1) + # add the value at first index + # subtract the value at last index + 1 + for q in queries: + start, end, amt = q + arr[start-1] += amt + arr[end] -= amt + + # max value and running sum + mv = -1 + running = 0 + for a in arr: + running += a + if running > mv: + mv = running + + return mv + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + nm = input().split() + + n = int(nm[0]) + + m = int(nm[1]) + + queries = [] + + for _ in range(m): + queries.append(list(map(int, input().rstrip().split()))) + + result = arrayManipulation(n, queries) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Sakalya100_Day3/Tic_Tac_Toe.py b/Sakalya100_Day3/Tic_Tac_Toe.py new file mode 100644 index 000000000..cbd11e2f6 --- /dev/null +++ b/Sakalya100_Day3/Tic_Tac_Toe.py @@ -0,0 +1,237 @@ +from tkinter import * +from tkinter import messagebox + +root = Tk() +root.title('Codemy.com - Tic-Tac-Toe') +root.iconbitmap('c:/gui/codemy.ico') +# root.geometry("1200x710") + +# X starts so true +clicked = True +count = 0 + + +# disable all the buttons +def disable_all_buttons(): + b1.config(state=DISABLED) + b2.config(state=DISABLED) + b3.config(state=DISABLED) + b4.config(state=DISABLED) + b5.config(state=DISABLED) + b6.config(state=DISABLED) + b7.config(state=DISABLED) + b8.config(state=DISABLED) + b9.config(state=DISABLED) + + +# Check to see if someone won +def checkifwon(): + global winner + winner = False + + if b1["text"] == "X" and b2["text"] == "X" and b3["text"] == "X": + b1.config(bg="red") + b2.config(bg="red") + b3.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + elif b4["text"] == "X" and b5["text"] == "X" and b6["text"] == "X": + b4.config(bg="red") + b5.config(bg="red") + b6.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b7["text"] == "X" and b8["text"] == "X" and b9["text"] == "X": + b7.config(bg="red") + b8.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b1["text"] == "X" and b4["text"] == "X" and b7["text"] == "X": + b1.config(bg="red") + b4.config(bg="red") + b7.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b2["text"] == "X" and b5["text"] == "X" and b8["text"] == "X": + b2.config(bg="red") + b5.config(bg="red") + b8.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b3["text"] == "X" and b6["text"] == "X" and b9["text"] == "X": + b3.config(bg="red") + b6.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b1["text"] == "X" and b5["text"] == "X" and b9["text"] == "X": + b1.config(bg="red") + b5.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + elif b3["text"] == "X" and b5["text"] == "X" and b7["text"] == "X": + b3.config(bg="red") + b5.config(bg="red") + b7.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! X Wins!!") + disable_all_buttons() + + #### CHECK FOR O's Win + elif b1["text"] == "O" and b2["text"] == "O" and b3["text"] == "O": + b1.config(bg="red") + b2.config(bg="red") + b3.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + elif b4["text"] == "O" and b5["text"] == "O" and b6["text"] == "O": + b4.config(bg="red") + b5.config(bg="red") + b6.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b7["text"] == "O" and b8["text"] == "O" and b9["text"] == "O": + b7.config(bg="red") + b8.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b1["text"] == "O" and b4["text"] == "O" and b7["text"] == "O": + b1.config(bg="red") + b4.config(bg="red") + b7.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b2["text"] == "O" and b5["text"] == "O" and b8["text"] == "O": + b2.config(bg="red") + b5.config(bg="red") + b8.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b3["text"] == "O" and b6["text"] == "O" and b9["text"] == "O": + b3.config(bg="red") + b6.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b1["text"] == "O" and b5["text"] == "O" and b9["text"] == "O": + b1.config(bg="red") + b5.config(bg="red") + b9.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + elif b3["text"] == "O" and b5["text"] == "O" and b7["text"] == "O": + b3.config(bg="red") + b5.config(bg="red") + b7.config(bg="red") + winner = True + messagebox.showinfo("Tic Tac Toe", "CONGRATULATIONS! O Wins!!") + disable_all_buttons() + + # Check if tie + if count == 9 and winner == False: + messagebox.showinfo("Tic Tac Toe", "It's A Tie!\n No One Wins!") + disable_all_buttons() + + +# Button clicked function +def b_click(b): + global clicked, count + + if b["text"] == " " and clicked == True: + b["text"] = "X" + clicked = False + count += 1 + checkifwon() + elif b["text"] == " " and clicked == False: + b["text"] = "O" + clicked = True + count += 1 + checkifwon() + else: + messagebox.showerror("Tic Tac Toe", "Hey! That box has already been selected\nPick Another Box...") + + +# Start the game over! +def reset(): + global b1, b2, b3, b4, b5, b6, b7, b8, b9 + global clicked, count + clicked = True + count = 0 + + # Build our buttons + b1 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b1)) + b2 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b2)) + b3 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b3)) + + b4 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b4)) + b5 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b5)) + b6 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b6)) + + b7 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b7)) + b8 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b8)) + b9 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", + command=lambda: b_click(b9)) + + # Grid our buttons to the screen + b1.grid(row=0, column=0) + b2.grid(row=0, column=1) + b3.grid(row=0, column=2) + + b4.grid(row=1, column=0) + b5.grid(row=1, column=1) + b6.grid(row=1, column=2) + + b7.grid(row=2, column=0) + b8.grid(row=2, column=1) + b9.grid(row=2, column=2) + + +# Create menue +my_menu = Menu(root) +root.config(menu=my_menu) + +# Create Options Menu +options_menu = Menu(my_menu, tearoff=False) +my_menu.add_cascade(label="Options", menu=options_menu) +options_menu.add_command(label="Rest Game", command=reset) + +reset() + +root.mainloop() diff --git a/Sakalya100_Day3/weather_api.py b/Sakalya100_Day3/weather_api.py new file mode 100644 index 000000000..5cd31784f --- /dev/null +++ b/Sakalya100_Day3/weather_api.py @@ -0,0 +1,44 @@ +import tkinter as tk +import requests +import time + + +def getWeather(canvas): + city = textField.get() + api = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=1ff6c206dc85dfaa9483c118a661d090" + + json_data = requests.get(api).json() + condition = json_data['weather'][0]['main'] + temp = int(json_data['main']['temp'] - 273.15) + min_temp = int(json_data['main']['temp_min'] - 273.15) + max_temp = int(json_data['main']['temp_max'] - 273.15) + pressure = json_data['main']['pressure'] + humidity = json_data['main']['humidity'] + wind = json_data['wind']['speed'] + sunrise = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunrise'] - 21600)) + sunset = time.strftime('%I:%M:%S', time.gmtime(json_data['sys']['sunset'] - 21600)) + + final_info = condition + "\n" + str(temp) + "°C" + final_data = "\n" + "Min Temp: " + str(min_temp) + "°C" + "\n" + "Max Temp: " + str( + max_temp) + "°C" + "\n" + "Pressure: " + str(pressure) + "\n" + "Humidity: " + str( + humidity) + "\n" + "Wind Speed: " + str(wind) + "\n" + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset + label1.config(text=final_info) + label2.config(text=final_data) + + +canvas = tk.Tk() +canvas.geometry("600x500") +canvas.title("Weather App") +f = ("poppins", 15, "bold") +t = ("poppins", 35, "bold") + +textField = tk.Entry(canvas, justify='center', width=20, font=t) +textField.pack(pady=20) +textField.focus() +textField.bind('', getWeather) + +label1 = tk.Label(canvas, font=t) +label1.pack() +label2 = tk.Label(canvas, font=f) +label2.pack() +canvas.mainloop() \ No newline at end of file diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Board.js b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Board.js new file mode 100644 index 000000000..882358c03 --- /dev/null +++ b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Board.js @@ -0,0 +1,185 @@ +class Board { + constructor() { + this.whitePieces = []; + this.blackPieces = []; + this.score = 0; + this.setupPieces(); + + + } + + setupPieces() { + this.whitePieces.push(new King(4, 7, true)); + this.whitePieces.push(new Queen(3, 7, true)); + this.whitePieces.push(new Bishop(2, 7, true)); + this.whitePieces.push(new Bishop(5, 7, true)); + this.whitePieces.push(new Knight(1, 7, true)); + this.whitePieces.push(new Rook(0, 7, true)); + this.whitePieces.push(new Knight(6, 7, true)); + this.whitePieces.push(new Rook(7, 7, true)); + + this.whitePieces.push(new Pawn(4, 6, true)); + this.whitePieces.push(new Pawn(3, 6, true)); + this.whitePieces.push(new Pawn(2, 6, true)); + this.whitePieces.push(new Pawn(5, 6, true)); + this.whitePieces.push(new Pawn(1, 6, true)); + this.whitePieces.push(new Pawn(0, 6, true)); + this.whitePieces.push(new Pawn(6, 6, true)); + this.whitePieces.push(new Pawn(7, 6, true)); + + //black pieces + this.blackPieces.push(new King(4, 0, false)); + this.blackPieces.push(new Queen(3, 0, false)); + this.blackPieces.push(new Bishop(2, 0, false)); + this.blackPieces.push(new Bishop(5, 0, false)); + this.blackPieces.push(new Knight(1, 0, false)); + this.blackPieces.push(new Rook(0, 0, false)); + this.blackPieces.push(new Knight(6, 0, false)); + this.blackPieces.push(new Rook(7, 0, false)); + + this.blackPieces.push(new Pawn(4, 1, false)); + this.blackPieces.push(new Pawn(3, 1, false)); + this.blackPieces.push(new Pawn(2, 1, false)); + this.blackPieces.push(new Pawn(5, 1, false)); + this.blackPieces.push(new Pawn(1, 1, false)); + this.blackPieces.push(new Pawn(0, 1, false)); + this.blackPieces.push(new Pawn(6, 1, false)); + this.blackPieces.push(new Pawn(7, 1, false)); + + + } + + show() { + for (var i = 0; i < this.whitePieces.length; i++) { + this.whitePieces[i].show(); + } + for (var i = 0; i < this.blackPieces.length; i++) { + this.blackPieces[i].show(); + } + } + + isPieceAt(x, y) { + for (var i = 0; i < this.whitePieces.length; i++) { + if (!this.whitePieces[i].taken && this.whitePieces[i].matrixPosition.x == + x && this.whitePieces[i].matrixPosition.y == y) { + return true; + } + } + for (var i = 0; i < this.blackPieces.length; i++) { + if (!this.blackPieces[i].taken && this.blackPieces[i].matrixPosition.x == + x && this.blackPieces[i].matrixPosition.y == y) { + return true; + } + } + return false; + } + + getPieceAt(x, y) { + for (var i = 0; i < this.whitePieces.length; i++) { + if (!this.whitePieces[i].taken && this.whitePieces[i].matrixPosition.x == + x && this.whitePieces[i].matrixPosition.y == y) { + return this.whitePieces[i]; + } + } + for (var i = 0; i < this.blackPieces.length; i++) { + if (!this.blackPieces[i].taken && this.blackPieces[i].matrixPosition.x == + x && this.blackPieces[i].matrixPosition.y == y) { + return this.blackPieces[i]; + } + } + return null; + } + + + generateNewBoardsWhitesTurn() { + var boards = []; + for (var i = 0; i < this.whitePieces.length; i++) { + if (!this.whitePieces[i].taken) { + var tempArr = this.whitePieces[i].generateNewBoards(this); + for (var j = 0; j < tempArr.length; j++) { + boards.push(tempArr[j]); + } + } + } + return boards; + } + generateNewBoardsBlacksTurn() { + var boards = []; + for (var i = 0; i < this.blackPieces.length; i++) { + if (!this.blackPieces[i].taken) { + var tempArr = this.blackPieces[i].generateNewBoards(this); + for (var j = 0; j < tempArr.length; j++) { + boards.push(tempArr[j]); + } + } + } + return boards; + } + + setScore() { + this.score = 0; + for (var i = 0; i < this.whitePieces.length; i++) { + if (!this.whitePieces[i].taken) { + this.score -= this.whitePieces[i].value; + } else { + //print("something"); + } + } + for (var i = 0; i < this.blackPieces.length; i++) { + if (!this.blackPieces[i].taken) { + this.score += this.blackPieces[i].value; + } else { + //print("something"); + } + } + + } + + move(from, to) { + var pieceToMove = this.getPieceAt(from.x, from.y); + if (pieceToMove == null) { + //print("shit"); + return; + } + // if (pieceToMove.canMove(to.x, to.y, this)) { + pieceToMove.move(to.x, to.y, this); + // } + } + + + clone() { + var clone = new Board(); + for (var i = 0; i < this.whitePieces.length; i++) { + clone.whitePieces[i] = this.whitePieces[i].clone(); + } + for (var i = 0; i < this.blackPieces.length; i++) { + clone.blackPieces[i] = this.blackPieces[i].clone(); + } + return clone; + } + + isDone() { + return this.whitePieces[0].taken || this.blackPieces[0].taken; + } + isDead() { + if (whiteAI && whitesMove) { + return this.whitePieces[0].taken; + } + if (blackAI && !whitesMove) { + return this.blackPieces[0].taken; + } + + return false; + } + + hasWon() { + if (whiteAI && whitesMove) { + return this.blackPieces[0].taken; + } + if (blackAI && !whitesMove) { + return this.whitePieces[0].taken; + } + + return false; + } +} diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/MinimaxFunctions.js b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/MinimaxFunctions.js new file mode 100644 index 000000000..61b762d96 --- /dev/null +++ b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/MinimaxFunctions.js @@ -0,0 +1,176 @@ +var maxDepth = 3; + + +function minFun(board, depth) { + if (depth >= maxDepth) { + board.setScore(); + return board.score; + } + + var boards = board.generateNewBoardsWhitesTurn(); + var lowestBoardNo = 0; + var lowestScore = 100000; + for (var i = 0; i < boards.length; i++) { + if (!boards[i].isDead()) { + var score = maxFun(boards[i], depth + 1); + if (score < lowestScore) { + lowestBoardNo = i; + lowestScore = score; + } + } + } + return lowestScore; +} + +function maxFun(board, depth) { + if (depth >= maxDepth) { + board.setScore(); + return board.score; + } + + + var boards = board.generateNewBoardsBlacksTurn(); + if (depth == 0) { + //////print(boards); + } + var topBoardNo = 0; + var topScore = -100000; + for (var i = 0; i < boards.length; i++) { + var score = minFun(boards[i], depth + 1); + if (score > topScore) { + topBoardNo = i; + topScore = score; + } + } + + if (depth == 0) { + ////print(topScore); + return boards[topBoardNo]; + } + return topScore; +} + + +function minFunAB(board, alpha, beta, depth) { + if (depth >= maxDepth) { + board.setScore(); + return board.score; + } + + + if (board.isDead()) { + if (whiteAI && whitesMove) { + return 200; + } + if (blackAI && !whitesMove) { + return -200; + } + } + + if (board.hasWon()) { + + if (whiteAI && whitesMove) { + return -200; + } + if (blackAI && !whitesMove) { + return 200; + } + } + + var boards = board.generateNewBoardsWhitesTurn(); + var lowestBoardNo = 0; + var lowestScore = 300; + for (var i = 0; i < boards.length; i++) { + + var score = maxFunAB(boards[i], alpha, beta, depth + 1); + if (depth == 0) { + //print(score, i, boards[i]); + } + if (score < lowestScore) { + lowestBoardNo = i; + lowestScore = score; + } else { + if (depth == 0 && score == lowestScore) { + //print("same as so i do what i want", i); + if (random(1) < 0.3) { + lowestBoardNo = i; + } + } + } + if (score < alpha) { + return lowestScore; + } + if (score < beta) { + beta = score; + } + + } + + if (depth == 0) { + ////print(lowestScore); + ////print("i made it here"); + return boards[lowestBoardNo]; + } + ////print("ohNo"); + ////print(lowestScore); + return lowestScore; +} +//--------------------------------------------------------------------------------------- +function maxFunAB(board, alpha, beta, depth) { + if (depth >= maxDepth) { + board.setScore(); + return board.score; + } + + if (board.isDead()) { + if (whiteAI && whitesMove) { + return 200; + } + if (blackAI && !whitesMove) { + return -200; + } + } + + if (board.hasWon()) { + if (whiteAI && whitesMove) { + return -200; + } + if (blackAI && !whitesMove) { + return 200; + } + } + + var boards = board.generateNewBoardsBlacksTurn(); + if (depth == 0) { + //////print(boards); + } + var topBoardNo = 0; + var topScore = -300; + for (var i = 0; i < boards.length; i++) { + + var score = minFunAB(boards[i], alpha, beta, depth + 1); + if (score > topScore) { + topBoardNo = i; + topScore = score; + } else { + if (depth == 0 && score == topScore) { + if (random(1) < 0.3) { + topBoardNo = i; + } + } + } + if (score > beta) { + return topScore; + } + if (score > alpha) { + alpha = score; + } + + } + + if (depth == 0) { + ////print(topScore); + return boards[topBoardNo]; + } + return topScore; +} diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Piece.js b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Piece.js new file mode 100644 index 000000000..094122c86 --- /dev/null +++ b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/Piece.js @@ -0,0 +1,628 @@ +class Piece { + constructor(x, y, isWhite, letter, pic) { + this.matrixPosition = createVector(x, y); + this.pixelPosition = createVector(x * tileSize + tileSize / 2, y * + tileSize + tileSize / 2); + + this.taken = false; + this.white = isWhite; + this.letter = letter; + this.pic = pic; + this.movingThisPiece = false; + this.value = 0; + } + + //needs to extend these + show() { + if (!this.taken) { + + // textSize(40); + // strokeWeight(5); + // if(this.white){ + // fill(255); + // stroke(0); + // }else{ + // fill(30); + // stroke(255); + // } + // textAlign(CENTER,CENTER); + imageMode(CENTER); + if (this.movingThisPiece) { + // text(this.letter, mouseX,mouseY); + image(this.pic, mouseX, mouseY, tileSize * 1.5, tileSize * 1.5); + + } else { + // text(this.letter, this.pixelPosition.x,this.pixelPosition.y); + image(this.pic, this.pixelPosition.x, this.pixelPosition.y, tileSize, + tileSize); + + } + } + } + + + generateNewBoards(currentBoard) { + var boards = []; //all boards created from moving this piece + var moves = this.generateMoves(currentBoard); //all the posible moves this piece can do ,as vectors + for (var i = 0; i < moves.length; i++) { //for each move + boards[i] = currentBoard.clone(); //create a new board + boards[i].move(this.matrixPosition, moves[i]); //move this piece to the mvoe location + } + + return boards; + } + + + withinBounds(x, y) { + + if (x >= 0 && y >= 0 && x < 8 && y < 8) { + return true; + } + return false; + + } + + + + move(x, y, board) { + var attacking = board.getPieceAt(x, y); + if (attacking != null) { + attacking.taken = true; + } + this.matrixPosition = createVector(x, y); + this.pixelPosition = createVector(x * tileSize + tileSize / 2, y * + tileSize + tileSize / 2); + + } + attackingAllies(x, y, board) { + var attacking = board.getPieceAt(x, y); + if (attacking != null) { + if (attacking.white == this.white) { + //if they are of the same player + return true; + } + } + return false; + } + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + return true; + } + + moveThroughPieces(x, y, board) { + var stepDirectionX = x - this.matrixPosition.x; + if (stepDirectionX > 0) { + stepDirectionX = 1; + } else if (stepDirectionX < 0) { + stepDirectionX = -1; + } + var stepDirectionY = y - this.matrixPosition.y; + if (stepDirectionY > 0) { + stepDirectionY = 1; + } else if (stepDirectionY < 0) { + stepDirectionY = -1; + } + var tempPos = createVector(this.matrixPosition.x, this.matrixPosition.y); + tempPos.x += stepDirectionX; + tempPos.y += stepDirectionY; + while (tempPos.x != x || tempPos.y != y) { + + if (board.getPieceAt(tempPos.x, tempPos.y) != null) { + return true; + } + tempPos.x += stepDirectionX; + tempPos.y += stepDirectionY; + } + + return false; + } + + + +} + +class King extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "K"; + if (isWhite) { + this.pic = images[0]; + + } else { + this.pic = images[6]; + } + this.value = 99; + } + + clone() { + var clone = new King(this.matrixPosition.x, this.matrixPosition.y, this.white); + clone.taken = this.taken; + return clone; + + } + + + + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + if (abs(x - this.matrixPosition.x) <= 1 && abs(y - this.matrixPosition.y) <= + 1) { + return true; + } + return false; + } + + generateMoves(board) { + var moves = []; + for (var i = -1; i < 2; i++) { + for (var j = -1; j < 2; j++) { + var x = this.matrixPosition.x + i; + var y = this.matrixPosition.y + j; + if (this.withinBounds(x, y)) { + if (i != 0 || j != 0) { + if (!this.attackingAllies(x, y, board)) { + moves.push(createVector(x, y)) + } + } + } + } + + } + return moves; + + } +} + +class Queen extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "Q"; + if (isWhite) { + this.pic = images[1]; + + } else { + this.pic = images[7]; + } + this.value = 9; + + } + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + + if (x == this.matrixPosition.x || y == this.matrixPosition.y) { + if (this.moveThroughPieces(x, y, board)) { + return false; + } + + return true; + } + //diagonal + if (abs(x - this.matrixPosition.x) == abs(y - this.matrixPosition.y)) { + if (this.moveThroughPieces(x, y, board)) { + return false; + } + + return true; + } + return false; + } + generateMoves(board) { + var moves = []; + + //generateHorizontal moves + for (var i = 0; i < 8; i++) { + var x = i; + var y = this.matrixPosition.y; + if (x != this.matrixPosition.x) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + //generateVertical moves + for (var i = 0; i < 8; i++) { + var x = this.matrixPosition.x;; + var y = i; + if (i != this.matrixPosition.y) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + + //generateDiagonal Moves + for (var i = 0; i < 8; i++) { + var x = i; + var y = this.matrixPosition.y - (this.matrixPosition.x - i); + if (x != this.matrixPosition.x) { + if (this.withinBounds(x, y)) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + } + + for (var i = 0; i < 8; i++) { + var x = this.matrixPosition.x + (this.matrixPosition.y - i); + var y = i; + if (x != this.matrixPosition.x) { + if (this.withinBounds(x, y)) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + } + //print("Queen", moves); + return moves; + } + clone() { + var clone = new Queen(this.matrixPosition.x, this.matrixPosition.y, + this.white); + clone.taken = this.taken; + return clone; + + } +} +class Bishop extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "B"; + if (isWhite) { + this.pic = images[2]; + + } else { + this.pic = images[8]; + } + this.value = 3; + + } + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + + + //diagonal + if (abs(x - this.matrixPosition.x) == abs(y - this.matrixPosition.y)) { + if (this.moveThroughPieces(x, y, board)) { + return false; + } + + return true; + } + return false; + } + + generateMoves(board) { + var moves = []; + //generateDiagonal Moves + for (var i = 0; i < 8; i++) { + var x = i; + var y = this.matrixPosition.y - (this.matrixPosition.x - i); + if (x != this.matrixPosition.x) { + if (this.withinBounds(x, y)) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + } + + for (var i = 0; i < 8; i++) { + var x = this.matrixPosition.x + (this.matrixPosition.y - i); + var y = i; + if (x != this.matrixPosition.x) { + if (this.withinBounds(x, y)) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + } + //print("Bishop", moves); + + return moves; + } + clone() { + var clone = new Bishop(this.matrixPosition.x, this.matrixPosition.y, + this.white); + clone.taken = this.taken; + return clone; + + } +} +class Rook extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "R"; + if (isWhite) { + this.pic = images[4]; + + } else { + this.pic = images[10]; + } + this.value = 5; + + } + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + + + if (x == this.matrixPosition.x || y == this.matrixPosition.y) { + if (this.moveThroughPieces(x, y, board)) { + return false; + } + + return true; + } + return false; + } + + generateMoves(board) { + var moves = []; + + //generateHorizontal moves + for (var i = 0; i < 8; i++) { + var x = i; + var y = this.matrixPosition.y; + if (x != this.matrixPosition.x) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + //generateVertical moves + for (var i = 0; i < 8; i++) { + var x = this.matrixPosition.x;; + var y = i; + if (i != this.matrixPosition.y) { + if (!this.attackingAllies(x, y, board)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + } + //print("Rook", moves); + + return moves; + + + } + + clone() { + var clone = new Rook(this.matrixPosition.x, this.matrixPosition.y, this + .white); + clone.taken = this.taken; + return clone; + + } +} +class Knight extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "Kn"; + if (isWhite) { + this.pic = images[3]; + + } else { + this.pic = images[9]; + } + this.value = 3; + + } + + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + + + if ((abs(x - this.matrixPosition.x) == 2 && abs(y - this.matrixPosition + .y) == 1) || (abs(x - this.matrixPosition.x) == 1 && abs(y - this.matrixPosition + .y) == 2)) { + return true; + } + return false; + } + + + + generateMoves(board) { + var moves = []; + for (var i = -2; i < 3; i += 4) { + for (var j = -1; j < 2; j += 2) { + + var x = i + this.matrixPosition.x; + var y = j + this.matrixPosition.y; + if (!this.attackingAllies(x, y, board)) { + if (this.withinBounds(x, y)) { + moves.push(createVector(x, y)); + + } + } + } + } + for (var i = -1; i < 2; i += 2) { + for (var j = -2; j < 3; j += 4) { + + var x = i + this.matrixPosition.x; + var y = j + this.matrixPosition.y; + + if (this.withinBounds(x, y)) { + if (!this.attackingAllies(x, y, board)) { + moves.push(createVector(x, y)); + + } + } + } + } + //print("Knight", moves); + + return moves; + + } + clone() { + var clone = new Knight(this.matrixPosition.x, this.matrixPosition.y, + this.white); + clone.taken = this.taken; + return clone; + + } +} +class Pawn extends Piece { + constructor(x, y, isWhite) { + super(x, y, isWhite); + this.letter = "p"; + this.firstTurn = true; + if (isWhite) { + this.pic = images[5]; + + } else { + this.pic = images[11]; + } + this.value = 1; + + } + + canMove(x, y, board) { + if (!this.withinBounds(x, y)) { + return false; + } + if (this.attackingAllies(x, y, board)) { + return false; + } + var attacking = board.isPieceAt(x, y); + if (attacking) { + //if attacking a player + if (abs(x - this.matrixPosition.x) == abs(y - this.matrixPosition.y) && + ((this.white && (y - this.matrixPosition.y) == -1) || (!this.white && + (y - this.matrixPosition.y) == 1))) { + this.firstTurn = false; + return true; + } + return false; + } + if (x != this.matrixPosition.x) { + return false; + } + if ((this.white && y - this.matrixPosition.y == -1) || (!this.white && + y - this.matrixPosition.y == 1)) { + this.firstTurn = false; + return true; + } + if (this.firstTurn && ((this.white && y - this.matrixPosition.y == -2) || + (!this.white && y - this.matrixPosition.y == 2))) { + if (this.moveThroughPieces(x, y, board)) { + return false; + } + + this.firstTurn = false; + return true; + } + return false; + } + + + generateMoves(board) { + var moves = []; + + for (var i = -1; i < 2; i += 2) { + var x = this.matrixPosition.x + i; + if (this.white) { + var y = this.matrixPosition.y - 1; + } else { + var y = this.matrixPosition.y + 1; + } + var attacking = board.getPieceAt(x, y); + if (attacking) { + if (!this.attackingAllies(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + + var x = this.matrixPosition.x; + if (this.white) { + var y = this.matrixPosition.y - 1; + } else { + var y = this.matrixPosition.y + 1; + } + if (!board.isPieceAt(x, y) && this.withinBounds(x, y)) { + moves.push(createVector(x, y)); + } + + if (this.firstTurn) { + + if (this.white) { + var y = this.matrixPosition.y - 2; + } else { + var y = this.matrixPosition.y + 2; + } + if (!board.isPieceAt(x, y) && this.withinBounds(x, y)) { + if (!this.moveThroughPieces(x, y, board)) { + moves.push(createVector(x, y)); + } + } + } + //print("pawn", moves); + return moves; + } + clone() { + var clone = new Pawn(this.matrixPosition.x, this.matrixPosition.y, this + .white); + clone.taken = this.taken; + clone.firstTurn = this.firstTurn; + return clone; + } + + move(x, y, board) { + var attacking = board.getPieceAt(x, y); + if (attacking != null) { + attacking.taken = true; + } + this.matrixPosition = createVector(x, y); + this.pixelPosition = createVector(x * tileSize + tileSize / 2, y * + tileSize + tileSize / 2); + this.firstTurn = false; + } +} diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_01.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_01.png new file mode 100644 index 000000000..328aa9284 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_01.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_02.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_02.png new file mode 100644 index 000000000..15f28b3bd Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_02.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_03.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_03.png new file mode 100644 index 000000000..600610a44 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_03.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_04.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_04.png new file mode 100644 index 000000000..61d0431b1 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_04.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_05.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_05.png new file mode 100644 index 000000000..dafb1494f Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_05.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_06.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_06.png new file mode 100644 index 000000000..afd685dcb Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_06.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_07.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_07.png new file mode 100644 index 000000000..23cdf6f4b Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_07.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_08.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_08.png new file mode 100644 index 000000000..e7dbbbe9d Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_08.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_09.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_09.png new file mode 100644 index 000000000..bc35adce8 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_09.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_10.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_10.png new file mode 100644 index 000000000..3892a0304 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_10.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_11.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_11.png new file mode 100644 index 000000000..2835bb45f Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_11.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_12.png b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_12.png new file mode 100644 index 000000000..21f36d903 Binary files /dev/null and b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/assets/2000px-Chess_Pieces_Sprite_12.png differ diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/index.html b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/index.html new file mode 100644 index 000000000..57917e79e --- /dev/null +++ b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/index.html @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Sakalya100_Day5/Chess-AI-gh-pages/Chess/libraries/p5.dom.js b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/libraries/p5.dom.js new file mode 100644 index 000000000..561d30066 --- /dev/null +++ b/Sakalya100_Day5/Chess-AI-gh-pages/Chess/libraries/p5.dom.js @@ -0,0 +1,2190 @@ +/*! p5.dom.js v0.3.2 March 25, 2017 */ +/** + *

The web is much more than just canvas and p5.dom makes it easy to interact + * with other HTML5 objects, including text, hyperlink, image, input, video, + * audio, and webcam.

+ *

There is a set of creation methods, DOM manipulation methods, and + * an extended p5.Element that supports a range of HTML elements. See the + * + * beyond the canvas tutorial for a full overview of how this addon works. + * + *

Methods and properties shown in black are part of the p5.js core, items in + * blue are part of the p5.dom library. You will need to include an extra file + * in order to access the blue functions. See the + * using a library + * section for information on how to include this library. p5.dom comes with + * p5 complete or you can download the single file + * + * here.

+ *

See tutorial: beyond the canvas + * for more info on how to use this libary. + * + * @module p5.dom + * @submodule p5.dom + * @for p5.dom + * @main + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) + define('p5.dom', ['p5'], function (p5) { (factory(p5));}); + else if (typeof exports === 'object') + factory(require('../p5')); + else + factory(root['p5']); +}(this, function (p5) { + +// ============================================================================= +// p5 additions +// ============================================================================= + + /** + * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' + * prefixes to specify an ID or class respectively, and none for a tag) and returns it as + * a p5.Element. If a class or tag name is given with more than 1 element, + * only the first element will be returned. + * The DOM node itself can be accessed with .elt. + * Returns null if none found. You can also specify a container to search within. + * + * @method select + * @param {String} name id, class, or tag name of element to search for + * @param {String} [container] id, p5.Element, or HTML element to search within + * @return {Object|p5.Element|Null} p5.Element containing node found + * @example + *

+ * function setup() { + * createCanvas(100,100); + * //translates canvas 50px down + * select('canvas').position(100, 100); + * } + *
+ *
+ * // these are all valid calls to select() + * var a = select('#moo'); + * var b = select('#blah', '#myContainer'); + * var c = select('#foo', b); + * var d = document.getElementById('beep'); + * var e = select('p', d); + *
+ * + */ + p5.prototype.select = function (e, p) { + var res = null; + var container = getContainer(p); + if (e[0] === '.'){ + e = e.slice(1); + res = container.getElementsByClassName(e); + if (res.length) { + res = res[0]; + } else { + res = null; + } + }else if (e[0] === '#'){ + e = e.slice(1); + res = container.getElementById(e); + }else { + res = container.getElementsByTagName(e); + if (res.length) { + res = res[0]; + } else { + res = null; + } + } + if (res) { + return wrapElement(res); + } else { + return null; + } + }; + + /** + * Searches the page for elements with the given class or tag name (using the '.' prefix + * to specify a class and no prefix for a tag) and returns them as p5.Elements + * in an array. + * The DOM node itself can be accessed with .elt. + * Returns an empty array if none found. + * You can also specify a container to search within. + * + * @method selectAll + * @param {String} name class or tag name of elements to search for + * @param {String} [container] id, p5.Element, or HTML element to search within + * @return {Array} Array of p5.Elements containing nodes found + * @example + *
+ * function setup() { + * createButton('btn'); + * createButton('2nd btn'); + * createButton('3rd btn'); + * var buttons = selectAll('button'); + * + * for (var i = 0; i < buttons.length; i++){ + * buttons[i].size(100,100); + * } + * } + *
+ *
+ * // these are all valid calls to selectAll() + * var a = selectAll('.moo'); + * var b = selectAll('div'); + * var c = selectAll('button', '#myContainer'); + * var d = select('#container'); + * var e = selectAll('p', d); + * var f = document.getElementById('beep'); + * var g = select('.blah', f); + *
+ * + */ + p5.prototype.selectAll = function (e, p) { + var arr = []; + var res; + var container = getContainer(p); + if (e[0] === '.'){ + e = e.slice(1); + res = container.getElementsByClassName(e); + } else { + res = container.getElementsByTagName(e); + } + if (res) { + for (var j = 0; j < res.length; j++) { + var obj = wrapElement(res[j]); + arr.push(obj); + } + } + return arr; + }; + + /** + * Helper function for select and selectAll + */ + function getContainer(p) { + var container = document; + if (typeof p === 'string' && p[0] === '#'){ + p = p.slice(1); + container = document.getElementById(p) || document; + } else if (p instanceof p5.Element){ + container = p.elt; + } else if (p instanceof HTMLElement){ + container = p; + } + return container; + } + + /** + * Helper function for getElement and getElements. + */ + function wrapElement(elt) { + if(elt.tagName === "INPUT" && elt.type === "checkbox") { + var converted = new p5.Element(elt); + converted.checked = function(){ + if (arguments.length === 0){ + return this.elt.checked; + } else if(arguments[0]) { + this.elt.checked = true; + } else { + this.elt.checked = false; + } + return this; + }; + return converted; + } else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { + return new p5.MediaElement(elt); + } else { + return new p5.Element(elt); + } + } + + /** + * Removes all elements created by p5, except any canvas / graphics + * elements created by createCanvas or createGraphics. + * Event handlers are removed, and element is removed from the DOM. + * @method removeElements + * @example + *
+ * function setup() { + * createCanvas(100, 100); + * createDiv('this is some text'); + * createP('this is a paragraph'); + * } + * function mousePressed() { + * removeElements(); // this will remove the div and p, not canvas + * } + *
+ * + */ + p5.prototype.removeElements = function (e) { + for (var i=0; i + * var myDiv; + * function setup() { + * myDiv = createDiv('this is some text'); + * } + * + */ + + /** + * Creates a <p></p> element in the DOM with given inner HTML. Used + * for paragraph length text. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createP + * @param {String} html inner HTML for element created + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var myP; + * function setup() { + * myP = createP('this is some text'); + * } + *
+ */ + + /** + * Creates a <span></span> element in the DOM with given inner HTML. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createSpan + * @param {String} html inner HTML for element created + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var mySpan; + * function setup() { + * mySpan = createSpan('this is some text'); + * } + *
+ */ + var tags = ['div', 'p', 'span']; + tags.forEach(function(tag) { + var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); + p5.prototype[method] = function(html) { + var elt = document.createElement(tag); + elt.innerHTML = typeof html === undefined ? "" : html; + return addElement(elt, this); + } + }); + + /** + * Creates an <img> element in the DOM with given src and + * alternate text. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createImg + * @param {String} src src path or url for image + * @param {String} [alt] alternate text to be used if image does not load + * @param {Function} [successCallback] callback to be called once image data is loaded + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var img; + * function setup() { + * img = createImg('http://p5js.org/img/asterisk-01.png'); + * } + *
+ */ + p5.prototype.createImg = function() { + var elt = document.createElement('img'); + var args = arguments; + var self; + var setAttrs = function(){ + self.width = elt.offsetWidth || elt.width; + self.height = elt.offsetHeight || elt.height; + if (args.length > 1 && typeof args[1] === 'function'){ + self.fn = args[1]; + self.fn(); + }else if (args.length > 1 && typeof args[2] === 'function'){ + self.fn = args[2]; + self.fn(); + } + }; + elt.src = args[0]; + if (args.length > 1 && typeof args[1] === 'string'){ + elt.alt = args[1]; + } + elt.onload = function(){ + setAttrs(); + } + self = addElement(elt, this); + return self; + }; + + /** + * Creates an <a></a> element in the DOM for including a hyperlink. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createA + * @param {String} href url of page to link to + * @param {String} html inner html of link element to display + * @param {String} [target] target where new link should open, + * could be _blank, _self, _parent, _top. + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var myLink; + * function setup() { + * myLink = createA('http://p5js.org/', 'this is a link'); + * } + *
+ */ + p5.prototype.createA = function(href, html, target) { + var elt = document.createElement('a'); + elt.href = href; + elt.innerHTML = html; + if (target) elt.target = target; + return addElement(elt, this); + }; + + /** INPUT **/ + + + /** + * Creates a slider <input></input> element in the DOM. + * Use .size() to set the display length of the slider. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createSlider + * @param {Number} min minimum value of the slider + * @param {Number} max maximum value of the slider + * @param {Number} [value] default value of the slider + * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var slider; + * function setup() { + * slider = createSlider(0, 255, 100); + * slider.position(10, 10); + * slider.style('width', '80px'); + * } + * + * function draw() { + * var val = slider.value(); + * background(val); + * } + *
+ * + *
+ * var slider; + * function setup() { + * colorMode(HSB); + * slider = createSlider(0, 360, 60, 40); + * slider.position(10, 10); + * slider.style('width', '80px'); + * } + * + * function draw() { + * var val = slider.value(); + * background(val, 100, 100, 1); + * } + *
+ */ + p5.prototype.createSlider = function(min, max, value, step) { + var elt = document.createElement('input'); + elt.type = 'range'; + elt.min = min; + elt.max = max; + if (step === 0) { + elt.step = .000000000000000001; // smallest valid step + } else if (step) { + elt.step = step; + } + if (typeof(value) === "number") elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates a <button></button> element in the DOM. + * Use .size() to set the display size of the button. + * Use .mousePressed() to specify behavior on press. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createButton + * @param {String} label label displayed on the button + * @param {String} [value] value of the button + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var button; + * function setup() { + * createCanvas(100, 100); + * background(0); + * button = createButton('click me'); + * button.position(19, 19); + * button.mousePressed(changeBG); + * } + * + * function changeBG() { + * var val = random(255); + * background(val); + * } + *
+ */ + p5.prototype.createButton = function(label, value) { + var elt = document.createElement('button'); + elt.innerHTML = label; + elt.value = value; + if (value) elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates a checkbox <input></input> element in the DOM. + * Calling .checked() on a checkbox returns if it is checked or not + * + * @method createCheckbox + * @param {String} [label] label displayed after checkbox + * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var checkbox; + * + * function setup() { + * checkbox = createCheckbox('label', false); + * checkbox.changed(myCheckedEvent); + * } + * + * function myCheckedEvent() { + * if (this.checked()) { + * console.log("Checking!"); + * } else { + * console.log("Unchecking!"); + * } + * } + *
+ */ + p5.prototype.createCheckbox = function() { + var elt = document.createElement('div'); + var checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + elt.appendChild(checkbox); + //checkbox must be wrapped in p5.Element before label so that label appears after + var self = addElement(elt, this); + self.checked = function(){ + var cb = self.elt.getElementsByTagName('input')[0]; + if (cb) { + if (arguments.length === 0){ + return cb.checked; + }else if(arguments[0]){ + cb.checked = true; + }else{ + cb.checked = false; + } + } + return self; + }; + this.value = function(val){ + self.value = val; + return this; + }; + if (arguments[0]){ + var ran = Math.random().toString(36).slice(2); + var label = document.createElement('label'); + checkbox.setAttribute('id', ran); + label.htmlFor = ran; + self.value(arguments[0]); + label.appendChild(document.createTextNode(arguments[0])); + elt.appendChild(label); + } + if (arguments[1]){ + checkbox.checked = true; + } + return self; + }; + + /** + * Creates a dropdown menu <select></select> element in the DOM. + * @method createSelect + * @param {boolean} [multiple] true if dropdown should support multiple selections + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var sel; + * + * function setup() { + * textAlign(CENTER); + * background(200); + * sel = createSelect(); + * sel.position(10, 10); + * sel.option('pear'); + * sel.option('kiwi'); + * sel.option('grape'); + * sel.changed(mySelectEvent); + * } + * + * function mySelectEvent() { + * var item = sel.value(); + * background(200); + * text("it's a "+item+"!", 50, 50); + * } + *
+ */ + p5.prototype.createSelect = function(mult) { + var elt = document.createElement('select'); + if (mult){ + elt.setAttribute('multiple', 'true'); + } + var self = addElement(elt, this); + self.option = function(name, value){ + var opt = document.createElement('option'); + opt.innerHTML = name; + if (arguments.length > 1) + opt.value = value; + else + opt.value = name; + elt.appendChild(opt); + }; + self.selected = function(value){ + var arr = []; + if (arguments.length > 0){ + for (var i = 0; i < this.elt.length; i++){ + if (value.toString() === this.elt[i].value){ + this.elt.selectedIndex = i; + } + } + return this; + }else{ + if (mult){ + for (var i = 0; i < this.elt.selectedOptions.length; i++){ + arr.push(this.elt.selectedOptions[i].value); + } + return arr; + }else{ + return this.elt.value; + } + } + }; + return self; + }; + + /** + * Creates a radio button <input></input> element in the DOM. + * The .option() method can be used to set options for the radio after it is + * created. The .value() method will return the currently selected option. + * + * @method createRadio + * @param {String} [divId] the id and name of the created div and input field respectively + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * var radio; + * + * function setup() { + * radio = createRadio(); + * radio.option("black"); + * radio.option("white"); + * radio.option("gray"); + * radio.style('width', '60px'); + * textAlign(CENTER); + * fill(255, 0, 0); + * } + * + * function draw() { + * var val = radio.value(); + * background(val); + * text(val, width/2, height/2); + * } + *
+ *
+ * var radio; + * + * function setup() { + * radio = createRadio(); + * radio.option('apple', 1); + * radio.option('bread', 2); + * radio.option('juice', 3); + * radio.style('width', '60px'); + * textAlign(CENTER); + * } + * + * function draw() { + * background(200); + * var val = radio.value(); + * if (val) { + * text('item cost is $'+val, width/2, height/2); + * } + * } + *
+ */ + p5.prototype.createRadio = function() { + var radios = document.querySelectorAll("input[type=radio]"); + var count = 0; + if(radios.length > 1){ + var length = radios.length; + var prev=radios[0].name; + var current = radios[1].name; + count = 1; + for(var i = 1; i < length; i++) { + current = radios[i].name; + if(prev != current){ + count++; + } + prev = current; + } + } + else if (radios.length == 1){ + count = 1; + } + var elt = document.createElement('div'); + var self = addElement(elt, this); + var times = -1; + self.option = function(name, value){ + var opt = document.createElement('input'); + opt.type = 'radio'; + opt.innerHTML = name; + if (arguments.length > 1) + opt.value = value; + else + opt.value = name; + opt.setAttribute('name',"defaultradio"+count); + elt.appendChild(opt); + if (name){ + times++; + var ran = Math.random().toString(36).slice(2); + var label = document.createElement('label'); + opt.setAttribute('id', "defaultradio"+count+"-"+times); + label.htmlFor = "defaultradio"+count+"-"+times; + label.appendChild(document.createTextNode(name)); + elt.appendChild(label); + } + return opt; + }; + self.selected = function(){ + var length = this.elt.childNodes.length; + if(arguments.length == 1) { + for (var i = 0; i < length; i+=2){ + if(this.elt.childNodes[i].value == arguments[0]) + this.elt.childNodes[i].checked = true; + } + return this; + } else { + for (var i = 0; i < length; i+=2){ + if(this.elt.childNodes[i].checked == true) + return this.elt.childNodes[i].value; + } + } + }; + self.value = function(){ + var length = this.elt.childNodes.length; + if(arguments.length == 1) { + for (var i = 0; i < length; i+=2){ + if(this.elt.childNodes[i].value == arguments[0]) + this.elt.childNodes[i].checked = true; + } + return this; + } else { + for (var i = 0; i < length; i+=2){ + if(this.elt.childNodes[i].checked == true) + return this.elt.childNodes[i].value; + } + return ""; + } + }; + return self + }; + + /** + * Creates an <input></input> element in the DOM for text input. + * Use .size() to set the display length of the box. + * Appends to the container node if one is specified, otherwise + * appends to body. + * + * @method createInput + * @param {Number} [value] default value of the input box + * @param {String} [type] type of text, ie text, password etc. Defaults to text + * @return {Object|p5.Element} pointer to p5.Element holding created node + * @example + *
+ * function setup(){ + * var inp = createInput(''); + * inp.input(myInputEvent); + * } + * + * function myInputEvent(){ + * console.log('you are typing: ', this.value()); + * } + * + *
+ */ + p5.prototype.createInput = function(value, type) { + var elt = document.createElement('input'); + elt.type = type ? type : 'text'; + if (value) elt.value = value; + return addElement(elt, this); + }; + + /** + * Creates an <input></input> element in the DOM of type 'file'. + * This allows users to select local files for use in a sketch. + * + * @method createFileInput + * @param {Function} [callback] callback function for when a file loaded + * @param {String} [multiple] optional to allow multiple files selected + * @return {Object|p5.Element} pointer to p5.Element holding created DOM element + * @example + * var input; + * var img; + * + * function setup() { + * input = createFileInput(handleFile); + * input.position(0, 0); + * } + * + * function draw() { + * if (img) { + * image(img, 0, 0, width, height); + * } + * } + * + * function handleFile(file) { + * print(file); + * if (file.type === 'image') { + * img = createImg(file.data); + * img.hide(); + * } + * } + */ + p5.prototype.createFileInput = function(callback, multiple) { + + // Is the file stuff supported? + if (window.File && window.FileReader && window.FileList && window.Blob) { + // Yup, we're ok and make an input file selector + var elt = document.createElement('input'); + elt.type = 'file'; + + // If we get a second argument that evaluates to true + // then we are looking for multiple files + if (multiple) { + // Anything gets the job done + elt.multiple = 'multiple'; + } + + // Function to handle when a file is selected + // We're simplifying life and assuming that we always + // want to load every selected file + function handleFileSelect(evt) { + // These are the files + var files = evt.target.files; + // Load each one and trigger a callback + for (var i = 0; i < files.length; i++) { + var f = files[i]; + var reader = new FileReader(); + function makeLoader(theFile) { + // Making a p5.File object + var p5file = new p5.File(theFile); + return function(e) { + p5file.data = e.target.result; + callback(p5file); + }; + }; + reader.onload = makeLoader(f); + + // Text or data? + // This should likely be improved + if (f.type.indexOf('text') > -1) { + reader.readAsText(f); + } else { + reader.readAsDataURL(f); + } + } + } + + // Now let's handle when a file was selected + elt.addEventListener('change', handleFileSelect, false); + return addElement(elt, this); + } else { + console.log('The File APIs are not fully supported in this browser. Cannot create element.'); + } + }; + + + /** VIDEO STUFF **/ + + function createMedia(pInst, type, src, callback) { + var elt = document.createElement(type); + + // allow src to be empty + var src = src || ''; + if (typeof src === 'string') { + src = [src]; + } + for (var i=0; i