-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSOVIAASSISTANT.py
3191 lines (2815 loc) · 179 KB
/
SOVIAASSISTANT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from SOVIA import takecommand
from tkinter import *
import PIL.Image, PIL.ImageTk
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import random
import smtplib
import pyautogui
import psutil
import pyjokes
import requests
import json
import subprocess
import wolframalpha
import snakeGame
import pygame #Game library
from pygame.locals import * #For useful variables..for eg QUIT
import copy #Library used to make exact copies of lists.
import pickle #Library used to store dictionaries in a text file and read them from text files.
import random #Used for making random selections
from collections import defaultdict #Used for giving dictionary values default data types.
from collections import Counter #For counting elements in a list effieciently.
import threading #To allow for AI to think simultaneously while the GUI is coloring the board.
import time
import cv2
import numpy as np
import joblib
import pygame
from sys import exit
# from random import randrange, choice
import os
import tkinter as tk
#import Roman
#numbers = {'hundred': 100, 'thousand': 1000, 'lakh': 100000}
#a = {'name': 'your email'}
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
# Initialize the converter
converter = pyttsx3.init()
# Set properties before adding
# Things to say
# Sets speed percent
# Can be more than 100
# converter.setProperty('rate', 140)
# Set volume 0-1
converter.setProperty('volume', 1)
window = Tk()
#window.iconbitmap(r'Aicon.ico')
global var
global var1
var = StringVar()
var1 = StringVar()
# Funtion which makes the Assistant speak
def speak(audio):
engine.say(audio)
engine.runAndWait()
# Function to send Emails
def sendemail(to, content):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('email id', 'password') # email id - use any email id whose security/privacy is off
server.sendmail('email id', to, content)
server.close()
# Function for greetings
def wishme():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour <= 12:
var.set("Good Morning Sir")
window.update()
speak("Good Morning Sir")
elif hour >= 12 and hour <= 17:
var.set("Good Afternoon Sir")
window.update()
speak("Good Afternoon Sir")
else:
var.set("Good Evening Sir")
window.update()
speak("Good Evening Sir")
var.set("SOVIA at your service, How Can I help you?")
window.update()
speak("SOVIA at your service, How Can I help you?") # BotName - Give a name to your assistant
# Function to take commands form microphone
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
var.set("Listening...")
window.update()
print("Listening...")
r.pause_threshold = 1
r.energy_threshold = 4000
audio = r.listen(source)
try:
var.set("Recognizing...")
window.update()
print("Recognizing")
query = r.recognize_google(audio, language='en-in')
except Exception as e:
return "None"
var1.set(query)
window.update()
return query
# function to take screenshot
def screenshot():
img=pyautogui.screenshot()
img.save("D:\Assistant\ss.png")
# funtion to tell about CPU percentage
def cpu():
usage=str(psutil.cpu_percent())
var.set("CPU is at" + usage)
window.update()
speak("CPU is at" + usage)
# function to tell battery percentage
def battery():
battery=psutil.sensors_battery()
var.set(battery.percent)
window.update()
speak(battery.percent)
#var.set(battery.percent)
#window.update()
#speak(battery.percent)
#var.set("percent")
#window.update()
speak("percent")
# Function to tell joke
def jokes():
var.set(pyjokes.get_joke())#here is the joke
window.update()
speak(pyjokes.get_joke())
# Function to tell news
def news():
url = (f"http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=e38e33aa03d448068b70c4c1c2fed2f4")
response = requests.get(url)
t = response.text
my_json = json.loads(t)
var.set("News for the day are")
window.update()
speak("News for the day are")
for i in range(0, 5):
speak(my_json['articles'][i]['title'])
speak("the description of above news is" + my_json['articles'][i]['description'])
# Function to tell features
def features():
f=['Tell time','Tell date',
'Tell a Joke','Tell a Current weather report and weather forecast for next day',
'Search things in Wikipedia',
'Send Emails through Gmail','Search in google chrome',
'Shutdown the System','Logout the System','Restart the System',
'Play songs','Switch Songs','Remember things',
'Tell what you told me to remember','Take Screenshots',
'Tell about CPU status','Tell battery Percentage',
'Tell News','Open System application','show the three types of prediction-addmission, loan and spam email checker','cilck the photo',
'record the video']
for i in f:
print(i)
for i in f:
var.set(i)
window.update()
speak(i)
def forecast(City):
city_api_endpoint = "http://api.openweathermap.org/data/2.5/forecast?q="
join_key = "&appid=" + "8e3aff6cd41e65082ba7285a185f00c4"
units = "&units=metric"
city_forecast = city_api_endpoint + City + join_key + units
forecast_json = requests.get(city_forecast).json()
if forecast_json["cod"] != "404":
forecast = forecast_json['list'][6]['main']
forecast_temperature = forecast['temp']
forecast_pressure = forecast['pressure']
forecast_humidity = forecast['humidity']
forecast_main = forecast_json['list'][0]['weather'][0]['main']
text1 = str("Tommorrow's Temperature is " + str(forecast_temperature) + "degree celsius" +
"\n atmospheric pressure is" + str(forecast_pressure) + "hectopascal" + "humidity is "
+ str(forecast_humidity) + "percent" + "with " + str(forecast_main))
var.set(text1)
window.update()
speak(text1)
def weather():
api_key = "93654f3dc80dd40be139ca13704330c4"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
var.set("Please tell me your current city")
window.update()
speak("Please tell me your current city")
# Give city name
city_name = takecommand().lower()
units = "&units=metric"
# complete_url variable to store complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name+units
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
current_temperature = y["temp"]
current_temperature = current_temperature-273.15
current_temperature = ('%.2f' % current_temperature)
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
text=str(" Temperature " +
str(current_temperature) +"degree celsius"+
"\n atmospheric pressure is" +
str(current_pressure) +"hectopascal"
"\n humidity is " +
str(current_humidiy) +"percent"+
"with " +
str(weather_description))
var.set(text)
window.update()
speak(text)
var.set("Do you want to know weather forecast for tommorrow??")
window.update()
speak("Do you want to know weather forecast for tommorrow??")
cmd=takecommand().lower()
if "yes" or "weather forecast" in cmd:
City = city_name
forecast(City)
elif "no"or'9' in cmd:
var.set("ok")
window.update()
speak("ok")
else:
print(" City Not Found ")
def Jarvis():
#btn2['state'] = 'disabled'
btn1.configure(bg='orange')
wishme()
while True:
btn1.configure(bg='orange')
query = takeCommand().lower()
print(query)
if 'exit' in query:
var.set("Bye Sir have a great day")
btn1.configure(bg='#5C85FB')
#btn2['state'] = 'normal'
window.update()
speak("Bye Sir have a great day")
break
elif "offline" in query:
speak("ok Sir have a great day")
quit()
elif 'wikipedia' in query:
if 'open wikipedia' in query:
webbrowser.open('wikipedia.com')
else:
try:
#var.set("Sure sir let me check..")
#window.update()
speak("Sure sir let me check..")
query = query.replace("according to wikipedia", "")
results = wikipedia.summary(query, sentences=2)
#var.set("Sure sir let me check..")
#window.update()
speak("According to wikipedia")
var.set(results)
window.update()
speak(results)
except Exception as e:
var.set("sorry sir could not find any results")
window.update()
speak("sorry sir could not find any results")
elif 'open youtube' in query:
var.set('opening Youtube')
window.update()
speak('opening Youtube')
webbrowser.open("youtube.com")
elif 'open course era' in query:
var.set('opening course era')
window.update()
speak('opening course era')
webbrowser.open("coursera.com")
elif 'open google' in query:
var.set('opening google...')
window.update()
speak('opening google')
webbrowser.open("google.com")
elif 'hello' in query:
var.set("Hello sir")
window.update()
speak("Hello sir")
elif 'open stackoverflow' in query:
var.set('opening stackoverflow')
window.update()
speak('opening stackoverflow')
webbrowser.open('stackoverflow.com')
elif ('play music' in query):
var.set('Here are your favorites')
window.update()
speak('Here are your favorites')
music_dir = "D:/Music" # Enter the Path of Music Library
songs = os.listdir(music_dir)
n = random.randint(0, 27)
os.startfile(os.path.join(music_dir, songs[n]))
elif "play another song" in query:
var.set("Ok sir")
window.update()
speak("Ok sir")
music_dir = "D:/Music" # Enter the Path of Music Library
songs = os.listdir(music_dir)
n = random.randint(0, 27)
os.startfile(os.path.join(music_dir, songs[n]))
elif 'the time' in query:
strtime = datetime.datetime.now().strftime("%H:%M:%S")
var.set("sir the time is %s" % strtime)
window.update()
speak("sir the time is %s" % strtime)
elif 'the date' in query:
strdate = datetime.datetime.today().strftime("%d %m %y")
var.set("sir today's date is %s" % strdate)
window.update()
speak("sir today's date is %s" % strdate)
elif 'thank you' in query:
var.set("Welcome sir")
window.update()
speak("Welcome sir")
elif 'can you do for me' in query:
var.set("I can do multiple tasks for you Ma'am. tell me whatever you want to perform sir")
window.update()
speak("I can do multiple tasks for you Ma'am. tell me whatever you want to perform sir")
elif 'your name' in query:
var.set("Myself Sovia Sir")
window.update()
speak("Myself Sovia Sir")
elif 'say hello' in query:
var.set('Hello Everyone! My self SOVIA')
window.update()
speak('Hello Everyone! My self SOVIA')
elif 'open pycharm' in query:
var.set("Opening Pycharm")
window.update()
speak("Opening Pycharm")
path = "C:\\Program Files\\JetBrains\\PyCharm Community Edition 2020.1.1\\bin\\pycharm64.exe" # Enter the correct Path according to your system
os.startfile(path)
elif 'open chrome' in query:
var.set("Opening Google Chrome")
window.update()
speak("Opening Google Chrome")
path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" # Enter the correct Path according to your system
os.startfile(path)
elif 'admission' in query:
var.set('opening the Addmission Prediction')
window.update()
speak('opening the Addmission Prediction')
webbrowser.open("https://the-predictor-mic.herokuapp.com/admission/")
elif 'loan' in query:
var.set('opening the Loan Prediction')
window.update()
speak('opening the Loan Prediction')
webbrowser.open("https://the-predictor-mic.herokuapp.com/loan/")
elif 'spam' in query:
var.set('open the Spam Email Checker')
window.update()
speak('opening the Spam Email Checker')
webbrowser.open("https://the-predictor-mic.herokuapp.com/spam/")
elif 'email' in query:
try:
var.set("Please enter the recevers address")
window.update()
speak("Please enter the recevers address")
def send_mail():
son=e.get()
import yagmail
to = son
var.set("what is the subject of the mail")
window.update()
speak("what is the subject of the mail")
h = takecommand()
var.set("what should I say...")
window.update()
speak("what should I say...")
k = takecommand()
yag = yagmail.SMTP('<<email>>', '<<password>>')
yag.send(to, h, k)
speak("Email sent successfully")
master = tk.Tk()
tk.Label(master, text="Email Address").grid(row=2,pady=5)
e = tk.Entry(master,width=35)
e.grid(row=2, column=1,pady=5)
tk.Button(master, text="Enter", command=send_mail).grid(row=3, column=1, sticky=tk.W, pady=4)
master.geometry("280x200+0+0")
tk.mainloop()
#send_mail(to,subject,content)
#var.set("Email sent successfully")
#window.update()
except Exception as e:
print(e)
var.set("Sorry Sir! I was not able to send this email")
window.update()
speak('Sorry Sir! I was not able to send this email')
elif 'search' in query:
var.set("What should I search for")
window.update()
speak("What should I search for")
chromepath="C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
search=takecommand().lower()
webbrowser.get(chromepath).open_new_tab(search+".com")
elif 'logout' in query:
os.system("shutdown - l") #for logout
elif 'shutdown' in query:
os.system("shutdown /s /t 1") #for shutdown
elif 'restart' in query:
os.system("shutdown /r /t 1") #for restart
elif "open python" in query:
var.set("Opening Python IdlE")
window.update()
speak('opening python IdlE')
os.startfile('C:\\Users\\user\\python37\\python.exe') # Enter the correct Path according to your system
# to make assistant to remember something
elif "remember that" in query:
var.set("What should I remember")
window.update()
speak("What should I remember")
data=takecommand()
var.set("you said me to remember" + data)
window.update()
speak("you said me to remember" + data)
remember=open("data.txt","w")
remember.write(data)
remember.close()
# make assistant speak what you told to remember
elif 'what i told you to remember' in query:
remember=open("data.txt","r")
var.set("you said me to remember that" + remember.read())
window.update()
speak("you said me to remember that" + remember.read())
elif 'screenshot' in query:
screenshot()
var.set("Screenshot taken")
window.update()
speak("Screenshot taken")
elif 'cpu' in query:
cpu()
elif 'battery' in query:
battery()
elif 'joke' in query:
jokes()
elif 'news' in query:
news()
# to open system apps
elif 'wordpad' in query:
var.set("Opening Wordpad")
window.update()
speak("Opening Wordpad")
subprocess.Popen('C:\\Windows\\System32\\write.exe')
elif 'notepad' in query:
var.set("Opening notepad")
window.update()
speak("Opening notepad")
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
elif 'calculator' in query:
var.set("Opening calculator")
window.update()
speak("Opening calculator")
subprocess.Popen('C:\\Windows\\System32\\calc.exe')
elif 'word' in query:
var.set("Opening word")
window.update()
speak("Opening word")
subprocess.Popen("C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE")
elif 'powerpoint' in query:
var.set("Opening powerpoint")
window.update()
speak("Opening powerpoint")
subprocess.Popen("C:\\Program Files\\Microsoft Office\\root\\Office16\\POWERPNT.EXE")
elif 'excel' in query:
var.set("Opening excel")
window.update()
speak("Opening excel")
subprocess.Popen("C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE")
elif 'photoshop' in query:
var.set("Opening photoshop")
window.update()
speak("Opening photoshop")
subprocess.Popen("C:\\Program Files (x86)\\Adobe\\Photoshop 7.0\\Photoshop.exe")
elif 'paint' in query:
var.set("Opening Paint")
window.update()
speak("Opening Paint")
subprocess.Popen("C:\\Windows\\System32\\mspaint.exe")
elif 'your feature' in query:
var.set("I can...")
window.update()
speak("I can...")
features()
elif 'what' in query:
# answer()
question =query
app_id = '7WP4V3-7T4GPQX6EQ'
client = wolframalpha.Client(app_id)
res = client.query(question)
answer = next(res.results).text
print(answer)
var.set(answer)
window.update()
speak(answer)
elif 'weather' in query:
weather()
elif 'click photo' in query:
stream = cv2.VideoCapture(0)
grabbed, frame = stream.read()
if grabbed:
cv2.imshow('pic', frame)
cv2.imwrite('pic.jpg', frame)
stream.release()
elif 'record video' in query:
cap = cv2.VideoCapture(0)
out = cv2.VideoWriter('output.avi', -1, 20.0, (640, 480))
while (cap.isOpened()):
ret, frame = cap.read()
if ret:
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
elif 'game' in query:
speak("You can play three types of game that is key operated games...in which I have snake game, voice based games....in which I have Chess... and motion based games....in which I have Dinosaur Game. So, which one you would like to play..One....Two or Three ")
query=takecommand().lower()
#snake Game
#-------------------------------------------------------
if 'One' or '1' in query:
speak("Do you want to play snake game")
inp=takecommand().lower()
if 'yes' in inp:
snakeGame.snakegame()
#Chess Game
#--------------------------------------------------------
#*************************************************************************************************************************************#
#*************************************************************************************************************************************#
#*************************************************************************************************************************************#
#*************************************************************************************************************************************#
if 'Two' or '2' in query:
speak("Do you want to play chess")
inp=takecommand().lower()
if 'yes' in inp:
#Import dependencies:
# import pygame #Game library
# from pygame.locals import * #For useful variables..for eg QUIT
# import copy #Library used to make exact copies of lists.
# import pickle #Library used to store dictionaries in a text file and read them from text files.
# import random #Used for making random selections
# from collections import defaultdict #Used for giving dictionary values default data types.
# from collections import Counter #For counting elements in a list effieciently.
# import threading #To allow for AI to think simultaneously while the GUI is coloring the board.
# import time
# import speech_recognition as sr
play_sound=True
class GamePosition:
def __init__(self,board,player,castling_rights,EnP_Target,HMC,history = {}):
# Making an object of Commands Class
self.c=Commands()
# A 2D array containing information about piece postitions. Check main function to see an example of such
# a representation.
self.board = board
# Stores 0 or 1. If white to play, equals 0. If black to play, stores 1.
self.player = player
# A list that contains castling rights for white and black. Each castling right is a list that contains right
# to castle kingside and queenside.
# Stores the coordinates of a square that can be targeted by en passant capture.
self.EnP = EnP_Target
self.castling = castling_rights
# Half move clock. Stores the number of irreversible moves made so far, in order to help
# detect draw by 50 moves without any capture or pawn movement.
self.HMC = HMC
# A dictionary that stores as key a position (hashed) and the value of each of
# these keys represents the number of times each of these positions was repeated in order for this
# position to be reached.
self.history = history
def getboard(self):
return self.board
def setboard(self,board):
self.board = board
def getplayer(self):
return self.player
def setplayer(self,player):
self.player = player
def getCastleRights(self):
return self.castling
def setCastleRights(self,castling_rights):
self.castling = castling_rights
def getEnP(self):
return self.EnP
def setEnP(self, EnP_Target):
self.EnP = EnP_Target
def getHMC(self):
return self.HMC
def setHMC(self,HMC):
self.HMC = HMC
def checkRepition(self):
# Returns True if any of of the values in the history dictionary is greater than 3.
# This would mean a position had been repeated at least thrice in order to reach the
# current position in this game.
return any(value>=3 for value in self.history.values())
def addtoHistory(self,position):
# Generate a unique key out of the current position:
key = self.c.pos2key(position)
#Add it to the history dictionary.
self.history[key] = self.history.get(key,0) + 1
def gethistory(self):
return self.history
def clone(self):
# This method returns another instance of the current object with exactly the same
# parameters but independent of the current object.
clone = GamePosition(copy.deepcopy(self.board), # Independent copy
self.player,
copy.deepcopy(self.castling), # Independent copy
self.EnP,
self.HMC)
return clone
class Shades:
"""
It is used to shade the board
"""
def __init__(self,image,coord):
self.image = image
self.pos = coord
def getInfo(self):
return [self.image,self.pos]
class Piece:
"""
Piece clips the sprite into pieces to display on the board
"""
def __init__(self,pieceinfo,chess_coord,square_width, square_height):
# pieceinfo is a string such as 'Qb'. The Q represents Queen and b
# shows the fact that it is black:
piece = pieceinfo[0]
color = pieceinfo[1]
# Get the information about where the image for this piece is stored
# on the overall sprite image with all the pieces. Note that
# square_width and square_height represent the size of a square on the
# chess board.
if piece=='K':
index = 0
elif piece=='Q':
index = 1
elif piece=='B':
index = 2
elif piece == 'N':
index = 3
elif piece == 'R':
index = 4
elif piece == 'P':
index = 5
left_x =square_width*index
if color == 'w':
left_y = 0
else:
left_y = square_height
self.pieceinfo = pieceinfo
# subsection defines the part of the sprite image that represents our
# piece
self.subsection = (left_x,left_y,square_width,square_height)
# There are two ways that the position of a piece is defined on the
# board.
# The default one used is the chess_coord, which stores something
# like (3,2). It represents the chess coordinate where our piece image should
# be blitted. On the other hand, is pos does not hold the default value
# of (-1,-1), it will hold pixel coordinates such as (420,360) that represents
# the location in the window that the piece should be blitted on. This is
# useful for example if our piece is transitioning from a square to another:
self.chess_coord = chess_coord
self.pos = (-1,-1)
def getInfo(self):
return [self.chess_coord, self.subsection,self.pos]
def setpos(self,pos):
self.pos = pos
def getpos(self):
return self.pos
def setcoord(self,coord):
self.chess_coord = coord
class Commands:
"""
this class works with variables that hold the information about game state.
it contains chess processing functions
"""
def isOccupied(self,board,x,y):
# isOccupied(board,x,y) - Returns true if a given coordinate on the board is not empty, and
# false otherwise.
if board[int(y)][int(x)] == 0:
# The square has nothing on it.
return False
return True
def isOccupiedby(self,board,x,y,color):
# isOccupiedby(board,x,y,color) - Same as above, but only returns true if the square
# specified by the coordinates is of the specific color inputted.
if board[y][x] == 0:
# the square has nothing on it.
return False
if board[y][x][1] == color[0]:
# The square has a piece of the color inputted.
return True
# The square has a piece of the opposite color.
return False
def filterbyColor(self,board,listofTuples,color):
# filterbyColor(board,listofTuples,color) - This function takes the board state, a list
# of coordinates, and a color as input. It will return the same list, but without
# coordinates that are out of bounds of the board and also without those occupied by the
# pieces of the particular color passed to this function as an argument. In other words,
# if 'white' is passed in, it will not return any white occupied square.
filtered_list = []
# Go through each coordinate:
for pos in listofTuples:
x = pos[0]
y = pos[1]
if x>=0 and x<=7 and y>=0 and y<=7 and not self.isOccupiedby(board,x,y,color):
# coordinates are on-board and no same-color piece is on the square.
filtered_list.append(pos)
return filtered_list
def lookfor(self,board,piece):
# lookfor(board,piece) - This functions takes the 2D array that represents a board and finds
# the indices of all the locations that is occupied by the specified piece. The list of
# indices is returned.
listofLocations = []
for row in range(8):
for col in range(8):
if board[row][col] == piece:
x = col
y = row
listofLocations.append((x,y))
return listofLocations
def isAttackedby(self,position,target_x,target_y,color):
# isAttackedby(position,target_x,target_y,color) - This function checks if the square specified
# by (target_x,target_y) coordinates is being attacked by any of a specific colored set of pieces.
# Get board
board = position.getboard()
# Get b from black or w from white
color = color[0]
# Get all the squares that are attacked by the particular side:
listofAttackedSquares = []
for x in range(8):
for y in range(8):
if board[y][x]!=0 and board[y][x][1]==color:
listofAttackedSquares.extend(
self.findPossibleSquares(position,x,y,True)) #The true argument
# prevents infinite recursion.
# Check if the target square falls under the range of attack by the specified
# side, and return it:
return (target_x,target_y) in listofAttackedSquares
def findPossibleSquares(self,position,x,y,AttackSearch=False):
# findPossibleSquares(position,x,y,AttackSearch=False) - This function takes as its input the
# current state of the chessboard, and a particular x and y coordinate. It will return for the
# piece on that board a list of possible coordinates it could move to, including captures and
# excluding illegal moves (eg moves that leave a king under check). AtttackSearch is an
# argument used to ensure infinite recursions do not occur.
# Get individual component data from the position object:
board = position.getboard()
player = position.getplayer()
castling_rights = position.getCastleRights()
EnP_Target = position.getEnP()
# In case something goes wrong:
piece = board[y][x][0] #Pawn, rook, etc.
color = board[y][x][1] #w or b.
# Have the complimentary color stored for convenience:
enemy_color = self.opp(color)
listofTuples = [] #Holds list of attacked squares.
if piece == 'P': #The piece is a pawn.
if color=='w': #The piece is white
if not self.isOccupied(board,x,y-1) and not AttackSearch:
#The piece immediately above is not occupied, append it.
listofTuples.append((x,y-1))
if y == 6 and not self.isOccupied(board,x,y-2):
#If pawn is at its initial position, it can move two squares.
listofTuples.append((x,y-2))
if x!=0 and self.isOccupiedby(board,x-1,y-1,'black'):
#The piece diagonally up and left of this pawn is a black piece.
#Also, this is not an 'a' file pawn (left edge pawn)
listofTuples.append((x-1,y-1))
if x!=7 and self.isOccupiedby(board,x+1,y-1,'black'):
#The piece diagonally up and right of this pawn is a black one.
#Also, this is not an 'h' file pawn.
listofTuples.append((x+1,y-1))
if EnP_Target!=-1: #There is a possible en pasant target:
if EnP_Target == (x-1,y-1) or EnP_Target == (x+1,y-1):
#We're at the correct location to potentially perform en
#passant:
listofTuples.append(EnP_Target)
elif color=='b': #The piece is black, same as above but opposite side.
if not self.isOccupied(board,x,y+1) and not AttackSearch:
listofTuples.append((x,y+1))
if y == 1 and not self.isOccupied(board,x,y+2):
listofTuples.append((x,y+2))
if x!=0 and self.isOccupiedby(board,x-1,y+1,'white'):
listofTuples.append((x-1,y+1))
if x!=7 and self.isOccupiedby(board,x+1,y+1,'white'):
listofTuples.append((x+1,y+1))
if EnP_Target == (x-1,y+1) or EnP_Target == (x+1,y+1):
listofTuples.append(EnP_Target)
elif piece == 'R': #The piece is a rook.
#Get all the horizontal squares:
for i in [-1,1]:
#i is -1 then +1. This allows for searching right and left.
kx = x #This variable stores the x coordinate being looked at.
while True: #loop till break.
kx = kx + i #Searching left or right
if kx<=7 and kx>=0: #Making sure we're still in board.
if not self.isOccupied(board,kx,y):
#The square being looked at it empty. Our rook can move
#here.
listofTuples.append((kx,y))
else:
#The sqaure being looked at is occupied. If an enemy
#piece is occupying it, it can be captured so its a valid
#move.
if self.isOccupiedby(board,kx,y,enemy_color):
listofTuples.append((kx,y))
#Regardless of the occupying piece color, the rook cannot
#jump over. No point continuing search beyond in this
#direction:
break
else: #We have exceeded the limits of the board
break
#Now using the same method, get the vertical squares:
for i in [-1,1]:
ky = y
while True:
ky = ky + i
if ky<=7 and ky>=0:
if not self.isOccupied(board,x,ky):
listofTuples.append((x,ky))
else:
if self.isOccupiedby(board,x,ky,enemy_color):
listofTuples.append((x,ky))
break
else:
break
elif piece == 'N': #The piece is a knight.
#The knight can jump across a board. It can jump either two or one
#squares in the x or y direction, but must jump the complimentary amount
#in the other. In other words, if it jumps 2 sqaures in the x direction,
#it must jump one square in the y direction and vice versa.
for dx in [-2,-1,1,2]:
if abs(dx)==1:
sy = 2
else:
sy = 1
for dy in [-sy,+sy]:
listofTuples.append((x+dx,y+dy))
#Filter the list of tuples so that only valid squares exist.
listofTuples = self.filterbyColor(board,listofTuples,color)
elif piece == 'B': # A bishop.
#A bishop moves diagonally. This means a change in x is accompanied by a
#change in y-coordiante when the piece moves. The changes are exactly the
#same in magnitude and direction.
for dx in [-1,1]: #Allow two directions in x.
for dy in [-1,1]: #Similarly, up and down for y.
kx = x #These varibales store the coordinates of the square being
#observed.
ky = y
while True: #loop till broken.
kx = kx + dx #change x
ky = ky + dy #change y
if kx<=7 and kx>=0 and ky<=7 and ky>=0:
#square is on the board
if not self.isOccupied(board,kx,ky):
#The square is empty, so our bishop can go there.
listofTuples.append((kx,ky))
else:
#The square is not empty. If it has a piece of the
#enemy,our bishop can capture it: