# data[].attributes.body
LEARN SHARE & CODE

# data[].attributes.body
from bs4 import BeautifulSoup as BS
import requests

def get_info(url):
data=requests.get(url)
soup=BS(data.text,'html.parser')
total=soup.find("div",class_="maincounter-number").text
total=total[1: len(total) - 2]
other=soup.find_all("span",class_="number-table")
recovered=other[2].text
deaths=other[3].text
deaths=deaths[1:]
ans={'Total Cases':total,'Recovered Cases':recovered,'Total Deaths':deaths}
return ans

url="https://www.worldometers.info/coronavirus/"
ans=get_info(url)
for i, j in ans.items():
print(i + " : " + j)

# data[].attributes.body
import turtle
t=turtle.Turtle()
s=turtle.Screen()
s.bgcolor('black')
t.pencolor('white')
a=0
b=0
t.speed(0)
t.penup()
t.goto(0,200)
t.pendown()
while True:
t.forward(a)
t.right(b)
a+=3
b+=1
if b==210:
break
t.hideturtle()
turtle.done()

# data[].attributes.body
import tkinter as tk
import webbrowser

class Check:
""" create checkbuttons for links """
def __init__(self, master, site):
self.var = tk.IntVar()
self.site = site
self = tk.Checkbutton(
master,
text = self.site,
variable = self.var,
command = self.check).pack()

def check(self):
v = self.var.get() # 1 checked 0 unchecked
if v:
checked.append(self.site)
else:
if self.site in checked:
checked.remove(self.site)

class App:
def __init__(self, sites):
"""creates the window"""
c = []
master = tk.Tk()
for site in sites:
c.append(Check(master, site))
tk.Button(
master,
text = "Launch",
command = self.start).pack()
master.mainloop()

def start(self):
chrome = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
w = webbrowser.get(chrome)
for checked_site in checked:
w.open(checked_site)

checked = []
app = App([
"https://www.facebook.com/",
"https://www.instagram.com/",
"https://twitter.com/login",
])

# data[].attributes.body
LDL=eval(input("enter value of LDL:"))
HDL=eval(input("enter value of HDL:"))
TRI=eval(input("enter value of TRI:"))
total= LDL+HDL+ (TRI/5.0)
if (LDL<100) and (HDL>60) and (TRI,150) and (total<200):
print ("you gucci fam")
elif (LDL>130) or (HDL<50) or (TRI>200) or (total>240):
print ("take serious action against your cholesterol fam!")
else:
print("almost everyone has these problems, homeslice")

# data[].attributes.body
reflections = {
"i am"       : "you are",
"i was"      : "you were",
"i"          : "you",
"i'm"        : "you are",
"i'd"        : "you would",
"i've"       : "you have",
"i'll"       : "you will",
"my"         : "your",
"you are"    : "I am",
"you were"   : "I was",
"you've"     : "I have",
"you'll"     : "I will",
"your"       : "my",
"yours"      : "mine",
"you"        : "me",
"me"         : "you",
"go"          : "gone",
"hello"      : "hey there"
}

from nltk.chat.util import Chat, reflections
pairs = [
[
r"my name is (.*)",
["Hello %1, How are you today ?",]
],
[
r"what is your name ?",
["My name is Jarvis and I'm a chatbot ?",]
],
[
r"how are you ?",
["I'm doing good\nHow about You ?",]
],
[
r"What can you do ?",
["I can assist, guide and spend time with you",]
],
[
r"how do I look like?",
["you are looking Gorgeous",]
],
[
r" What are your Hobbies?",
["Most of the time I spend with you, you my whole world",]
],
[
r"sorry (.*)",
["Its alright","Its OK, never mind",]
],
[
r"i'm (.*) doing good",
["Nice to hear that","Alright :)",]
],
[
r"hai|hi|hey|hello",
["Hello", "Hey there",]
],
[
r"(.*) age?|(.*) old are you?",
["I'm a computer program dude\nSeriously you are asking me this?",]

],
[
r"what (.*) want ?",
["Make me an offer I can't refuse",]

],
[
r"(.*) weather today ?",
["'it's pretty good","it's worser than ever"]
],
[
r"(.*) created ?",
["Sarang created me using Python's NLTK library ","top secret ;)",]
],
[
r"(.*) (location|city) ?",
['Kozhikode, Kerala',]
],
[
r"(.*) hobbies ?",
["My hobbies are spending time with you", "you are my world",]
],
[
r"how is weather in (.*)?",
["Weather in %1 is awesome like always","Too hot man here in %1","Too cold man here in %1","Never even heard about %1"]
],
[
r"i work in (.*)?",
["%1 is an Amazing company, I have heard about it. But they are in huge loss these days.",]
],
[
r"(.*)raining in (.*)",
["No rain since last week here in %2","Damn its raining too much here in %2"]
],
[
r"how (.*) health(.*)",
["I'm a computer program, so I'm always healthy ",]
],
[
r"(.*) (sports|game) ?",
["I'm a very big fan of Football and batminton",]
],
[
r"who (.*) sportsperson ?",
["Messy","Ronaldo","Roony","Neymar"]
],
[
r"who (.*) (moviestar|actor)?",
["our own Lal ettan"]
],
[
r"What (.*) time now",
["it's a good time for you, you are a lucky charm"]
],
[
r"quit",
["BBye take care. See you soon :) ","It was nice talking to you. See you soon :)"]
],
]

def Jarvis():
print("Hi, I'm Jarvis and I chat alot ;)\nPlease type lowercase English language to start a conversation. Type quit to leave ") #default message at the start
chat = Chat(pairs, reflections)
chat.converse()
if __name__ == "__main__":
Jarvis()

# data[].attributes.body
# import all functions from the tkinter
from tkinter import *

from tkinter import ttk

#import Calendar module
import calendar

def showCal():

#new calendar window
new_window = Tk()

#setting the background color of GUI application
new_window.config(background = 'white')

#setting the title of the GUI application
new_window.title("Calendar")

#setting the geometry of the GUI application
new_window.geometry('550x600')

# get method returns current text as string
fetch_year = int(year_field.get())

# calendar method of calendar module return
# the calendar of the given year .
cal_content = calendar.calendar(fetch_year)

# Create a label for showing the content of the calender
cal_year = Label(new_window, text = cal_content, font = "Consolas 10 bold")

# grid method is used for placing
# the widgets at respective positions
# in table like structure.
cal_year.grid(row = 5, column = 1, padx = 20)

# start the GUI
new_window.mainloop()

if __name__=='__main__':

#Create the basic gui window
root = Tk()

#setting the background color of GUI application
root.config(background = 'white')

#setting the title of the GUI application
root.title("HOME")

#setting the geometry of the GUI application
root.geometry('500x400')

# Create a CALENDAR : label with specified font and size
cal = Label(root, text = "Welcome to the calendar Application", bg = "Red", font = ("times", 20, 'bold'))

#Create a Year label : a label to ask the user for year
year = Label(root, text = 'Please enter a year',bg = 'Green')

#Create a Year Entry : Entry
year_field = Entry(root)

# Create a Show Calendar Button and attached to showCal function
Show = Button(root, text = "Show Calendar", fg = "Black", bg = "Light Green", command = showCal)

# Create a Exit Button and attached to exit function
Exit = Button(root, text = "Exit", fg = "Black", bg = "Light Green", command = exit)

# grid method is used for placing
# the widgets at respective positions
# in table like structure.
cal.grid(row = 1, column = 1)

year.grid(row = 2, column = 1)

year_field.grid(row = 3, column = 1)

Show.grid(row = 4, column = 1)

Exit.grid(row = 6, column = 1)

# start the GUI
root.mainloop()

# data[].attributes.body
name1=input("enter the first name:")
height_m1=eval(input("enter the first height:"))
weight_kg1=eval(input("enter the first weight:"))

name2= input("enter the second name:")
height_m2=eval(input("enter the second height:"))
weight_kg2=eval(input("enter the second weight:"))

name3=input("enter the third name:")
height_m3=eval(input("enter the third height:"))
weight_kg3=eval(input("enter the third weight:"))

name4=input("enter the forth name:")
height_m4=eval(input("enter the forth height:"))
weight_kg4=eval(input("enter the forth weight:"))

def bmi_calculator(name, height_m,weight_kg):
bmi = weight_kg/(height_m**2)
print("bmi:")
print(bmi)
if bmi<25:
return name + " is not over weight"
else:
return name + " is overweight"

result1=bmi_calculator(name1, height_m1,weight_kg1)
result2=bmi_calculator(name2, height_m2,weight_kg2)
result3=bmi_calculator(name3, height_m3,weight_kg3)
result4=bmi_calculator(name4, height_m4,weight_kg4)

print(result1)
print(result2)
print(result3)
print(result4)

# data[].attributes.body
#!/usr/bin/python
import getpass
import string
import os

# creatinga lists of users, their PINs and bank statements
users = ['user1', 'user2', 'user3']
pins = ['1111', '2222', '3333']
amounts = [1000, 2000, 3000]
count = 0
# while loop checks existance of the enterd username
while True:
user = input('\nENTER USER NAME: ')
user = user.lower()
if user in users:
if user == users[0]:
n = 0
elif user == users[1]:
n = 1
else:
n = 2
break
else:
print('----------------')
print('****************')
print('INVALID USERNAME')
print('****************')
print('----------------')

# comparing pin
while count < 3:
print('------------------')
print('******************')
pin = str(getpass.getpass('PLEASE ENTER PIN: '))
print('******************')
print('------------------')
if pin.isdigit():
if user == 'user1':
if pin == pins[0]:
break
else:
count += 1
print('-----------')
print('***********')
print('INVALID PIN')
print('***********')
print('-----------')
print()

if user == 'user2':
if pin == pins[1]:
break
else:
count += 1
print('-----------')
print('***********')
print('INVALID PIN')
print('***********')
print('-----------')
print()

if user == 'user3':
if pin == pins[2]:
break
else:
count += 1
print('-----------')
print('***********')
print('INVALID PIN')
print('***********')
print('-----------')
print()
else:
print('------------------------')
print('************************')
print('PIN CONSISTS OF 4 DIGITS')
print('************************')
print('------------------------')
count += 1

# in case of a valid pin- continuing, or exiting
if count == 3:
print('-----------------------------------')
print('***********************************')
print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
print('***********************************')
print('-----------------------------------')
exit()

print('-------------------------')
print('*************************')
print('LOGIN SUCCESFUL, CONTINUE')
print('*************************')
print('-------------------------')
print()
print('--------------------------')
print('**************************')
print(str.capitalize(users[n]), 'welcome to ATM')
print('**************************')
print('----------ATM SYSTEM-----------')
# Main menu
while True:
#os.system('clear')
print('-------------------------------')
print('*******************************')
response = input('SELECT FROM FOLLOWING OPTIONS: \nStatement__(S) \nWithdraw___(W) \nLodgement__(L)  \nChange PIN_(P)  \nQuit_______(Q) \n: ').lower()
print('*******************************')
print('-------------------------------')
valid_responses = ['s', 'w', 'l', 'p', 'q']
response = response.lower()
if response == 's':
print('---------------------------------------------')
print('*********************************************')
print(str.capitalize(users[n]), 'YOU HAVE ', amounts[n],'EURO ON YOUR ACCOUNT.')
print('*********************************************')
print('---------------------------------------------')

elif response == 'w':
print('---------------------------------------------')
print('*********************************************')
cash_out = int(input('ENTER AMOUNT YOU WOULD LIKE TO WITHDRAW: '))
print('*********************************************')
print('---------------------------------------------')
if cash_out%10 != 0:
print('------------------------------------------------------')
print('******************************************************')
print('AMOUNT YOU WANT TO WITHDRAW MUST TO MATCH 10 EURO NOTES')
print('******************************************************')
print('------------------------------------------------------')
elif cash_out > amounts[n]:
print('-----------------------------')
print('*****************************')
print('YOU HAVE INSUFFICIENT BALANCE')
print('*****************************')
print('-----------------------------')
else:
amounts[n] = amounts[n] - cash_out
print('-----------------------------------')
print('***********************************')
print('YOUR NEW BALANCE IS: ', amounts[n], 'EURO')
print('***********************************')
print('-----------------------------------')

elif response == 'l':
print()
print('---------------------------------------------')
print('*********************************************')
cash_in = int(input('ENTER AMOUNT YOU WANT TO LODGE: '))
print('*********************************************')
print('---------------------------------------------')
print()
if cash_in%10 != 0:
print('----------------------------------------------------')
print('****************************************************')
print('AMOUNT YOU WANT TO LODGE MUST TO MATCH 10 EURO NOTES')
print('****************************************************')
print('----------------------------------------------------')
else:
amounts[n] = amounts[n] + cash_in
print('----------------------------------------')
print('****************************************')
print('YOUR NEW BALANCE IS: ', amounts[n], 'EURO')
print('****************************************')
print('----------------------------------------')
elif response == 'p':
print('-----------------------------')
print('*****************************')
new_pin = str(getpass.getpass('ENTER A NEW PIN: '))
print('*****************************')
print('-----------------------------')
if new_pin.isdigit() and new_pin != pins[n] and len(new_pin) == 4:
print('------------------')
print('******************')
new_ppin = str(getpass.getpass('CONFIRM NEW PIN: '))
print('*******************')
print('-------------------')
if new_ppin != new_pin:
print('------------')
print('************')
print('PIN MISMATCH')
print('************')
print('------------')
else:
pins[n] = new_pin
print('NEW PIN SAVED')
else:
print('-------------------------------------')
print('*************************************')
print('   NEW PIN MUST CONSIST OF 4 DIGITS \nAND MUST BE DIFFERENT TO PREVIOUS PIN')
print('*************************************')
print('-------------------------------------')
elif response == 'q':
exit()
else:
print('------------------')
print('******************')
print('RESPONSE NOT VALID')
print('******************')
print('------------------')

# data[].attributes.body
def main():
pinCode = ["1234", "1999", "2424", "1985", "5555","1621"] #data of the account holders
accountHoldersName = ["harry den", "zain ul abideen", "waseema shaukat", "ayesha mukhtar", "khalid mahmood",]
accountNumber = ['1353', '199281', "182838", "185597", "667432",
balance = [567000, 21873, 2341871, 275638, 91820,14562396876]

flag = False
for i in range (0,999999999): #so the loop runs almost infinit many times
print("""
\t\t=== Welcome To Simple ATM System ===
""")
inputName = input("Enter Your Name: ")
inputName = inputName.lower()
inputPin = 0000 #if pin is wrong it will be use as this is assigned before referance.
index = 0 #if pin is wrong it will be use as this is assigned before referance.
for name in accountHoldersName:
count = 0
if name == inputName:
index = count #index of anme is stored and if the pin of that index is same user will be given access to the account.
inputPin = input("\nEnter Pin Number: ")
count += 1

if inputPin == pinCode[index]:
flag = True
else:
print("Invalid data.")
flag = False
continue
if flag == True:
print("\nYour account number is: ",accountNumber[index])
print("Your account balance is: Rs.", balance[index])
drawOrDeposite = input("\nDo you want to draw or deposit cash (draw/deposite/no): ")
if drawOrDeposite == "draw":
amount = input("\nEnter the amount you want to draw: ")
try: #Exception handling
amount = int(amount)
if amount > balance[index]:
raise
except:
print("invalid amount.")
continue
remainingBalalnce = balance[index] - amount #subtracting the drawed amount.
balance.remove(balance[index]) #removing the old ammount from the list and adding the new list after draw.
balance.insert(index,remainingBalalnce)
availableBalance = print("\nYour available balance is: ",remainingBalalnce)
elif drawOrDeposite == "deposite":
amount = input("Enter the amount you want to deposite: ")
try:
amount = int(amount)
if amount > balance[index]:
raise
except:
print("invalid amount.")
continue
remainingBalalnce = balance[index] + amount #adding the deposited amount.
balance.remove(balance[index])#removing the old ammount from the list and adding the new list after draw.
balance.insert(index,remainingBalalnce)
availableBalance = print("Your available balance is: ",remainingBalalnce)
print("\n\nThank you for using this Simple ATM System. \n  Brought To You By code-projects.org")

main()

# data[].attributes.body
import turtle
import time
wndw = turtle.Screen()
wndw.bgcolor("black")
wndw.setup(width=600, height=600)
wndw.title("Analogue Clock")
wndw.tracer(0)
# Create the drawing pen
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)
def draw_clock(hr, mn, sec, pen):
# Draw clock face
pen.up()
pen.goto(0, 210)
pen.setheading(180)
pen.color("green")
pen.pendown()
pen.circle(210)
# Draw hour hashes
pen.up()
pen.goto(0, 0)
pen.setheading(90)
for _ in range(12):
pen.fd(190)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0, 0)
pen.rt(30)
# Draw the hands
# Each tuple in list hands describes the color, the length
# and the divisor for the angle
hands = [("white", 80, 12), ("blue", 150, 60), ("red", 110, 60)]
time_set = (hr, mn, sec)
for hand in hands:
time_part = time_set[hands.index(hand)]
angle = (time_part/hand[2])*360
pen.penup()
pen.goto(0, 0)
pen.color(hand[0])
pen.setheading(90)
pen.rt(angle)
pen.pendown()
pen.fd(hand[1])
while True:
hr = int(time.strftime("%I"))
mn = int(time.strftime("%M"))
sec = int(time.strftime("%S"))
draw_clock(hr, mn, sec, pen)
wndw.update()
time.sleep(1)
pen.clear()
wndw.mainloop()

# data[].attributes.body
def zodiac_sign(day, month):

# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'

elif month == 'january':
astro_sign = 'Capricorn' if (day < 20) else 'aquarius'

elif month == 'february':
astro_sign = 'Aquarius' if (day < 19) else 'pisces'

elif month == 'march':
astro_sign = 'Pisces' if (day < 21) else 'aries'

elif month == 'april':
astro_sign = 'Aries' if (day < 20) else 'taurus'

elif month == 'may':
astro_sign = 'Taurus' if (day < 21) else 'gemini'

elif month == 'june':
astro_sign = 'Gemini' if (day < 21) else 'cancer'

elif month == 'july':
astro_sign = 'Cancer' if (day < 23) else 'leo'

elif month == 'august':
astro_sign = 'Leo' if (day < 23) else 'virgo'

elif month == 'september':
astro_sign = 'Virgo' if (day < 23) else 'libra'

elif month == 'october':
astro_sign = 'Libra' if (day < 23) else 'scorpio'

elif month == 'november':
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'

print("your astrological sign is:",astro_sign)

# Driver code
if __name__ == '__main__':
day = int(input('enter the date:'))
month = input("enter the monthe:")
zodiac_sign(day, month)

# data[].attributes.body
def findage(current_date,current_month,current_year,birth_date,birth_month,birth_year):
month=[31,28,31,30,31,30,31,31,30,31,30,31]
if(birth_date>current_date):
current_month=current_month-1
current_date=current_date+month[birth_month-1]

if(birth_month>current_month):
current_year=current_year-1
current_month=current_month+12
calculated_date=current_date-birth_date
calculated_month=current_month-birth_month
calculated_year=current_year-birth_year
print("Present Age")
print("Years:",calculated_year,"Months:",calculated_month,"Days:",calculated_date)

current_date=eval(input("enter the current_date:"))
current_month=eval(input("enter the current_month:"))
current_year=eval(input("enter the current_year:"))

birth_date=eval(input("enter the birth_date:"))
birth_month=eval(input("enter the birth_month:"))
birth_year=eval(input("enter the birth_year:"))
findage(current_date,current_month,current_year,birth_date,birth_month,birth_year)

# data[].attributes.body
# importing whole module
from tkinter import *
from tkinter.ttk import *

# importing strftime function to
# retrieve system's time
from time import strftime

# creating tkinter window
root = Tk()
root.title('Clock')

# This function is used to
# display time on the label
def time():
string = strftime('%H:%M:%S %p')
lbl.config(text = string)
lbl.after(1000, time)

# Styling the label widget so that clock
# will look more attractive
lbl = Label(root, font = ('Castellar', 40, 'bold'),
background = 'black',
foreground = 'white')

# Placing clock at the centre
# of the tkinter window
lbl.pack(anchor = 'center')
time()

mainloop()

# data[].attributes.body
import turtle
turtle.bgcolor("black")
turtle.pensize(2)
turtle.speed(0)

for i in range(6):
for colours in ['red','magenta','blue','cyan','green','yellow','white']:
turtle.color(colours)
turtle.circle(100)
turtle.left(10)
turtle.hideturtle()

# data[].attributes.body
import turtle
t=turtle.Turtle()
s=turtle.Screen()
s.bgcolor('white')
t.pencolor('red')
t.speed(1000)
c=0
d=0
while True:
for i in range(4):
t.forward(80)
t.right(90)
t.right(15)
c+=1
if c>=390/15:
t.forward(50)
c=0
d+=1
if d>12:
break
t.hideturtle()
turtle.done()

# data[].attributes.body
import turtle
my_wn=turtle.Screen()
turtle.speed(50)
for i in range(30):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)
turtle.exitonclick()

# data[].attributes.body
import turtle
import math
import colorsys
phi=180*(3-math.sqrt(5))
t=turtle.Pen()
t.speed(0)
def square(t,size):
for tmp in range(0,4):
t.forward(size)
t.right(90)

num=200
for x in reversed(range(0,num)):
t.fillcolor(colorsys.hsv_to_rgb(x/num,1.0,1.0))
t.begin_fill()
t.circle(5+x,None,11)
square(t,5+x)
t.end_fill()
t.right(phi)
t.right(.8)
turtle.mainloop()

# data[].attributes.body
import re

# Function to categorize password
def password(v):

# the password should not be a
# newline or space
if v == "\n" or v == " ":
return "Password cannot be a newline or space!"

# the password length should be in
# between 9 and 20
if 9 <= len(v) <= 20:

# checks for occurrence of a character
# three or more times in a row
if re.search(r'(.)\1\1', v):
return "Weak Password: Same character repeats three or more times in a row"

# checks for occurrence of same string
# pattern( minimum of two character length)
# repeating
if re.search(r'(..)(.*?)\1', v):
return "Weak password: Same string pattern repetition"

else:
return "Strong Password!"

else:
return "Password length must be 9-20 characters!"

# Main method
def main():

# Driver code
print(password(input("enter a password:")))
print(password(input("enter a password:")))
print(password(input("enter a password:")))

# Driver Code
if __name__ == '__main__':
main()

# data[].attributes.body
from bs4 import BeautifulSoup as BS
import requests

def get_price(url):
data=requests.get(url)
soup=BS(data.text,'html.parser')
ans=soup.find('div',id='current-price').text
return ans
url='https://www.goodreturns.in/gold-rates/'
ans=get_price(url)
print(ans)

# data[].attributes.body
# importing above defined libraries to
# implement the functionalities
from PIL import ImageGrab, ImageOps
import pyautogui
import time
import numpy as np

class cordinates():

# coordinates of replay button to start the game
replaybutton =(360, 214)
# this coordinates represent the top-right coordinates
# that will be used to define the front box
dinasaur = (149, 239 )

def restartGame():

# using pyautogui library, we are clicking on the
# replay button without any user interaction
pyautogui.click(cordinates.replaybutton)

# we will keep our Bot always down that
# will prevent him to get hit by bird
pyautogui.keyDown('down')

def press_space():

# releasing the Down Key
pyautogui.keyUp('down')

# pressing Space to overcome Bush
pyautogui.keyDown('space')

# so that Space Key will be recognized easily
time.sleep(0.05)

# printing the "Jump" statement on the
# terminal to see the current output
print("jump")
time.sleep(0.10)

# releasing the Space Key
pyautogui.keyUp('space')

# again pressing the Down Key to keep my Bot always down
pyautogui.keyDown('down')

def imageGrab():
# defining the coordinates of box in front of dinosaur
box = (cordinates.dinasaur[0]+30, cordinates.dinasaur[1],
cordinates.dinasaur[0]+120, cordinates.dinasaur[1]+2)

# grabbing all the pixels values in form of RGB tupples
image = ImageGrab.grab(box)

# converting RGB to Grayscale to
# make processing easy and result faster
grayImage = ImageOps.grayscale(image)

# using numpy to get sum of all grayscale pixels
a = np.array(grayImage.getcolors())

# returning the sum
print(a.sum())
return a.sum()

# function to restart the game
restartGame()
while True:
# 435 is the sum of white pixels values of box.
# You may get different value is you are taking bigger
# or smaller box than the box taken in this article.
# if value returned by "imageGrab" function is not equal to 435,
# it means either bird or bush is coming towards dinosaur
if(imageGrab()!= 435):
press_space()
# time to recognize the operation performed by above function
time.sleep(0.1)

# data[].attributes.body
from googlesearch import *
import webbrowser
#to search, will ask search query at the time of execution
query = input("Input your query:")
#iexplorer_path = r'C:\Program Files (x86)\Internet Explorer\iexplore.exe %s'
chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
for url in search(query, tld="co.in", num=1, stop = 1, pause = 2):
webbrowser.open("https://google.com/search?q=%s" % query)

# data[].attributes.body
# Python rogram to find the SHA-1 message digest of a file

# importing the hashlib module
import hashlib

def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""

# make a hash object
h = hashlib.sha1()

# open file for reading in binary mode
with open(filename,'rb') as file:

# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)

# return the hex representation of digest
return h.hexdigest()

message = hash_file(input("enter the file:"))
print(message)

# data[].attributes.body
"""
Recursively draw rectangles.

Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/

"""
import pygame

# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

def recursive_draw(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, black,
[x,y,width,height],
1)

# Is the rectangle wide enough to draw again?
if( width > 14 ):
# Scale down
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw(x, y, width, height)

pygame.init()

# Set the height and width of the screen
size = [700, 500]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

# Set the screen background
screen.fill(white)

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
recursive_draw(0, 0, 700, 500)
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Limit to 60 frames per second
clock.tick(60)

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

# data[].attributes.body
import instaloader
mod=instaloader.Instaloader()
a=input('Enter the User Name -->')
mod.download_profile(a,profile_pic_only=True)

# data[].attributes.body
import speedtest
test=speedtest.Speedtest()
down=test.download()
upload=test.upload()
print(f"Download speed:{down}")
print(f"Upload speed:{upload}")

# data[].attributes.body
from tkinter import *

#Import Tk themed widgets
from tkinter import ttk

class Loan_Calculator():

def __init__(self):

#creating the root window here
root = Tk()

#set the title
root.title('Loan Calculator')

#set the geometry
#root.geometry('250x300')

#set the background color
root.config(background='beige')

#creating the labels
Label(root,text='Annual Interest Rate',bg='Beige' , borderwidth = 4).grid(row=1,column = 1,sticky = W)

Label(root,text='Numbers of Years',bg='Beige' , borderwidth = 4).grid(row=2,column = 1,sticky = W)

Label(root,text='Loan Ammount',bg='Beige' , borderwidth = 4).grid(row=3,column = 1,sticky = W)

Label(root,text='Monthly Payment',bg='Beige' , borderwidth = 4).grid(row=4 ,column = 1,sticky = W)

Label(root,text='Total Payment',bg='Beige' , borderwidth = 4).grid(row=5,column = 1,sticky = W)

#Create the Entry Widgets
self.AnnualInterest = StringVar()
Entry(root, textvariable = self.AnnualInterest,justify = RIGHT).grid(row = 1,column = 2,sticky = E)

self.years = StringVar()
Entry(root, textvariable = self.years,justify = RIGHT).grid(row = 2,column = 2,sticky = E)

self.amount = StringVar()
Entry(root, textvariable = self.amount,justify = RIGHT).grid(row = 3,column = 2,sticky = E)

self.monthlyPayment = StringVar()
Label(root, textvariable = self.monthlyPayment).grid(row = 4,column = 2,sticky = E)

self.TotalPayment = StringVar()
Label(root, textvariable = self.TotalPayment).grid(row = 5,column = 2,sticky = E)

#CREATING BUTTONS
compute = Button(root, text = 'Compute Loan',command = self.ComputePayment).grid(row = 6, column = 2,sticky = E)

root.mainloop()

# compute the total payment.
def ComputePayment(self):

month = self.getMonthlyPayment(
float(self.amount.get()),
float(self.AnnualInterest.get()) / 1200,
int(self.years.get()))

self.monthlyPayment.set(format(month, '10.2f'))

total = float(self.monthlyPayment.get()) * 12 * int(self.years.get())

self.TotalPayment.set(format(total, '10.2f'))

def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):
# compute the monthly payment.
month = loanAmount * monthlyInterestRate / (1
- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
return month;

Loan_Calculator()

# data[].attributes.body
import turtle

turtle.bgcolor("white")
turtle.pensize(2)

def curve():
for i in range(200):
turtle.right(1)
turtle.forward(1)

turtle.speed(0)
turtle.color("pink","pink")

turtle.begin_fill()
turtle.left(140)
turtle.forward(111.65)
curve()

turtle.left(120)
curve()
turtle.forward(111.65)
turtle.end_fill()
turtle.hideturtle()

# data[].attributes.body
# Python program to implement Morse Code Translator

'''
VARIABLE KEY
'cipher' -> 'stores the morse translated form of the english string'
'decipher' -> 'stores the english translated form of the morse string'
'citext' -> 'stores morse code of a single character'
'i' -> 'keeps count of the spaces between morse characters'
'message' -> 'stores the string to be encoded or decoded'
'''

# Dictionary representing the morse code chart
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--',
'X':'-..-', 'Y':'-.--', 'Z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}

# Function to encrypt the string
# according to the morse code chart
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':

# Looks up the dictionary and adds the
# correspponding morse code
# along with a space to separate
# morse codes for different characters
cipher += MORSE_CODE_DICT[letter] + ' '
else:
# 1 space indicates different characters
# and 2 indicates different words
cipher += ' '

return cipher

# Function to decrypt the string
# from morse to english
def decrypt(message):

# extra space added at the end to access the
# last morse code
message += ' '

decipher = ''
citext = ''
for letter in message:

# checks for space
if (letter != ' '):

# counter to keep track of space
i = 0

# storing morse code of a single character
citext += letter

# in case of space
else:
# if i = 1 that indicates a new character
i += 1

# if i = 2 that indicates a new word
if i == 2 :

# adding space to separate words
decipher += ' '
else:

# accessing the keys using their values (reverse of encryption)
decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
.values()).index(citext)]
citext = ''

return decipher
# Hard-coded driver function to run the program
def main():
message = input("enter the string:")
result = encrypt(message.upper())
print (result)

message = "--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... "
result = decrypt(message)
'''print (result) '''

# Executes the main function
if __name__ == '__main__':
main()

# data[].attributes.body
import phonenumbers
from phonenumbers import carrier
from phonenumbers import geocoder
phone_number=phonenumbers.parse("+919495567349")
print(geocoder.description_for_number(phone_number,'en'))
print(carrier.name_for_number(phone_number,'en'))

# data[].attributes.body
from tqdm import tqdm
import time

for i in tqdm(range(101),
desc="Loading........",
ascii=False, ncols=75):
time.sleep(0.01)
print('You are Hacked!!!!!' )

# data[].attributes.body
# pyCalc
# Version 1.1

# Handle Imports
from tkinter import *
from tkinter import ttk

# Define Calculator Class

class Calculator:

# Track calculator values
calc_value = 0.0

# Track Mathematical operators
div_trigger = False
mult_trigger = False
add_trigger = False
sub_trigger = False

# Function - Add up numbers in Entry
def button_press(self, value):
entry_val = self.number_entry.get()
if value != "AC":
entry_val += value
self.number_entry.delete(0, "end")
self.number_entry.insert(0, entry_val)
else:
entry_val = ""
self.number_entry.delete(0, "end")
self.number_entry.insert(0, entry_val)

# Function - Check if value is a float
def isfloat(self, str_val):
try:
float(str_val)
return True
except ValueError:
return False

# Function - Perform mathematical operations
def math_button_press(self, value):
if self.isfloat(str(self.number_entry.get())):
self.div_trigger = False
self.mult_trigger = False
self.add_trigger = False
self.sub_trigger = False

self.calc_value = float(self.entry_value.get())
if value == "/":
self.div_trigger = True
elif value == "*":
self.mult_trigger = True
elif value == "+":
self.add_trigger = True
else:
self.sub_trigger = True

self.number_entry.delete(0, "end")

# Function - Display results to Entry
def equal_button_press(self):
if self.div_trigger or self.mult_trigger or self.add_trigger or self.sub_trigger:
if self.add_trigger:
solution = self.calc_value + float(self.entry_value.get())
elif self.sub_trigger:
solution = self.calc_value - float(self.entry_value.get())
elif self.mult_trigger:
solution = self.calc_value * float(self.entry_value.get())
else:
solution = self.calc_value / float(self.entry_value.get())
self.number_entry.delete(0, "end")
self.number_entry.insert(0, solution)

# Create Tkinter Interface
def __init__(self, root):
self.entry_value = StringVar(root, value="")
root.title('pyCalc')
root.geometry("580x330")
root.resizable(width=False, height=False)

# Tkinter Styling
style = ttk.Style()
style.configure("TButton", font="Serif 15", padding=10)
style.configure("TEntry", font="Serif 18", padding=10)

# Setup GUI
self.number_entry = ttk.Entry(
root, textvariable=self.entry_value, width=50)
self.number_entry.grid(row=0, columnspan=4)

# Buttons - Row 1
self.button7 = ttk.Button(root, text="7",
command=lambda: self.button_press("7")).grid(row=1, column=0)

self.button8 = ttk.Button(root, text="8",
command=lambda: self.button_press("8")).grid(row=1, column=1)

self.button9 = ttk.Button(root, text="9",
command=lambda: self.button_press("9")).grid(row=1, column=2)

self.button_division = ttk.Button(root, text="/",
command=lambda: self.math_button_press("/")).grid(row=1, column=3)

# Buttons - Row 2
self.button4 = ttk.Button(root, text="4",
command=lambda: self.button_press("4")).grid(row=2, column=0)

self.button5 = ttk.Button(root, text="5",
command=lambda: self.button_press("5")).grid(row=2, column=1)

self.button6 = ttk.Button(root, text="6",
command=lambda: self.button_press("6")).grid(row=2, column=2)

self.button_multiply = ttk.Button(root, text="*",
command=lambda: self.math_button_press("*")).grid(row=2, column=3)

# Buttons - Row 3
self.button1 = ttk.Button(root, text="1",
command=lambda: self.button_press("1")).grid(row=3, column=0)

self.button2 = ttk.Button(root, text="2",
command=lambda: self.button_press("2")).grid(row=3, column=1)

self.button3 = ttk.Button(root, text="3",
command=lambda: self.button_press("3")).grid(row=3, column=2)

self.button_add = ttk.Button(root, text="+",
command=lambda: self.math_button_press("+")).grid(row=3, column=3)

# Buttons - Row 4
self.button_clear = ttk.Button(root, text="AC",
command=lambda: self.button_press("AC")).grid(row=4, column=0)

self.button0 = ttk.Button(root, text="0",
command=lambda: self.button_press("0")).grid(row=4, column=1)

self.button_equal = ttk.Button(root, text="=",
command=lambda: self.equal_button_press()).grid(row=4, column=2)

self.button_sub = ttk.Button(root, text="-",
command=lambda: self.math_button_press("-")).grid(row=4, column=3)

# Run application
root = Tk()
calc = Calculator(root)
root.mainloop()

# data[].attributes.body
from PyDictionary import PyDictionary
dict=PyDictionary()
meaning = dict.meaning(input("enter the word to be searched:"))
print(meaning)

# data[].attributes.body
import random
import string
def get_random_password_string(length):
password_character=string.ascii_letters+string.digits+string.punctuation
password=' '.join(random.choice(password_character) for i in range(length))
print("Your Password is:",password)
get_random_password_string(int(input("enter how many characters:")))

# data[].attributes.body
import time
print("Press ENTER to start the stopwatch")
print("and , Press CTRL+C to stop the stopwatch")
while True:
try:
input()
start_time=time.time()
print("stopwatch started..........!!!!!!!!!!!!!!!")
except KeyboardInterrupt:
print("Stopwatch stopped........!!!!!!!!!!!!!")
end_time=time.time()
print("The Total Time:",round(end_time - start_time,2),"seconds")
break

# data[].attributes.body
"""
Show how to put a timeer on the screen.

Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/

"""

import pygame

# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

pygame.init()

# Set the height and width of the screen
size = [700, 500]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

font = pygame.font.Font(None, 25)

frame_count = 0
frame_rate = 60
start_time = 90

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

# Set the screen background
screen.fill(white)

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

# --- Timer going up ---
# Calculate total seconds
total_seconds = frame_count // frame_rate

# Divide by 60 to get total minutes
minutes = total_seconds // 60

# Use modulus (remainder) to get seconds
seconds = total_seconds % 60

# Use python string formatting to format in leading zeros
output_string = "Time: {0:02}:{1:02}".format(minutes, seconds)

# Blit to the screen
text = font.render(output_string, True, black)
screen.blit(text, [250, 250])

# --- Timer going down ---
# --- Timer going up ---
# Calculate total seconds
total_seconds = start_time - (frame_count // frame_rate)
if total_seconds < 0:
total_seconds = 0

# Divide by 60 to get total minutes
minutes = total_seconds // 60

# Use modulus (remainder) to get seconds
seconds = total_seconds % 60

# Use python string formatting to format in leading zeros
output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)

# Blit to the screen
text = font.render(output_string, True, black)

screen.blit(text, [250, 280])

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
frame_count += 1
# Limit to 20 frames per second
clock.tick(frame_rate)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()

# data[].attributes.body
from translate import Translator
translator= Translator(from_lang=input("enter  your language:"),to_lang=input("which language do you want to translate:"))
translation = translator.translate(input("enter the word or sentence:"))
print( translation)

# data[].attributes.body
'''import moviepy.editor
video=moviepy.editor.VideoFileClip("war.mp4")
audio=video.audio
audio.write_audiofile("reasult.mp3")
'''
import moviepy.editor as mp

# Insert Local Video File Path
clip = mp.VideoFileClip(r"WAR.mp4")

# Insert Local Audio File Path
clip.audio.write_audiofile(r"reasult.mp3")

# data[].attributes.body
# importing the module
import wikipedia

# setting language to hindi
wikipedia.set_lang("en")

# printing the summary
print(wikipedia.summary(input("enter what to search:")))

# data[].attributes.body
def windows(n):
if n%2!=0:
c=(n//2)+1
d=0
else:
c=c=(n//2)+1
d=c=(n//2)
for i in range( 1, n+1):
for j in range(1, n+1):
if i==1 or j==1 or i==n or j==n:
print('*',end= " ")
else:
if i==c or j==c:
print('*',end= " ")
elif i==d or j==d:
print('*',end= " ")
else:
print(" ",end=" ")
print()
if __name__=="__main__":
n=7
windows(n)

# data[].attributes.body
from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])

# data[].attributes.body
import pafy

url = input("enter the youtube url to convert mp3:")
video = pafy.new(url)

bestaudio = video.getbestaudio()
bestaudio.download()

# data[].attributes.body
yes_no = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]

# Introduction
name = input("What is your name, adventurer?\n")
print("Greetings, " + name + ". Let us go on a quest!")
print("You find yourself on the edge of a dark forest.")
print("Can you find your way through?\n")

# Start of game
response = ""
while response not in yes_no:
response = input("Would you like to step into the forest?\nyes/no\n")
if response == "yes":
print("You head into the forest. You hear crows cawwing in the distance.\n")
elif response == "no":
print("You are not ready for this quest. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")

# Next part of game
response = ""
while response not in directions:
print("To your left, you see a bear.")
print("To your right, there is more forest.")
print("There is a rock wall directly in front of you.")
print("Behind you is the forest exit.\n")
response = input("What direction do you move?\nleft/right/forward/backward\n")
if response == "left":
print("The bear eats you. Farewell, " + name + ".")
quit()
elif response == "right":
print("You head deeper into the forest.\n")
elif response == "forward":
print("You cannot scale the wall.\n")
response = ""
elif response == "backward":
print("You leave the forest. Goodbye, " + name + ".")
quit()
else:
print("I didn't understand that.\n")

# data[].attributes.body
# -*- coding: utf-8 -*-
""" Air Hockey """

import sys, random

if sys.version_info.major > 2:
import tkinter as tk
else:
import Tkinter as tk

RED, BLACK, WHITE, DARK_RED, BLUE = "red", "black", "white", "dark red", "blue"
ZERO = 2 #for edges.
LOWER, UPPER = "lower", "upper"
HOME, AWAY = "Top", "Bottom"
#Should ALWAYS make a copy of START_SCORE before using it - START_SCORE.copy().
START_SCORE = {HOME: 0, AWAY: 0}
MAX_SCORE = 7 #Winning score.
SPEED = 20 #milliseconds between frame update.
FONT = "ms 50"
MAX_SPEED, PADDLE_SPEED = 15, 15

#### METHODS ####

def str_dict(dic):
""" Returns a string version of score dictionary - dic """
return "%s: %d, %s: %d" % (HOME, dic[HOME], AWAY, dic[AWAY])

def rand():
"""
Picks a random tuple to return out of:
(1, 1), (1, -1), (-1, 1), (-1, -1)
"""
return random.choice(((1, 1), (1, -1), (-1, 1), (-1, -1)))

#### OBJECT DEFINITIONS ####

class Equitment(object):
"""
Parent class of Puck and Paddle.
canvas: tk.Canvas object.
width: int, radius of object.
position: tuple, initial position (x, y).
color: string, color of object.
"""
def __init__(self, canvas, width, position, color):
self.can, self.w = canvas, width
self.x, self.y = position

self.Object = self.can.create_oval(self.x-self.w, self.y-self.w,
self.x+self.w, self.y+self.w, fill=color)
def update(self, position):
self.x, self.y = position
self.can.coords(self.Object, self.x-self.w, self.y-self.w,
self.x+self.w, self.y+self.w)
def __eq__(self, other):
overlapping = self.can.find_overlapping(self.x-self.w, self.y-self.w,
self.x+self.w, self.y+self.w)
return other.get_object() in overlapping

def get_width(self):
return self.w
def get_position(self):
return self.x, self.y
def get_object(self):
return self.Object

class PuckManager(Equitment):
"""
A black instance of Equitment.
canvas: tk.Canvas object.
width: int, radius of puck.
position: tuple, initial position (x, y).
"""
def __init__(self, canvas, width, position):
Equitment.__init__(self, canvas, width, position, BLACK)

class Paddle(Equitment):
"""
A red instance of Equitment with an extra drawing (handle).
canvas: tk.Canvas object.
width: int, radius of paddle.
position: tuple, initial position (x, y).
"""
def __init__(self, canvas, width, position):
Equitment.__init__(self, canvas, width, position, RED)
self.handle = self.can.create_oval(self.x-self.w/2, self.y-self.w/2,
self.x+self.w/2, self.y+self.w/2, fill=DARK_RED)
def update(self, position):
Equitment.update(self, position)
self.can.coords(self.handle, self.x-self.w/2, self.y-self.w/2,
self.x+self.w/2, self.y+self.w/2)

class Background(object):
"""
canvas: tk.Canvas object.
screen: tuple, screen size (w, h).
goal_w: int, width of the goal.
"""
def __init__(self, canvas, screen, goal_w):
self.can, self.goal_w = canvas, goal_w
self.w, self.h = screen

self.draw_bg()

def draw_bg(self):
self.can.config(bg=WHITE, width=self.w, height=self.h)
#middle circle
d = self.goal_w/4
self.can.create_oval(self.w/2-d, self.h/2-d, self.w/2+d, self.h/2+d,
fill=WHITE, outline=BLUE)
self.can.create_line(ZERO, self.h/2, self.w, self.h/2, fill=BLUE)#middle
self.can.create_line(ZERO, ZERO, ZERO, self.h, fill=BLUE) #left
self.can.create_line(self.w, ZERO, self.w, self.h, fill=BLUE) #right
#top
self.can.create_line(ZERO, ZERO, self.w/2-self.goal_w/2, ZERO,
fill=BLUE)
self.can.create_line(self.w/2+self.goal_w/2, ZERO, self.w, ZERO,
fill=BLUE)
#bottom
self.can.create_line(ZERO, self.h, self.w/2-self.goal_w/2, self.h,
fill=BLUE)
self.can.create_line(self.w/2+self.goal_w/2, self.h, self.w, self.h,
fill=BLUE)

def is_position_valid(self, position, width, constraint=None):
x, y = position
#if puck is in goal, let it keep going in.
if constraint == None and self.is_in_goal(position, width):
return True
elif (x - width < ZERO or x + width > self.w or
y - width < ZERO or y + width > self.h):
return False
elif constraint == LOWER:
return y - width > self.h/2
elif constraint == UPPER:
return y + width < self.h/2
else:
return True

def is_in_goal(self, position, width):
x, y = position
if (y - width <= ZERO and x - width > self.w/2 - self.goal_w/2 and
x + width < self.w/2 + self.goal_w/2):
return HOME
elif (y + width >= self.h and x - width > self.w/2 - self.goal_w/2 and
x + width < self.w/2 + self.goal_w/2):
return AWAY
else:
return False

def get_screen(self):
return self.w, self.h
def get_goal_w(self):
return self.goal_w

class Puck(object):
"""
canvas: tk.Canvas object.
background: Background object.
"""
def __init__(self, canvas, background):
self.background = background
self.screen = self.background.get_screen()
self.x, self.y = self.screen[0]/2, self.screen[1]/2
self.can, self.w = canvas, self.background.get_goal_w()/12
c, d = rand() #generate psuedorandom directions.
self.vx, self.vy = 4*c, 6*d
self.a = .99 #friction
self.cushion = self.w*0.25

self.puck = PuckManager(canvas, self.w, (self.y, self.x))

def update(self):
#air hockey table - puck never completely stops.
if self.vx > 0.25: self.vx *= self.a
if self.vy > 0.25: self.vy *= self.a

x, y = self.x + self.vx, self.y + self.vy
if not self.background.is_position_valid((x, y), self.w):
if x - self.w < ZERO or x + self.w > self.screen[0]:
self.vx *= -1
if y - self.w < ZERO or y + self.w > self.screen[1]:
self.vy *= -1
x, y = self.x+self.vx, self.y+self.vy

self.x, self.y = x, y
self.puck.update((self.x, self.y))

def hit(self, paddle, moving):
x, y = paddle.get_position()

if moving:
if (x > self.x - self.cushion and x < self.x + self.cushion or
abs(self.vx) > MAX_SPEED):
xpower = 1
else:
xpower = 5 if self.vx < 2 else 2
if (y > self.y - self.cushion and y < self.y + self.cushion or
abs(self.vy) > MAX_SPEED):
ypower = 1
else:
ypower = 5 if self.vy < 2 else 2
else:
xpower, ypower = 1, 1

if self.x + self.cushion < x:
xpower *= -1
if self.y + self.cushion < y:
ypower *= -1

self.vx = abs(self.vx)*xpower
self.vy = abs(self.vy)*ypower

def __eq__(self, other):
return other == self.puck
def in_goal(self):
return self.background.is_in_goal((self.x, self.y), self.w)

class Player(object):
"""
master: tk.Tk object.
canvas: tk.Canvas object.
background: Background object.
puck: Puck object.
constraint: UPPER or LOWER (can be None).
"""
def __init__(self, master, canvas, background, puck, constraint):
self.puck, self.background = puck, background
self.constraint, self.v = constraint, PADDLE_SPEED
screen = self.background.get_screen()
self.x = screen[0]/2
self.y = 60 if self.constraint == UPPER else screen[1] - 50

self.paddle = Paddle(canvas, self.background.get_goal_w()/7,
(self.x, self.y))
self.up, self.down, self.left, self.right = False, False, False, False

if self.constraint == LOWER:
master.bind('<Up>', self.MoveUp)
master.bind('<Down>', self.MoveDown)
master.bind('<KeyRelease-Up>', self.UpRelease)
master.bind('<KeyRelease-Down>', self.DownRelease)
master.bind('<Right>', self.MoveRight)
master.bind('<Left>', self.MoveLeft)
master.bind('<KeyRelease-Right>', self.RightRelease)
master.bind('<KeyRelease-Left>', self.LeftRelease)
else:
master.bind('<w>', self.MoveUp)
master.bind('<s>', self.MoveDown)
master.bind('<KeyRelease-w>', self.UpRelease)
master.bind('<KeyRelease-s>', self.DownRelease)
master.bind('<d>', self.MoveRight)
master.bind('<a>', self.MoveLeft)
master.bind('<KeyRelease-d>', self.RightRelease)
master.bind('<KeyRelease-a>', self.LeftRelease)

def update(self):
x, y = self.x, self.y

if self.up: y = self.y - self.v
if self.down: y = self.y + self.v
if self.left: x = self.x - self.v
if self.right: x = self.x + self.v

if self.background.is_position_valid((x, y),
self.paddle.get_width(), self.constraint):
self.x, self.y = x, y
self.paddle.update((self.x, self.y))
if self.puck == self.paddle:
moving = any((self.up, self.down, self.left, self.right))
self.puck.hit(self.paddle, moving)

def MoveUp(self, callback=False):
self.up = True
def MoveDown(self, callback=False):
self.down = True
def MoveLeft(self, callback=False):
self.left = True
def MoveRight(self, callback=False):
self.right = True
def UpRelease(self, callback=False):
self.up = False
def DownRelease(self, callback=False):
self.down = False
def LeftRelease(self, callback=False):
self.left = False
def RightRelease(self, callback=False):
self.right = False

class Home(object):
"""
Game Manager.
master: tk.Tk object.
screen: tuple, screen size (w, h).
score: dict.
"""
def __init__(self, master, screen, score=START_SCORE.copy()):
self.frame = tk.Frame(master)
self.frame.pack()
self.can = tk.Canvas(self.frame)
self.can.pack()
#goal width = 1/3 of screen width
background = Background(self.can, screen, screen[0]*0.33)
self.puck = Puck(self.can, background)
self.p1 = Player(master, self.can, background, self.puck, UPPER)
self.p2 = Player(master, self.can, background, self.puck, LOWER)

master.bind("<Return>", self.reset)
master.bind("<r>", self.reset)

master.title(str_dict(score))

self.master, self.screen, self.score = master, screen, score

self.update()

def reset(self, callback=False):
""" <Return> or <r> key. """
if callback.keycode == 82: #r key resets score.
self.score = START_SCORE.copy()
self.frame.destroy()
self.__init__(self.master, self.screen, self.score)

def update(self):
self.puck.update()
self.p1.update()
self.p2.update()
if not self.puck.in_goal():
self.frame.after(SPEED, self.update)
else:
winner = HOME if self.puck.in_goal() == AWAY else AWAY
self.update_score(winner)

def update_score(self, winner):
self.score[winner] += 1
self.master.title(str_dict(self.score))
if self.score[winner] == MAX_SCORE:
self.frame.bell()
self.can.create_text(self.screen[0]/2, self.screen[1]/2, font=FONT,
text="%s wins!" % winner)
self.score = START_SCORE.copy()
else:
self.can.create_text(self.screen[0]/2, self.screen[1]/2, font=FONT,
text="Point for %s" % winner)

def play(screen):
""" screen: tuple, screen size (w, h). """
root = tk.Tk()
#    root.state("zoomed")
#    root.resizable(0, 0)
Home(root, screen)
#root.eval('tk::PlaceWindow %s center' %root.winfo_pathname(root.winfo_id()))
root.mainloop()

if __name__ == "__main__":
""" Choose screen size """
screen = 700, 760

play(screen)

# data[].attributes.body
import pygame
import random

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
RED      = ( 255,   0,   0)
BLUE     = (   0,   0, 255)

# --- Classes

class Block(pygame.sprite.Sprite):
""" This class represents the block. """
def __init__(self, color):
# Call the parent class (Sprite) constructor
super().__init__()

self.image = pygame.Surface([20, 15])
self.image.fill(color)

self.rect = self.image.get_rect()

class Player(pygame.sprite.Sprite):
""" This class represents the Player. """

def __init__(self):
""" Set up the player on creation. """
# Call the parent class (Sprite) constructor
super().__init__()

self.image = pygame.Surface([20, 20])
self.image.fill(RED)

self.rect = self.image.get_rect()

def update(self):
""" Update the player's position. """
# Get the current mouse position. This returns the position
# as a list of two numbers.
pos = pygame.mouse.get_pos()

# Set the player x position to the mouse x position
self.rect.x = pos[0]

class Bullet(pygame.sprite.Sprite):
""" This class represents the bullet . """
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()

self.image = pygame.Surface([4, 10])
self.image.fill(BLACK)

self.rect = self.image.get_rect()

def update(self):
""" Move the bullet. """
self.rect.y -= 3

# --- Create the window

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])

# --- Sprite lists

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# List of each block in the game
block_list = pygame.sprite.Group()

# List of each bullet
bullet_list = pygame.sprite.Group()

# --- Create the sprites

for i in range(50):
# This represents a block
block = Block(BLUE)

# Set a random location for the block
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(350)

# Add the block to the list of objects
block_list.add(block)
all_sprites_list.add(block)

# Create a red player block
player = Player()
all_sprites_list.add(player)

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0
player.rect.y = 370

# -------- Main Program Loop -----------
while not done:
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

elif event.type == pygame.MOUSEBUTTONDOWN:
# Fire a bullet if the user clicks the mouse button
bullet = Bullet()
# Set the bullet so it is where the player is
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
# Add the bullet to the lists
all_sprites_list.add(bullet)
bullet_list.add(bullet)

# --- Game logic

# Call the update() method on all the sprites
all_sprites_list.update()

# Calculate mechanics for each bullet
for bullet in bullet_list:

# See if it hit a block
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

# For each block hit, remove the bullet and add to the score
for block in block_hit_list:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 1
print(score)

# Remove the bullet if it flies up off the screen
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)

# --- Draw a frame

# Clear the screen
screen.fill(WHITE)

# Draw all the spites
all_sprites_list.draw(screen)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# --- Limit to 20 frames per second
clock.tick(60)

pygame.quit()

# data[].attributes.body
# Import a library of functions called 'pygame'
import pygame
import random

# Initialize the game engine
pygame.init()

BLACK = [  0,   0,   0]
WHITE = [255, 255, 255]

# Set the height and width of the screen
SIZE = [400, 400]

screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Snow Animation")

# Create an empty array
snow_list = []

# Loop 50 times and add a snow flake in a random x,y position
for i in range(50):
x = random.randrange(0, 400)
y = random.randrange(0, 400)
snow_list.append([x, y])

clock = pygame.time.Clock()

#Loop until the user clicks the close button.
done = False
while done == False:

for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

# Set the screen background
screen.fill(BLACK)

# Process each snow flake in the list
for i in range(len(snow_list)):

# Draw the snow flake
pygame.draw.circle(screen, WHITE, snow_list[i], 2)

# Move the snow flake down one pixel
snow_list[i][1] += 1

# If the snow flake has moved off the bottom of the screen
if snow_list[i][1] > 400:
# Reset it just above the top
y = random.randrange(-50, -10)
snow_list[i][1] = y
# Give it a new x position
x = random.randrange(0, 400)
snow_list[i][0] = x

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(20)

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()

# data[].attributes.body
import pygame

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

pygame.init()

# Set the height and width of the screen
size = [700, 500]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Instruction Screen")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Starting position of the rectangle
rect_x = 50
rect_y = 50

# Speed and direction of rectangle
rect_change_x = 5
rect_change_y = 5

# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)

display_instructions = True
instruction_page = 1

# -------- Instruction Page Loop -----------
while not done and display_instructions:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
instruction_page += 1
if instruction_page == 3:
display_instructions = False

# Set the screen background
screen.fill(BLACK)

if instruction_page == 1:
# Draw instructions, page 1
# This could also load an image created in another program.
# That could be both easier and more flexible.

text = font.render("Instructions", True, WHITE)
screen.blit(text, [10, 10])

text = font.render("Page 1", True, WHITE)
screen.blit(text, [10, 40])

if instruction_page == 2:
# Draw instructions, page 2
text = font.render("This program bounces a rectangle", True, WHITE)
screen.blit(text, [10, 10])

text = font.render("Page 2", True, WHITE)
screen.blit(text, [10, 40])

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

# Set the screen background
screen.fill(BLACK)

# Draw the rectangle
pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50])

# Move the rectangle starting point
rect_x += rect_change_x
rect_y += rect_change_y

# Bounce the ball if needed
if rect_y > 450 or rect_y < 0:
rect_change_y = rect_change_y * -1
if rect_x > 650 or rect_x < 0:
rect_change_x = rect_change_x * -1

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

# data[].attributes.body
# --- Import libraries used for this program

import math
import pygame

# Define some colors
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)

# Size of break-out blocks
block_width = 23
block_height = 15

class Block(pygame.sprite.Sprite):
"""This class represents each block that will get knocked out by the ball
It derives from the "Sprite" class in Pygame """

def __init__(self, color, x, y):
""" Constructor. Pass in the color of the block,
and its x and y position. """

# Call the parent class (Sprite) constructor
super().__init__()

# Create the image of the block of appropriate size
# The width and height are sent as a list for the first parameter.
self.image = pygame.Surface([block_width, block_height])

# Fill the image with the appropriate color
self.image.fill(color)

# Fetch the rectangle object that has the dimensions of the image
self.rect = self.image.get_rect()

# Move the top left of the rectangle to x,y.
# This is where our block will appear..
self.rect.x = x
self.rect.y = y

class Ball(pygame.sprite.Sprite):
""" This class represents the ball
It derives from the "Sprite" class in Pygame """

# Speed in pixels per cycle
speed = 10.0

# Floating point representation of where the ball is
x = 0.0
y = 180.0

# Direction of ball (in degrees)
direction = 200

width = 10
height = 10

# Constructor. Pass in the color of the block, and its x and y position
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()

# Create the image of the ball
self.image = pygame.Surface([self.width, self.height])

# Color the ball
self.image.fill(white)

# Get a rectangle object that shows where our image is
self.rect = self.image.get_rect()

# Get attributes for the height/width of the screen
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

def bounce(self, diff):
""" This function will bounce the ball
off a horizontal surface (not a vertical one) """

self.direction = (180 - self.direction) % 360
self.direction -= diff

def update(self):
""" Update the position of the ball. """
# Sine and Cosine work in degrees, so we have to convert them
direction_radians = math.radians(self.direction)

# Change the position (x and y) according to the speed and direction
self.x += self.speed * math.sin(direction_radians)
self.y -= self.speed * math.cos(direction_radians)

# Move the image to where our x and y are
self.rect.x = self.x
self.rect.y = self.y

# Do we bounce off the top of the screen?
if self.y <= 0:
self.bounce(0)
self.y = 1

# Do we bounce off the left of the screen?
if self.x <= 0:
self.direction = (360 - self.direction) % 360
self.x = 1

# Do we bounce of the right side of the screen?
if self.x > self.screenwidth - self.width:
self.direction = (360 - self.direction) % 360
self.x = self.screenwidth - self.width - 1

# Did we fall off the bottom edge of the screen?
if self.y > 600:
return True
else:
return False

class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """

def __init__(self):
""" Constructor for Player. """
# Call the parent's constructor
super().__init__()

self.width = 75
self.height = 15
self.image = pygame.Surface([self.width, self.height])
self.image.fill((white))

# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

self.rect.x = 0
self.rect.y = self.screenheight-self.height

def update(self):
""" Update the player position. """
# Get where the mouse is
pos = pygame.mouse.get_pos()
# Set the left side of the player bar to the mouse position
self.rect.x = pos[0]
# Make sure we don't push the player paddle
# off the right side of the screen
if self.rect.x > self.screenwidth - self.width:
self.rect.x = self.screenwidth - self.width

# Call this function so the Pygame library can initialize itself
pygame.init()

# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])

# Set the title of the window
pygame.display.set_caption('Breakout')

# Enable this to make the mouse disappear when over our window
pygame.mouse.set_visible(0)

# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)

# Create a surface we can draw on
background = pygame.Surface(screen.get_size())

# Create sprite lists
blocks = pygame.sprite.Group()
balls = pygame.sprite.Group()
allsprites = pygame.sprite.Group()

# Create the player paddle object
player = Player()
allsprites.add(player)

# Create the ball
ball = Ball()
allsprites.add(ball)
balls.add(ball)

# The top of the block (y position)
top = 80

# Number of blocks to create
blockcount = 32

# --- Create blocks

# Five rows of blocks
for row in range(5):
# 32 columns of blocks
for column in range(0, blockcount):
# Create a block (color,x,y)
block = Block(blue, column * (block_width + 2) + 1, top)
blocks.add(block)
allsprites.add(block)
# Move the top of the next row down
top += block_height + 2

# Clock to limit speed
clock = pygame.time.Clock()

# Is the game over?
game_over = False

# Exit the program?
exit_program = False

# Main program loop
while exit_program != True:

# Limit to 30 fps
clock.tick(30)

# Clear the screen
screen.fill(black)

# Process the events in the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_program = True

# Update the ball and player position as long
# as the game is not over.
if not game_over:
# Update the player and ball positions
player.update()
game_over = ball.update()

# If we are done, print game over
if game_over:
text = font.render("Game Over", True, white)
textpos = text.get_rect(centerx=background.get_width()/2)
textpos.top = 300
screen.blit(text, textpos)

# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player, balls, False):
# The 'diff' lets you try to bounce the ball left or right
# depending where on the paddle you hit it
diff = (player.rect.x + player.width/2) - (ball.rect.x+ball.width/2)

# Set the ball's y position in case
# we hit the ball on the edge of the paddle
ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1
ball.bounce(diff)

# Check for collisions between the ball and the blocks
deadblocks = pygame.sprite.spritecollide(ball, blocks, True)

# If we actually hit a block, bounce the ball
if len(deadblocks) > 0:
ball.bounce(0)

# Game ends if all the blocks are gone
if len(blocks) == 0:
game_over = True

# Draw Everything
allsprites.draw(screen)

# Flip the screen and show what we've drawn
pygame.display.flip()

pygame.quit()

# data[].attributes.body
from random import randrange
from turtle import *
from freegames import vector

ball = vector(-200, -200)
speed = vector(0, 0)
targets = []

def tap(x, y):
"Respond to screen tap."
if not inside(ball):
ball.x = -199
ball.y = -199
speed.x = (x + 200) / 25
speed.y = (y + 200) / 25

def inside(xy):
"Return True if xy within screen."
return -200 < xy.x < 200 and -200 < xy.y < 200

def draw():
"Draw ball and targets."
clear()

for target in targets:
goto(target.x, target.y)
dot(20, 'blue')

if inside(ball):
goto(ball.x, ball.y)
dot(6, 'red')

update()

def move():
"Move ball and targets."
if randrange(40) == 0:
y = randrange(-150, 150)
target = vector(200, y)
targets.append(target)

for target in targets:
target.x -= 0.5

if inside(ball):
speed.y -= 0.35
ball.move(speed)

dupe = targets.copy()
targets.clear()

for target in dupe:
if abs(target - ball) > 13:
targets.append(target)

draw()

for target in targets:
if not inside(target):
return

ontimer(move, 50)

setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

# data[].attributes.body
import pygame
import random
import math

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
RED      = ( 255,   0,   0)

class Block(pygame.sprite.Sprite):
""" This class represents the ball that moves in a circle. """

def __init__(self, color, width, height):
""" Constructor that create's the ball's image. """
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()

# The "center" the sprite will orbit
self.center_x = 0
self.center_y = 0

# Current angle in radians
self.angle = 0

# How far away from the center to orbit, in pixels
self.radius = 0

# How fast to orbit, in radians per frame
self.speed = 0.05

def update(self):
""" Update the ball's position. """
# Calculate a new x, y
self.rect.x = self.radius * math.sin(self.angle) + self.center_x
self.rect.y = self.radius * math.cos(self.angle) + self.center_y

# Increase the angle in prep for the next round.
self.angle += self.speed

class Player(pygame.sprite.Sprite):
""" Class to represent the player. """
def __init__(self, color, width, height):
""" Create the player image. """
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()

def update(self):
"""Set the user to be where the mouse is. """
pos = pygame.mouse.get_pos()
self.rect.x = pos[0]
self.rect.y = pos[1]

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

for i in range(50):
# This represents a block
block = Block(BLACK, 20, 15)

# Set a random center location for the block to orbit
block.center_x = random.randrange(SCREEN_WIDTH)
block.center_y = random.randrange(SCREEN_HEIGHT)
# Random radius from 10 to 200
block.radius = random.randrange(10, 200)
# Random start angle from 0 to 2pi
block.angle = random.random() * 2 * math.pi
# radians per frame
block.speed = 0.008
# Add the block to the list of objects
block_list.add(block)
all_sprites_list.add(block)

# Create a RED player block
player = Player(RED, 20, 15)
all_sprites_list.add(player)

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

all_sprites_list.update()

# Clear the screen
screen.fill(WHITE)

# See if the player block has collided with anything.
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

# Check the list of collisions.
for block in blocks_hit_list:
score += 1
print( score )

# Draw all the spites
all_sprites_list.draw(screen)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Limit to 60 frames per second
clock.tick(60)

pygame.quit()

# data[].attributes.body
import random
min = 1
max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":
print ("Rolling the dices...")
print ("The values are....")
print( random.randint(min, max))
print (random.randint(min, max))

roll_again = input("Roll the dices again?: ")

# data[].attributes.body
import pygame

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)

# This sets the width and height of each grid location
width  = 20
height = 20

# This sets the margin between each cell
margin = 5

# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = []
for row in range(10):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(10):
grid[row].append(0) # Append a cell

# Set row 1, cell 5 to one. (Remember rows and
# column numbers start at zero.)
grid[1][5] = 1

# Initialize pygame
pygame.init()

# Set the height and width of the screen
size = [255, 255]
screen = pygame.display.set_mode(size)

# Set title of screen
pygame.display.set_caption("Array Backed Grid")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while done == False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
# User clicks the mouse. Get the position
pos = pygame.mouse.get_pos()
# Change the x/y screen coordinates to grid coordinates
column = pos[0] // (width + margin)
row = pos[1] // (height + margin)
# Set that location to zero
grid[row][column] = 1
print("Click ", pos, "Grid coordinates: ", row, column)

# Set the screen background
screen.fill(BLACK)

# Draw the grid
for row in range(10):
for column in range(10):
color = WHITE
if grid[row][column] == 1:
color = GREEN
pygame.draw.rect(screen,
color,
[(margin+width)*column+margin,
(margin+height)*row+margin,
width,
height])

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

# data[].attributes.body
from random import *
from turtle import *
from freegames import vector

bird = vector(0, 0)
balls = []

def tap(x, y):
"Move bird up in response to screen tap."
up = vector(0, 30)
bird.move(up)

def inside(point):
"Return True if point on screen."
return -200 < point.x < 200 and -200 < point.y < 200

def draw(alive):
"Draw screen objects."
clear()

goto(bird.x, bird.y)

if alive:
dot(10, 'green')
else:
dot(10, 'red')

for ball in balls:
goto(ball.x, ball.y)
dot(20, 'black')

update()

def move():
"Update object positions."
bird.y -= 5

for ball in balls:
ball.x -= 3

if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
balls.append(ball)

while len(balls) > 0 and not inside(balls[0]):
balls.pop(0)

if not inside(bird):
draw(False)
return

for ball in balls:
if abs(ball - bird) < 15:
draw(False)
return

draw(True)
ontimer(move, 50)

setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

# data[].attributes.body
import random

games = 0
won = 0
lost = 0
tie = 0
choice = "Y"
while choice != 'N':
ans = int(input('Enter 1-Rock 2- Paper 3 -Scissor : '))
comp = random.randint(1, 3)
if ans == comp:
print("tie !!!!!!!!!!!!!!!!")
tie += 1
if ans == 1:
if(comp == 3):
print("You won")
won += 1
elif(comp == 2):
print("You lost")
lost += 1
if(ans == 2):
if(comp == 1):
print("You won")
won += 1
elif(comp == 3):
print("You lost")
lost += 1
if(ans == 3):
if(comp == 2):
print("You won")
won += 1
elif(comp == 1):
print("You lost")
lost += 1
games += 1
choice = input("Want to play more( Y/N) :").upper()

print('\n\n\n Simple stat of this Game \n')
print(' Total guess  :', games)
print("You won Games :", won)
print("You lost Games :", lost)
print("Tie Games :", tie)

# data[].attributes.headline
Menu driven of Tic Tac Toe & Stone Paper Scissor

# data[].attributes.subject
Menu driven of Tic Tac Toe & Stone Paper Scissor

# data[].attributes.body
import os
import time
import random

def welcome():
for i in range(0, 11):
print("*", end="")
print()
print("* WELCOME *", end="")
print()
for i in range(0, 11):
print("*", end="")
print()
input("Press ENTER key to start")
option()

def option():
for i in range(0, 21):
print("*", end="")
print()
print("1)StonePaperScissors\n2)TicTacToe")
for i in range(0, 21):
print("*", end="")
print()
chc = int(input("Enter your choice number: "))
if chc == 1:
stonepaperscissor()
elif chc == 2:
tictactoemenu()
else:
welcome()

def stonepaperscissor():
print("STONE,PAPER,SCISSORS")
print("You will be competing against the computer")
print("The competitor who first scores 5 points will be declared as the winner")
print("For Stone,Enter 0")
print("For Paper,Enter 1")
print("For Scissors,Enter 2")
print("To EndGame and go back to MainMenu,Enter -1")
user = 0
comp = 0
cnt = 0
choice_play = ["Stone", "Paper", "Scissors"]
while user < 5 and comp < 5 and cnt < 25:
cnt += 1
a = int(input("Enter your choice="))
for i in range(0, 20):
print("*", end="")
print()
if a == -1:
print("Thankyou For Playing")
welcome()
break
b = random.choice([0, 1, 2])
if a == 0 and b == 1:
comp += 1
elif a == 0 and b == 2:
user += 1
elif a == 1 and b == 0:
user += 1
elif a == 1 and b == 2:
comp += 1
elif a == 2 and b == 0:
comp += 1
elif a == 2 and b == 1:
user += 1
print("You:", choice_play[a])
print("Computer:", choice_play[b])
print("Scores")
print("You=", user, "\t Computer=", comp)
for i in range(0, 20):
print("*", end="")
print()
if(user > comp and user == 5):
print("Congratulations!!You are the Winner!")
elif(user < comp and comp == 5):
print("Sorry!!Better luck next time!")
elif(user == comp and cnt >= 25):
print("Its a Draw")

def tictactoemenu():
print("Welcome To TicTacToe")
for i in range(0, 21):
print("*", end="")
print()
print("1)TwoPlayer\n2)OnePlayer")
for i in range(0, 21):
print("*", end="")
print()
chc = int(input("Enter your choice number: "))
if chc == 1:
two_player()
elif chc == 2:
single_player()
else:
option()

def two_player():
board = ["", " ", " ", " ", " ", " ", " ", " ", " ", " "]

def rules():
print("Welcome to TICTACTOE")
print("This is a two player game where USER1 is X and USER2 is O")
print("Enter your choice from 1 to 9")
print("""
1 | 2 | 3
---|---|---
4 | 5 | 6
---|---|---
7 | 8 | 9
""")

def print_board():
print("   |   |   ")
print(" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print("   |   |   ")
print("---|---|---")
print("   |   |   ")
print(" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print("   |   |   ")
print("---|---|---")
print("   |   |   ")
print(" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print("   |   |   ")

def is_winner(board, player):
if (board[1] == player and board[2] == player and board[3] == player) or \
(board[4] == player and board[5] == player and board[6] == player) or \
(board[7] == player and board[8] == player and board[9] == player) or \
(board[1] == player and board[4] == player and board[7] == player) or \
(board[2] == player and board[5] == player and board[8] == player) or \
(board[3] == player and board[6] == player and board[9] == player) or \
(board[1] == player and board[5] == player and board[9] == player) or \
(board[3] == player and board[5] == player and board[7] == player):
return True
else:
return False

def is_board_full(board):
if " " in board:
return False
else:
return True

while True:
os.system("clear")
rules()
print_board()

# user 1
choice = input("Please choose an empty space for X: ")
choice = int(choice)
if board[choice] == " ":
board[choice] = "X"
else:
print("Spot already taken")
time.sleep(1)
# for user 1 to win
if is_winner(board, "X"):
os.system("clear")
rules()
print_board()
print("USER1 Win")
break

os.system("clear")
rules()
print_board()

# check if board is full i.e. a tie
if is_board_full(board):
print("Tie")
break

# user 2
choice = input("Please choose an empty space for O: ")
choice = int(choice)
if board[choice] == " ":
board[choice] = "O"
else:
print("Spot already taken")
time.sleep(1)
# for user 2 to win
if is_winner(board, "O"):
os.system("clear")
rules()
print_board()
print("USER2 Win")
break

# check if board is full i.e. a tie
if is_board_full(board):
print("Tie")
break

def single_player():
board = ["", " ", " ", " ", " ", " ", " ", " ", " ", " "]

def rules():
print("Welcome to TICTACTOE")
print("This is a single player game where You are X and Computer is O")
print("Enter your choice from 1 to 9")
print("""
1 | 2 | 3
---|---|---
4 | 5 | 6
---|---|---
7 | 8 | 9
""")

def print_board():
print("   |   |   ")
print(" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print("   |   |   ")
print("---|---|---")
print("   |   |   ")
print(" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print("   |   |   ")
print("---|---|---")
print("   |   |   ")
print(" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print("   |   |   ")

def is_winner(board, player):
if (board[1] == player and board[2] == player and board[3] == player) or \
(board[4] == player and board[5] == player and board[6] == player) or \
(board[7] == player and board[8] == player and board[9] == player) or \
(board[1] == player and board[4] == player and board[7] == player) or \
(board[2] == player and board[5] == player and board[8] == player) or \
(board[3] == player and board[6] == player and board[9] == player) or \
(board[1] == player and board[5] == player and board[9] == player) or \
(board[3] == player and board[5] == player and board[7] == player):
return True
else:
return False

def is_board_full(board):
if " " in board:
return False
else:
return True

def get_computer_move(board, player):

# check for a win
for i in range(1, 10):
if board[i] == " ":
board[i] = player
if is_winner(board, player):
return i
else:
board[i] = " "

# check for column block
for i in [1, 2, 3]:
if board[i] == "X" and board[i+3] == "X" and board[i+6] == " ":
return i+6
if board[i+3] == "X" and board[i+6] == "X" and board[i] == " ":
return i
if board[i] == "X" and board[i+6] == "X" and board[i+3] == " ":
return i+3

# check for rows blocks
for i in [1, 4, 7]:
if board[i] == "X" and board[i+1] == "X" and board[i+2] == " ":
return i+2
if board[i+1] == "X" and board[i+2] == "X" and board[i] == " ":
return i
if board[i] == "X" and board[i+2] == "X" and board[i+1] == " ":
return i+1

# check diagonal block
if board[1] == "X" and board[5] == "X" and board[9] == " ":
return 9
if board[9] == "X" and board[5] == "X" and board[1] == " ":
return 1
if board[1] == "X" and board[9] == "X" and board[5] == " ":
return 5
if board[3] == "X" and board[5] == "X" and board[7] == " ":
return 7
if board[7] == "X" and board[5] == "X" and board[3] == " ":
return 3
if board[3] == "X" and board[7] == "X" and board[5] == " ":
return 5

if board[5] == " ":
return 5
while True:
move = random.randint(1, 9)
if board[move] == " ":
return move
break
return 5

while True:
os.system("clear")
rules()
print_board()

# user 1
choice = input("Please choose an empty space for X: ")
choice = int(choice)
if board[choice] == " ":
board[choice] = "X"
else:
print("Spot already taken")
time.sleep(1)
# for user 1 to win
if is_winner(board, "X"):
os.system("clear")
rules()
print_board()
print("Congratulations!!You Win")
break

os.system("clear")
rules()
print_board()

# check if board is full i.e. a tie
if is_board_full(board):
print("Tie")
break

# user 2
choice = get_computer_move(board, "O")
if board[choice] == " ":
board[choice] = "O"
else:
print("Spot already taken")
time.sleep(1)
# for user 2 to win
if is_winner(board, "O"):
os.system("clear")
rules()
print_board()
print("Sorry!!COMPUTER Wins")
break

# check if board is full i.e. a tie
if is_board_full(board):
print("Tie")
break

welcome()
print("\n")
option()

# data[].attributes.body
from random import sample, shuffle

digits = 3
guesses = 10

print('I am thinking of a', digits, 'digit number.')
print('Try to guess what it is.')
print('Here are some clues:')
print('When I say:    That means:')
print('  pico         One digit is correct but in the wrong position.')
print('  fermi        One digit is correct and in the right position.')
print('  bagels       No digit is correct.')
print('There are no repeated digits in the number.')

# Create a random number.

letters = sample('0123456789', digits)

if letters[0] == '0':
letters.reverse()

number = ''.join(letters)

print('I have thought up a number.')
print('You have', guesses, 'guesses to get it.')

counter = 1

while True:
print('Guess #', counter)
guess = input()

if len(guess) != digits:
print('Wrong number of digits. Try again!')
continue

# Create the clues.

clues = []

for index in range(digits):
if guess[index] == number[index]:
clues.append('fermi')
elif guess[index] in number:
clues.append('pico')

shuffle(clues)

if len(clues) == 0:
print('bagels')
else:
print(' '.join(clues))

counter += 1

if guess == number:
print('You got it!')
break

if counter > guesses:
print('You ran out of guesses. The answer was', number)
break

# data[].attributes.body
# Python Program to illustrate
# Hangman Game
import random
from collections import Counter

someWords = '''apple banana mango strawberry
orange grape pineapple apricot lemon coconut watermelon
cherry papaya berry peach lychee dragonfruit '''

someWords = someWords.split(' ')
# randomly choose a secret word from our "someWords" LIST.
word = random.choice(someWords)

if __name__ == '__main__':
print('Guess the word! HINT: word is a name of a fruit')

for i in word:
# For printing the empty spaces for letters of the word
print('_', end = ' ')
print()

playing = True
# list for storing the letters guessed by the player
letterGuessed = ''
chances = len(word) + 2
correct = 0
flag = 0
try:
while (chances != 0) and flag == 0: #flag is updated when the word is correctly guessed
print()
chances -= 1

try:
guess = str(input('Enter a letter to guess: '))
except:
print('Enter only a letter!')
continue

# Validation of the guess
if not guess.isalpha():
print('Enter only a LETTER')
continue
elif len(guess) > 1:
print('Enter only a SINGLE letter')
continue
elif guess in letterGuessed:
print('You have already guessed that letter')
continue

# If letter is guessed correctly
if guess in word:
k = word.count(guess) #k stores the number of times the guessed letter occurs in the word
for _ in range(k):
letterGuessed += guess # The guess letter is added as many times as it occurs

# Print the word
for char in word:
if char in letterGuessed and (Counter(letterGuessed) != Counter(word)):
print(char, end = ' ')
correct += 1
# If user has guessed all the letters
elif (Counter(letterGuessed) == Counter(word)): # Once the correct word is guessed fully,
# the game ends, even if chances remain
print("The word is: ", end=' ')
print(word)
flag = 1
print('Congratulations, You won!')
break # To break out of the for loop
break # To break out of the while loop
else:
print('_', end = ' ')

# If user has used all of his chances
if chances <= 0 and (Counter(letterGuessed) != Counter(word)):
print()
print('You lost! Try again..')
print('The word was {}'.format(word))

except KeyboardInterrupt:
print()
print('Bye! Try again.')
exit()

# data[].attributes.body
#                                 Welcome to DataFlair Hangman Game:

import random
import time

# Initial Steps to invite in the game:
print("\nWelcome to Hangman game ")
name = input("Enter your name: ")
print("Hello " + name + "! Best of Luck!")
time.sleep(2)
print("The game is about to start!\n Let's play Hangman!")
time.sleep(3)

# The parameters we require to execute the game:
def main():
global count
global display
global word
global already_guessed
global length
global play_game
words_to_guess = ["january","border","image","film","promise","kids","lungs","doll","rhyme","damage","plants","diary","encyclopedia","dictionary"]
word = random.choice(words_to_guess)
length = len(word)
count = 0
display = '_' * length
already_guessed = []
play_game = ""

# A loop to re-execute the game when the first round ends:

def play_loop():
global play_game
play_game = input("Do You want to play again? y = yes, n = no \n")
while play_game not in ["y", "n","Y","N"]:
play_game = input("Do You want to play again? y = yes, n = no \n")
if play_game == "y":
main()
elif play_game == "n":
print("Thanks For Playing! We expect you back again!")
exit()

# Initializing all the conditions required for the game:
def hangman():
global count
global display
global word
global already_guessed
global play_game
limit = 5
guess = input("This is the Hangman Word: " + display + " Enter your guess: \n")
guess = guess.strip()
if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9":
print("Invalid Input, Try a letter\n")
hangman()

elif guess in word:
already_guessed.extend([guess])
index = word.find(guess)
word = word[:index] + "_" + word[index + 1:]
display = display[:index] + guess + display[index + 1:]
print(display + "\n")

elif guess in already_guessed:
print("Try another letter.\n")

else:
count += 1

if count == 1:
time.sleep(1)
print("   _____ \n"
"  |      \n"
"  |      \n"
"  |      \n"
"  |      \n"
"  |      \n"
"  |      \n"
"_|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")

elif count == 2:
time.sleep(1)
print("   _____ \n"
"  |     | \n"
"  |     |\n"
"  |      \n"
"  |      \n"
"  |      \n"
"  |      \n"
"_|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")

elif count == 3:
time.sleep(1)
print("   _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |      \n"
"  |      \n"
"  |      \n"
"_|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")

elif count == 4:
time.sleep(1)
print("   _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |     O \n"
"  |      \n"
"  |      \n"
"_|__\n")
print("Wrong guess. " + str(limit - count) + " last guess remaining\n")

elif count == 5:
time.sleep(1)
print("   _____ \n"
"  |     | \n"
"  |     |\n"
"  |     | \n"
"  |     O \n"
"  |    /|\ \n"
"  |    / \ \n"
"_|__\n")
print("Wrong guess. You are hanged!!!\n")
print("The word was:",already_guessed,word)
play_loop()

if word == '_' * length:
print("Congrats! You have guessed the word correctly!")
play_loop()

elif count != limit:
hangman()

main()

hangman()

# data[].attributes.body
import sys
import random

ans = True

while ans:
question = input("Ask the magic 8 ball a question: (press enter to quit) :")

answers = random.randint(1,8)

if question == "":
sys.exit()

elif answers == 1:
print ("It is certain")

elif answers == 2:
print ("Outlook good")

elif answers == 3:
print ("You may rely on it")

elif answers == 4:
print( "Ask again later")

elif answers == 5:
print ("Concentrate and ask again")

elif answers == 6:
print( "Reply hazy, try again")

elif answers == 7:
print ("My reply is no")

elif answers == 8:
print ("My sources say no")

# data[].attributes.body
#Take the users input
words =input("Enter some text to translate to pig latin: ")
print( "You entered: "), words

#Now I need to break apart the words into a list
words = words.split(' ')

#Now words is a list, so I can manipulate each one usinga loop

for i in words:
if len(i) >= 3: #I only want to translate words greater than 3 characters
i = i + "%say" % (i[0])
i = i[1:]
print(i)
else:
pass

# data[].attributes.body
import pygame

# Global constants

# Colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
BLUE     = (   0,   0, 255)
RED      = ( 255,   0,   0)
GREEN    = (   0, 255,   0)

# Screen dimensions
SCREEN_WIDTH  = 800
SCREEN_HEIGHT = 600

class Player(pygame.sprite.Sprite):
"""
This class represents the bar at the bottom that the player controls.
"""

# -- Methods
def __init__(self):
""" Constructor function """

# Call the parent's constructor
super().__init__()

# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
width = 40
height = 60
self.image = pygame.Surface([width, height])
self.image.fill(RED)

# Set a referance to the image rect.
self.rect = self.image.get_rect()

# Set speed vector of player
self.change_x = 0
self.change_y = 0

# List of sprites we can bump against
self.level = None

def update(self):
""" Move the player. """
# Gravity
self.calc_grav()

# Move left/right
self.rect.x += self.change_x

# See if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# If we are moving right,
# set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
elif self.change_x < 0:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right

# Move up/down
self.rect.y += self.change_y

# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:

# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
elif self.change_y < 0:
self.rect.top = block.rect.bottom

# Stop our vertical movement
self.change_y = 0

if isinstance(block, MovingPlatform):
self.rect.x += block.change_x

def calc_grav(self):
""" Calculate effect of gravity. """
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += .35

# See if we are on the ground.
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height

def jump(self):
""" Called when user hits 'jump' button. """

# move down a bit and see if there is a platform below us.
# Move down 2 pixels because it doesn't work well if we only move down 1
# when working with a platform moving down.
self.rect.y += 2
platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
self.rect.y -= 2

# If it is ok to jump, set our speed upwards
if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
self.change_y = -10

# Player-controlled movement:
def go_left(self):
""" Called when the user hits the left arrow. """
self.change_x = -6

def go_right(self):
""" Called when the user hits the right arrow. """
self.change_x = 6

def stop(self):
""" Called when the user lets off the keyboard. """
self.change_x = 0

class Platform(pygame.sprite.Sprite):
""" Platform the user can jump on """

def __init__(self, width, height):
""" Platform constructor. Assumes constructed with user passing in
an array of 5 numbers like what's defined at the top of this code.
"""
super().__init__()

self.image = pygame.Surface([width, height])
self.image.fill(GREEN)

self.rect = self.image.get_rect()

class MovingPlatform(Platform):
""" This is a fancier platform that can actually move. """
change_x = 0
change_y = 0

boundary_top = 0
boundary_bottom = 0
boundary_left = 0
boundary_right = 0

player = None

level = None

def update(self):
""" Move the platform.
If the player is in the way, it will shove the player
out of the way. This does NOT handle what happens if a
platform shoves a player into another object. Make sure
moving platforms have clearance to push the player around
or add code to handle what happens if they don't. """

# Move left/right
self.rect.x += self.change_x

# See if we hit the player
hit = pygame.sprite.collide_rect(self, self.player)
if hit:
# We did hit the player. Shove the player around and
# assume he/she won't hit anything else.

# If we are moving right, set our right side
# to the left side of the item we hit
if self.change_x < 0:
self.player.rect.right = self.rect.left
else:
# Otherwise if we are moving left, do the opposite.
self.player.rect.left = self.rect.right

# Move up/down
self.rect.y += self.change_y

# Check and see if we the player
hit = pygame.sprite.collide_rect(self, self.player)
if hit:
# We did hit the player. Shove the player around and
# assume he/she won't hit anything else.

# Reset our position based on the top/bottom of the object.
if self.change_y < 0:
self.player.rect.bottom = self.rect.top
else:
self.player.rect.top = self.rect.bottom

# Check the boundaries and see if we need to reverse
# direction.
if self.rect.bottom > self.boundary_bottom or self.rect.top < self.boundary_top:
self.change_y *= -1

cur_pos = self.rect.x - self.level.world_shift
if cur_pos < self.boundary_left or cur_pos > self.boundary_right:
self.change_x *= -1

class Level(object):
""" This is a generic super-class used to define a level.
Create a child class for each level with level-specific
info. """

# Lists of sprites used in all levels. Add or remove
# lists as needed for your game.
platform_list = None
enemy_list = None

# Background image
background = None

# How far this world has been scrolled left/right
world_shift = 0
level_limit = -1000

def __init__(self, player):
""" Constructor. Pass in a handle to player. Needed for when moving
platforms collide with the player. """
self.platform_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.player = player

# Update everythign on this level
def update(self):
""" Update everything in this level."""
self.platform_list.update()
self.enemy_list.update()

def draw(self, screen):
""" Draw everything on this level. """

# Draw the background
screen.fill(BLUE)

# Draw all the sprite lists that we have
self.platform_list.draw(screen)
self.enemy_list.draw(screen)

def shift_world(self, shift_x):
""" When the user moves left/right and we need to scroll everything:
"""

# Keep track of the shift amount
self.world_shift += shift_x

# Go through all the sprite lists and shift
for platform in self.platform_list:
platform.rect.x += shift_x

for enemy in self.enemy_list:
enemy.rect.x += shift_x

# Create platforms for the level
class Level_01(Level):
""" Definition for level 1. """

def __init__(self, player):
""" Create level 1. """

# Call the parent constructor
Level.__init__(self, player)

self.level_limit = -1500

# Array with width, height, x, and y of platform
level = [[210, 70, 500, 500],
[210, 70, 800, 400],
[210, 70, 1000, 500],
[210, 70, 1120, 280],
]

# Go through the array above and add platforms
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)

# Add a custom moving platform
block = MovingPlatform(70, 40)
block.rect.x = 1350
block.rect.y = 280
block.boundary_left = 1350
block.boundary_right = 1600
block.change_x = 1
block.player = self.player
block.level = self
self.platform_list.add(block)

# Create platforms for the level
class Level_02(Level):
""" Definition for level 2. """

def __init__(self, player):
""" Create level 1. """

# Call the parent constructor
Level.__init__(self, player)

self.level_limit = -1000

# Array with type of platform, and x, y location of the platform.
level = [[210, 70, 500, 550],
[210, 70, 800, 400],
[210, 70, 1000, 500],
[210, 70, 1120, 280],
]

# Go through the array above and add platforms
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)

# Add a custom moving platform
block = MovingPlatform(70, 70)
block.rect.x = 1500
block.rect.y = 300
block.boundary_top = 100
block.boundary_bottom = 550
block.change_y = -1
block.player = self.player
block.level = self
self.platform_list.add(block)

def main():
""" Main Program """
pygame.init()

# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Platformer with moving platforms")

# Create the player
player = Player()

# Create all the levels
level_list = []
level_list.append(Level_01(player))
level_list.append(Level_02(player))

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# If the player gets near the right side, shift the world left (-x)
if player.rect.right >= 500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)

# If the player gets near the left side, shift the world right (+x)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)

# If the player gets to the end of the level, go to the next level
current_position = player.rect.x + current_level.world_shift
if current_position < current_level.level_limit:
if current_level_no < len(level_list)-1:
player.rect.x = 120
current_level_no += 1
current_level = level_list[current_level_no]
player.level = current_level
else:
# Out of levels. This just exits the program.
# You'll want to do something better.
done = True

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()

# data[].attributes.body
from random import choice, random
from turtle import *
from freegames import vector

def value():
    "Randomly generate value between (-5, -3) or (3, 5)."
    return (3 + random() * 2) * choice([1, -1])

ball = vector(0, 0)
aim = vector(value(), value())
state = {1: 0, 2: 0}

def move(player, change):
    "Move player position by change."
    state[player] += change

def rectangle(x, y, width, height):
    "Draw rectangle at (x, y) with given width and height."
    up()
    goto(x, y)
    down()
    begin_fill()
    for count in range(2):
        forward(width)
        left(90)
        forward(height)
        left(90)
    end_fill()

def draw():
    "Draw game and move pong ball."
    clear()
    rectangle(-200, state[1], 10, 50)
    rectangle(190, state[2], 10, 50)

    ball.move(aim)
    x = ball.x
    y = ball.y

    up()
    goto(x, y)
    dot(10)
    update()

    if y < -200 or y > 200:
        aim.y = -aim.y

    if x < -185:
        low = state[1]
        high = state[1] + 50

        if low <= y <= high:
            aim.x = -aim.x
        else:
            return

    if x > 185:
        low = state[2]
        high = state[2] + 50

        if low <= y <= high:
            aim.x = -aim.x
        else:
            return

    ontimer(draw, 50)

setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: move(1, 20), 'w')
onkey(lambda: move(1, -20), 's')
onkey(lambda: move(2, 20), 'i')
onkey(lambda: move(2, -20), 'k')
draw()
done()

# data[].attributes.body
from random import *
from turtle import *
from freegames import floor, vector

tiles = {}
neighbors = [
vector(100, 0),
vector(-100, 0),
vector(0, 100),
vector(0, -100),
]

def load():
"Load tiles and scramble."
count = 1

for y in range(-200, 200, 100):
for x in range(-200, 200, 100):
mark = vector(x, y)
tiles[mark] = count
count += 1

tiles[mark] = None

for count in range(1000):
neighbor = choice(neighbors)
spot = mark + neighbor

if spot in tiles:
number = tiles[spot]
tiles[spot] = None
tiles[mark] = number
mark = spot

def square(mark, number):
"Draw white square with black outline and number."
up()
goto(mark.x, mark.y)
down()

color('black', 'white')
begin_fill()
for count in range(4):
forward(99)
left(90)
end_fill()

if number is None:
return
elif number < 10:
forward(20)

write(number, font=('Arial', 60, 'normal'))

def tap(x, y):
"Swap tile and empty square."
x = floor(x, 100)
y = floor(y, 100)
mark = vector(x, y)

for neighbor in neighbors:
spot = mark + neighbor

if spot in tiles and tiles[spot] is None:
number = tiles[mark]
tiles[spot] = number
square(spot, number)
tiles[mark] = None
square(mark, None)

def draw():
"Draw all tiles."
for mark in tiles:
square(mark, tiles[mark])
update()

setup(420, 420, 370, 0)
hideturtle()
tracer(False)
load()
draw()
onscreenclick(tap)
done()

# data[].attributes.body
import pygame
import time
import random

pygame.init()

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Sarang')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])

def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, red, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])

def gameLoop():
game_over = False
game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_List = []
Length_of_snake = 1

foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

while not game_over:

while game_close == True:
dis.fill(black)
message("Try Again! Press C-Play Again or Q-Quit", red)
Your_score(Length_of_snake - 1)
pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()

for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, white, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]

for x in snake_List[:-1]:
if x == snake_Head:
game_close = True

our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)

pygame.display.update()

if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

gameLoop()

# data[].attributes.body
# --------- Global Variables -----------

# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]

# Lets us know if the game is over yet
game_still_going = True

# Tells us who the winner is
winner = None

# Tells us who the current player is (X goes first)
current_player = "X"

# ------------- Functions ---------------

# Play a game of tic tac toe
def play_game():

# Show the initial game board
display_board()

# Loop until the game stops (winner or tie)
while game_still_going:

# Handle a turn
handle_turn(current_player)

# Check if the game is over
check_if_game_over()

# Flip to the other player
flip_player()

# Since the game is over, print the winner or tie
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie.")

# Display the game board to the screen
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + "     1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + "     4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + "     7 | 8 | 9")
print("\n")

# Handle a turn for an arbitrary player
def handle_turn(player):

# Get position from player
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")

# Whatever the user inputs, make sure it is a valid input, and the spot is open
valid = False
while not valid:

# Make sure the input is valid
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Choose a position from 1-9: ")

# Get correct index in our board list
position = int(position) - 1

# Then also make sure the spot is available on the board
if board[position] == "-":
valid = True
else:
print("You can't go there. Go again.")

# Put the game piece on the board
board[position] = player

# Show the game board
display_board()

# Check if the game is over
def check_if_game_over():
check_for_winner()
check_for_tie()

# Check to see if somebody has won
def check_for_winner():
# Set global variables
global winner
# Check if there was a winner anywhere
row_winner = check_rows()
column_winner = check_columns()
diagonal_winner = check_diagonals()
# Get the winner
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None

# Check the rows for a win
def check_rows():
# Set global variables
global game_still_going
# Check if any of the rows have all the same value (and is not empty)
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
# If any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_going = False
# Return the winner
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
# Or return None if there was no winner
else:
return None

# Check the columns for a win
def check_columns():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
column_1 = board[0] == board[3] == board[6] != "-"
column_2 = board[1] == board[4] == board[7] != "-"
column_3 = board[2] == board[5] == board[8] != "-"
# If any row does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_going = False
# Return the winner
if column_1:
return board[0]
elif column_2:
return board[1]
elif column_3:
return board[2]
# Or return None if there was no winner
else:
return None

# Check the diagonals for a win
def check_diagonals():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
# If any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
# Return the winner
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
# Or return None if there was no winner
else:
return None

# Check if there is a tie
def check_for_tie():
# Set global variables
global game_still_going
# If board is full
if "-" not in board:
game_still_going = False
return True
# Else there is no tie
else:
return False

# Flip the current player from X to O, or O to X
def flip_player():
# Global variables we need
global current_player
# If the current player was X, make it O
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"

# ------------ Start Execution -------------
# Play a game of tic tac toe
play_game()

# data[].attributes.body
import math
import random
import tkinter

def odd(n):
return n & 1

def color(a):
return 'green' if odd(a) else 'blue'

class Map:

def __init__(self, master, rows = 15, columns = 60):
self.master = master
self.row = random.randrange(rows)
self.col = random.randrange(columns)
self.cost = 0
self.found = False
Button = tkinter.Button
self.buttons = []
options = dict(text = '??', font = 'Courier 14')
for r in range(rows):
br = []                 # row of buttons
self.buttons.append(br)
for c in range(columns):
b = Button(
master,
command = lambda r=r, c=c: self(r, c),
fg = color(r+c),
**options
)
b.grid(row = r, column = c)
br.append(b)
master.mainloop()

def __bool__(self):
return self.found

def __call__(self, row, col):
if self:
self.master.quit()
distance = int(round(math.hypot(row-self.row, col-self.col)))
self.buttons[row][col].configure(text = '{}'.format(distance), bg = 'yellow', fg = 'red')
self.cost += 1
if not distance:
print('You win!  At the cost of {} sonar devices.'.format(self.cost))
self.found = True

def main():
root = tkinter.Tk()
map = Map(root)
root.destroy()

if __name__ == '__main__':
main()

# data[].attributes.body
import pygame

import constants
import levels

from player import Player

def main():
""" Main Program """
pygame.init()

# Set the height and width of the screen
size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Platformer with sprite sheets")

# Create the player
player = Player()

# Create all the levels
level_list = []
level_list.append(levels.Level_01(player))
level_list.append(levels.Level_02(player))

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = constants.SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# If the player gets near the right side, shift the world left (-x)
if player.rect.right >= 500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)

# If the player gets near the left side, shift the world right (+x)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)

# If the player gets to the end of the level, go to the next level
current_position = player.rect.x + current_level.world_shift
if current_position < current_level.level_limit:
player.rect.x = 120
if current_level_no < len(level_list)-1:
current_level_no += 1
current_level = level_list[current_level_no]
player.level = current_level

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()

# data[].attributes.body
File 1 (__.init__.py)
File2 (cli.py)
from .game import Player, Game
from .painter import present_6_die_name
from .recorder import RunRecord, MakeRecord
from os import linesep

class CLIGame():

def __init__(self):
self.prompt_end = "> "
self.game = Game()
# used for nicer print
self.prompted_for_pawn = False
# saving game data
self.record_maker = MakeRecord()
# getting game data
self.record_runner = None

def validate_input(self, prompt, desire_type, allawed_input=None,
error_mess="Invalid Option!", str_len=None):
'''
loop while receive correct value
param allowed_input can be list of allowed values
param str_len is two sized tuple if min and max
'''
prompt += linesep + self.prompt_end
while True:
choice = input(prompt)
if not choice:
print(linesep + error_mess)
continue
try:
choice = desire_type(choice)
except ValueError:
print(linesep + error_mess)
continue
if allawed_input:
if choice in allawed_input:
break
else:
print("Invalid Option!")
continue
elif str_len:
min_len, max_len = str_len
if min_len < len(choice) < max_len:
break
else:
print(linesep + error_mess)
else:
break
print()
return choice

def get_user_initial_choice(self):
text = linesep.join(["choose option",
"0 - start new game",
"1 - continue game",
"2 - run (review) recorded game"])
choice = self.validate_input(text, int, (0, 1, 2))
return choice

def prompt_for_file(self, mode="rb"):
'''return file descriptor'''
text = "Enter filename (name of the record)"
while True:
filename = self.validate_input(text, str)
try:
file_descr = open(filename, mode=mode)
return file_descr
except IOError as e:
print(e)
print("Try again")

def does_user_want_save_game(self):
'''return True if user want to save
game or False
'''
text = linesep.join(["Save game?",
"0 - No",
"1 - Yes"])
choice = self.validate_input(text, int, (0, 1))
return choice == 1

def prompt_for_player(self):
''' get player attributes from input,
initial player instance and
add player to the game
'''
available_colours = self.game.get_available_colours()
text = linesep.join(["choose type of player",
"0 - computer",
"1 - human"])
choice = self.validate_input(text, int, (0, 1))

if choice == 1:
name = self.validate_input("Enter name for player",
str, str_len=(1, 30))
available_options = range(len(available_colours))
if len(available_options) > 1:
# show available colours
options = ["{} - {}".format(index, colour)
for index, colour in
zip(available_options,
available_colours)]
text = "choose colour" + linesep
text += linesep.join(options)
choice = self.validate_input(text, int, available_options)
colour = available_colours.pop(choice)
else:
# only one colour left
colour = available_colours.pop()
player = Player(colour, name, self.prompt_choose_pawn)
elif choice == 0:
# automatically assign colours
colour = available_colours.pop()
player = Player(colour)
self.game.add_palyer(player)

def prompt_for_players(self):
'''put all players in the game'''
counts = ("first", "second", "third", "fourth last")
text_add = "Add {} player"
for i in range(2):
print(text_add.format(counts[i]))
self.prompt_for_player()
print("Player added")

text = linesep.join(["Choose option:",
"0 - add player",
"1 - start game with {} players"])
for i in range(2, 4):
choice = self.validate_input(text.format(str(i)), int, (0, 1))
if choice == 1:
break
elif choice == 0:
print(text_add.format(counts[i]))
self.prompt_for_player()
print("Player added")

def prompt_choose_pawn(self):
'''used when player (human) has more than
one possible pawn to move.
This method is pass as a callable during
player instantiation
'''
text = present_6_die_name(self.game.rolled_value,
str(self.game.curr_player))
text += linesep + "has more than one possible pawns to move."
text += " Choose pawn" + linesep
pawn_options = ["{} - {}".format(index + 1, pawn.id)
for index, pawn
in enumerate(self.game.allowed_pawns)]
text += linesep.join(pawn_options)
index = self.validate_input(
text, int, range(1, len(self.game.allowed_pawns) + 1))
self.prompted_for_pawn = True
return index - 1

def prompt_to_continue(self):
text = "press Enter to continue" + linesep
input(text)

def print_players_info(self):
word = "start" if self.game.rolled_value is None else "continue"
print("Game {} with {} players:".format(
word,
len(self.game.players)))
for player in self.game.players:
print(player)
print()

def print_info_after_turn(self):
'''it used game attributes to print info'''
pawns_id = [pawn.id for pawn in self.game.allowed_pawns]
# nicer print of dice
message = present_6_die_name(self.game.rolled_value,
str(self.game.curr_player))
message += linesep
if self.game.allowed_pawns:
message_moved = "{} is moved. ".format(
self.game.picked_pawn.id)
if self.prompted_for_pawn:
self.prompted_for_pawn = False
print(message_moved)
return
message += "{} possible pawns to move.".format(
" ".join(pawns_id))
message += " " + message_moved
if self.game.jog_pawns:
message += "Jog pawn "
message += " ".join([pawn.id for pawn in self.game.jog_pawns])
else:
message += "No possible pawns to move."
print(message)

def print_standing(self):
standing_list = ["{} - {}".format(index + 1, player)
for index, player in enumerate(self.game.standing)]
message = "Standing:" + linesep + linesep.join(standing_list)
print(message)

def print_board(self):
print(self.game.get_board_pic())

def run_recorded_game(self):
'''get history of game (rolled_value
and  index's allowed pawn) from
record_runner in order to replay game'''
self.load_recorded_players()
self.print_players_info()
self.prompt_to_continue()
for rolled_value, index in self.record_runner:
self.game.play_turn(index, rolled_value)
self.print_info_after_turn()
self.print_board()
self.prompt_to_continue()
self.print_board()

def continue_recorded_game(self):
'''move forward the game by calling
play_turn method to the moment
where game was interrupted.
'''
self.load_recorded_players()
self.record_players()
for rolled_value, index in self.record_runner:
self.game.play_turn(index, rolled_value)
self.record_maker.add_game_turn(
self.game.rolled_value, self.game.index)
self.print_players_info()
self.print_info_after_turn()
self.print_board()

def record_players(self):
'''save players on recorder'''
for player in self.game.players:
self.record_maker.add_player(player)

def load_recorded_players(self):
'''get recorded (save) players from
recorder and put them in game
'''
if self.record_runner is None:
file_descr = self.prompt_for_file()
self.record_runner = RunRecord(file_descr)
file_descr.close()
for player in self.record_runner.get_players(
self.prompt_choose_pawn):
self.game.add_palyer(player)

def load_players_for_new_game(self):
self.prompt_for_players()
self.print_players_info()
self.record_players()

def play_game(self):
'''mainly calling play_turn
Game's method while game finished
'''
try:
while not self.game.finished:
self.game.play_turn()
self.print_info_after_turn()
self.print_board()
self.record_maker.add_game_turn(
self.game.rolled_value, self.game.index)
self.prompt_to_continue()
print("Game finished")
self.print_standing()
self.offer_save_game()
except (KeyboardInterrupt, EOFError):
print(linesep +
"Exiting game. " +
"Save game and continue same game later?")
self.offer_save_game()
raise

def offer_save_game(self):
'''offer user save game'''
if self.does_user_want_save_game():
file_descr = self.prompt_for_file(mode="wb")
self.record_maker.save(file_descr)
file_descr.close()
print("Game is saved")

def start(self):
'''main method, starting cli'''
print()
try:
choice = self.get_user_initial_choice()
if choice == 0:  # start new game
self.load_players_for_new_game()
self.play_game()
elif choice == 1:  # continue game
self.continue_recorded_game()
if self.game.finished:
print("Could not continue.",
"Game is already finished",
linesep + "Exit")
else:
self.prompt_to_continue()
self.play_game()
elif choice == 2:  # review played game
self.run_recorded_game()
except (KeyboardInterrupt, EOFError):
print(linesep + "Exit Game")

if __name__ == '__main__':
CLIGame().start()

File 3 (game.py)
from collections import namedtuple, deque
import random
from .painter import PaintBoard

# Thanks to Angel Angelov
# This is piece or a token in ludo game
# Simple class has only index, colour and id attributes
Pawn = namedtuple("Pawn", "index colour id")

class Player():
'''Knows (holds) his pawns,
also know his colour
and choose which pawn to move
if more than one are possible
'''
def __init__(self, colour, name=None, choose_pawn_delegate=None):
'''choose_pawn_delegate is callable.
if choose_pawn_delegate is not None it is called
with argument list of available pawns to move
and expect chosen index from this list
if it is None (means computer) random index is chosen
'''
self.colour = colour
self.choose_pawn_delegate = choose_pawn_delegate
self.name = name
if self.name is None and self.choose_pawn_delegate is None:
self.name = "computer"
self.finished = False
# initialize four pawns with
# id (first leter from colour and index (from 1 to 4))
self.pawns = [Pawn(i, colour, colour[0].upper() + str(i))
for i in range(1, 5)]

def __str__(self):
return "{}({})".format(self.name, self.colour)

def choose_pawn(self, pawns):
'''Delegate choice to choose_pawn_delegate func attribute
if it is not None
'''
if len(pawns) == 1:
index = 0
elif len(pawns) > 1:
if self.choose_pawn_delegate is None:
index = random.randint(0, len(pawns) - 1)
else:
index = self.choose_pawn_delegate()
return index

class Board():
'''
Knows where are pawns.
Pawns are assigned with position numbers.
Can move (change position number) pawn.
Knows other things like
what distance pawn must past to reach end.
It just board. It does not know rules of the game.
'''

# common (shared) squares for all pawns
BOARD_SIZE = 56

# save (private) positions (squares) for each colour
# This is squares just before pawn finished
BOARD_COLOUR_SIZE = 7

COLOUR_ORDER = ['yellow', 'blue', 'red', 'green']

# distance between two neighbour colours
# (The distance from start square of one colour
# to start square of next colour)
COLOUR_DISTANCE = 14

def __init__(self):
#fn1353c
# get dict of start position for every colour
Board.COLOUR_START = {
colour: 1 + index * Board.COLOUR_DISTANCE for
index, colour in enumerate(Board.COLOUR_ORDER)}
# get dict of end position for every colour
Board.COLOUR_END = {
colour: index * Board.COLOUR_DISTANCE
for index, colour in enumerate(Board.COLOUR_ORDER)}
Board.COLOUR_END['yellow'] = Board.BOARD_SIZE

# dict where key is pawn and
# value is two size tuple holds position
# Position is combination of
# common (share) square and coloured (private) square.
self.pawns_possiotion = {}

# painter is used to visually represent
# the board and position of the pawns
self.painter = PaintBoard()

# pool means before start1353
self.board_pool_position = (0, 0)

def set_pawn(self, pawn, position):
'''save position'''
self.pawns_possiotion[pawn] = position

def put_pawn_on_board_pool(self, pawn):
self.set_pawn(pawn, self.board_pool_position)

def is_pawn_on_board_pool(self, pawn):
'''return True of False'''
return self.pawns_possiotion[pawn] == self.board_pool_position

def put_pawn_on_starting_square(self, pawn):
start = Board.COLOUR_START[pawn.colour.lower()]
position = (start, 0)
self.set_pawn(pawn, position)

def can_pawn_move(self, pawn, rolled_value):
'''check if pawn can outside board colour size'''
common_poss, private_poss = self.pawns_possiotion[pawn]
if private_poss + rolled_value > self.BOARD_COLOUR_SIZE:
return False
return True

def move_pawn(self, pawn, rolled_value):
'''change pawn position, check
if pawn reach his color square
'''
common_poss, private_poss = self.pawns_possiotion[pawn]
end = self.COLOUR_END[pawn.colour.lower()]
if private_poss > 0:
# pawn is already reached own final squares
private_poss += rolled_value
elif common_poss <= end and common_poss + rolled_value > end:
# pawn is entering in own squares
private_poss += rolled_value - (end - common_poss)
common_poss = end
else:
# pawn will be still in common square
common_poss += rolled_value
if common_poss > self.BOARD_SIZE:
common_poss = common_poss - self.BOARD_SIZE
position = common_poss, private_poss
self.set_pawn(pawn, position)

def does_pawn_reach_end(self, pawn):
'''if pawn must leave game'''
common_poss, private_poss = self.pawns_possiotion[pawn]
if private_poss == self.BOARD_COLOUR_SIZE:
return True
return False

def get_pawns_on_same_postion(self, pawn):
'''return list of pawns on same position'''
position = self.pawns_possiotion[pawn]
return [curr_pawn for curr_pawn, curr_postion in
self.pawns_possiotion.items()
if position == curr_postion]

def paint_board(self):
'''painter object expect dict of
key - occupied positions and
value - list of pawns on that position
'''
positions = {}
for pawn, position in self.pawns_possiotion.items():
common, private = position
if not private == Board.BOARD_COLOUR_SIZE:
positions.setdefault(position, []).append(pawn)
return self.painter.paint(positions)

class Die():

MIN = 1
MAX = 6

@staticmethod
def throw():
return random.randint(Die.MIN, Die.MAX)

class Game():
'''Knows the rules of the game.
Knows for example what to do when
one pawn reach another
or pawn reach end or
player roll six and so on
'''

def __init__(self):
self.players = deque()
self.standing = []
self.board = Board()
# is game finished
self.finished = False
# last rolled value from die (dice)
self.rolled_value = None
# player who last rolled die
self.curr_player = None
# curr_player's possible pawn to move
self.allowed_pawns = []
# curr_player's chosen pawn to move
self.picked_pawn = None
# chosen index from allowed pawn
self.index = None
# jog pawn if any
self.jog_pawns = []

def add_palyer(self, player):
self.players.append(player)
for pawn in player.pawns:
self.board.put_pawn_on_board_pool(pawn)

def get_available_colours(self):
'''if has available colour on boards'''
used = [player.colour for player in self.players]
available = set(self.board.COLOUR_ORDER) - set(used)
return sorted(available)

def _get_next_turn(self):
'''Get next player's turn.
It is underscore because if called
outside the class will break order
'''
if not self.rolled_value == Die.MAX:
self.players.rotate(-1)
return self.players[0]

def get_pawn_from_board_pool(self, player):
'''when pawn must start'''
for pawn in player.pawns:
if self.board.is_pawn_on_board_pool(pawn):
return pawn

def get_allowed_pawns_to_move(self, player, rolled_value):
''' return all pawns of a player which rolled value
from die allowed to move the pawn
'''
allowed_pawns = []
if rolled_value == Die.MAX:
pawn = self.get_pawn_from_board_pool(player)
if pawn:
allowed_pawns.append(pawn)
for pawn in player.pawns:
if not self.board.is_pawn_on_board_pool(pawn) and\
self.board.can_pawn_move(pawn, rolled_value):
allowed_pawns.append(pawn)
return sorted(allowed_pawns, key=lambda pawn: pawn.index)

def get_board_pic(self):
return self.board.paint_board()

def _jog_foreign_pawn(self, pawn):
pawns = self.board.get_pawns_on_same_postion(pawn)
for p in pawns:
if p.colour != pawn.colour:
self.board.put_pawn_on_board_pool(p)
self.jog_pawns.append(p)

def _make_move(self, player, pawn):
'''tell the board to move pawn.
After move ask board if pawn reach end or
jog others pawn. Check if pawn and player finished.
'''
if self.rolled_value == Die.MAX and\
self.board.is_pawn_on_board_pool(pawn):
self.board.put_pawn_on_starting_square(pawn)
self._jog_foreign_pawn(pawn)
return
self.board.move_pawn(pawn, self.rolled_value)
if self.board.does_pawn_reach_end(pawn):
player.pawns.remove(pawn)
if not player.pawns:
self.standing.append(player)
self.players.remove(player)
if len(self.players) == 1:
self.standing.extend(self.players)
self.finished = True
else:
self._jog_foreign_pawn(pawn)

def play_turn(self, ind=None, rolled_val=None):
'''this is main method which must be used to play game.
Method ask for next player's turn, roll die, ask player
to choose pawn, move pawn.
ind and rolled_val are suitable to be used when
game must be replicated (recorded)
ind is chosen index from allowed pawns
'''
self.jog_pawns = []
self.curr_player = self._get_next_turn()
if rolled_val is None:
self.rolled_value = Die.throw()
else:
self.rolled_value = rolled_val
self.allowed_pawns = self.get_allowed_pawns_to_move(
self.curr_player, self.rolled_value)
if self.allowed_pawns:
if ind is None:
self.index = self.curr_player.choose_pawn(
self.allowed_pawns)
else:
self.index = ind
self.picked_pawn = self.allowed_pawns[self.index]
self._make_move(self.curr_player, self.picked_pawn)
else:
self.index = -1
self.picked_pawn = None

File 4 Painter
from copy import deepcopy
from os import linesep

# board template (matrix)
BOARD_TMPL = [['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Y', 'E', 'L', 'L', 'O', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', 'V', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'B', 'L', 'U', 'E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', '-', '-', '>', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'], ['#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#'], ['#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', 'X', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#'], ['#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '<', '-', '-', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'G', 'R', 'E', 'E', 'N', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'R', 'E', 'D', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '^', ' ', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', '-', '-', '-', '-', '-', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|', ' ', '#', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#']]

# List of two sized tuples. The content of tuple correspond
# with address of matrix BOARD_TMPL. While list index correspond
# with pawn share position from board class
CODE_COMMON_SQUARES = [
(),  # 0 index not used
(14, 2), (14, 8), (14, 14), (14, 20), (14, 26), (14, 32), (14, 38),
(12, 38), (10, 38), (8, 38), (6, 38), (4, 38), (2, 38), (2, 44),
(2, 50), (4, 50), (6, 50), (8, 50), (10, 50), (12, 50), (14, 50),
(14, 56), (14, 62), (14, 68), (14, 74), (14, 80), (14, 86), (16, 86),
(18, 86), (18, 80), (18, 74), (18, 68), (18, 62), (18, 56), (18, 50),
(20, 50), (22, 50), (24, 50), (26, 50), (28, 50), (30, 50), (30, 44),
(30, 38), (28, 38), (26, 38), (24, 38), (22, 38), (20, 38), (18, 38),
(18, 32), (18, 26), (18, 20), (18, 14), (18, 8), (18, 2), (16, 2)
]

# tuple correspond with address of matrix BOARD_TMPL
# color correspond to pawn colour
# index of colour's list correspond with pawn private (final) position
CODE_COLOUR_SQUARES = {
'yellow': [(), (16, 8), (16, 14), (16, 20), (16, 26), (16, 32), (16, 38)],
'blue': [(), (4, 44), (6, 44), (8, 44), (10, 44), (12, 44), (14, 44)],
'red': [(), (16, 80), (16, 74), (16, 68), (16, 62), (16, 56), (16, 50)],
'green': [(), (28, 44), (26, 44), (24, 44), (22, 44), (20, 44), (18, 44)]
}

# tuple correspond with address of matrix BOARD_TMPL
# color correspond to pawn colour
# index of colour's list correspond with pawn initial position
CODE_POOL_PLACES = {
'yellow': [(), (6, 14), (6, 19), (8, 14), (8, 19)],
'blue': [(), (6, 71), (6, 76), (8, 71), (8, 76)],
'red': [(), (24, 71), (24, 76), (26, 71), (26, 76)],
'green': [(), (24, 14), (24, 19), (26, 14), (26, 19)]
}

class PaintBoard():

def __init__(self):
self.board_tmpl_curr = deepcopy(BOARD_TMPL)

def _place_pawn(self, pawn, position, offset):
common_poss, private_poss = position
colour = pawn.colour.lower()
if private_poss > 0:
# private squares
row, column = CODE_COLOUR_SQUARES[colour][private_poss]
elif common_poss == 0:
# pool
row, column = CODE_POOL_PLACES[colour][pawn.index]
offset = 0  # we do not need from offset in the pool only in squares
else:
# common squares
row, column = CODE_COMMON_SQUARES[common_poss]
if offset > 0:
self.board_tmpl_curr[row - 1][column + offset] = pawn.id[1]
else:
self.board_tmpl_curr[row - 1][column - 1] = pawn.id[0]
self.board_tmpl_curr[row - 1][column] = pawn.id[1]

def _place_pawns(self, position_pawns):
for position, pawns in position_pawns.items():
for index, pawn in enumerate(pawns):
self._place_pawn(pawn, position, index)

def paint(self, position):
'''expect dict of
key - occupied positions and
value - list of pawns on that position
'''
self.board_tmpl_curr = deepcopy(BOARD_TMPL)
self._place_pawns(position)
board_paint = [''.join(row_list) for row_list in self.board_tmpl_curr]
board_paint_str = linesep.join(board_paint)
return board_paint_str

def present_6_die_name(number, name):
'''nicer print of die and
name of the player
'''
hor_line = 9 * '-'
sps = 37 * ' '
hor_line = sps + hor_line
matrix = [['|       |', '|   #   |', '|       |'],
['|       |', '| #   # |', '|       |'],
['|     # |', '|   #   |', '| #     |'],
['| #   # |', '|       |', '| #   # |'],
['| #   # |', '|   #   |', '| #   # |'],
['| # # # |', '|       |', '| # # # |']]
matrix = [[sps + cell for cell in row] for row in matrix]
die = matrix[number - 1]
die[1] = die[1] + "   " + name
s = linesep.join([hor_line] + die + [hor_line])
return s

File 5 recorder
import pickle
from .game import Player

class RunRecord():
'''provide recoded game data
iterating over instance
yield rolled_value and index
'''

def __init__(self, file_obj):
self.file_obj = file_obj
data = pickle.load(self.file_obj)
self.players = data[0]
self.game_history = data[1]

def get_players(self, func=None):
'''
return Player object
recreated from a list
func is callable which player
may need for choice delegation
'''
res = []
for colour, name, is_computer in self.players:
if is_computer:
player = Player(colour)
else:
player = Player(colour, name, func)
res.append(player)
return res

def get_game_history(self):
return self.game_history

def __iter__(self):
return iter(self.game_history)

class MakeRecord():
'''save game data
as a nested list which is
saved with pickle
'''

def __init__(self):
self.players = []
self.game_history = []

def add_player(self, player_obj):
'''Accept Player object and
it save NOT as object rather as a list
'''
if player_obj.choose_pawn_delegate is None:
is_computer = True
else:
is_computer = False
self.players.append((player_obj.colour,
player_obj.name, is_computer))

def add_game_turn(self, rolled_value, index):
self.game_history.append((rolled_value, index))

def save(self, file_obj):
'''list of lists with players and
game history
'''
pickle.dump([self.players, self.game_history],
file_obj)

* *SAVE THEM IN LUDO FILE**
Create a new python file name it as run and type the following code
from ludo.cli import CLIGame

CLIGame().start()

# data[].attributes.body
# importing random
from random import *

# taking input from user
user_pass = input("Enter your password")

# storing alphabet letter to use thm to crack password
password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v',
'w', 'x', 'y', 'z',]

# initializing an empty string
guess = ""

# using while loop to generate many passwords untill one of
# them does not matches user_pass
while (guess != user_pass):
guess = ""
# generating random passwords using for loop
for letter in range(len(user_pass)):
guess_letter = password[randint(0, 25)]
guess = str(guess_letter) + str(guess)
# printing guessed passwords
print(guess)

# printing the matched password
print("Your password is",guess)

# data[].attributes.body
# importing random
from random import *

# taking input from user
user_pass = input("Enter your password")

# storing alphabet letter to use thm to crack password
password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v',
'w', 'x', 'y', 'z',]

# initializing an empty string
guess = ""

# using while loop to generate many passwords untill one of
# them does not matches user_pass
while (guess != user_pass):
guess = ""
# generating random passwords using for loop
for letter in range(len(user_pass)):
guess_letter = password[randint(0, 25)]
guess = str(guess_letter) + str(guess)
# printing guessed passwords
print(guess)

# printing the matched password
print("Your password is",guess)

# data[].attributes.body
# importing random
from random import *

# taking input from user
user_pass = input("Enter your password")

# storing alphabet letter to use thm to crack password
password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v',
'w', 'x', 'y', 'z',]

# initializing an empty string
guess = ""

# using while loop to generate many passwords untill one of
# them does not matches user_pass
while (guess != user_pass):
guess = ""
# generating random passwords using for loop
for letter in range(len(user_pass)):
guess_letter = password[randint(0, 25)]
guess = str(guess_letter) + str(guess)
# printing guessed passwords
print(guess)

# printing the matched password
print("Your password is",guess)

# data[].attributes.body
# importing random
from random import *

# taking input from user
user_pass = input("Enter your password")

# storing alphabet letter to use thm to crack password
password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v',
'w', 'x', 'y', 'z',]

# initializing an empty string
guess = ""

# using while loop to generate many passwords untill one of
# them does not matches user_pass
while (guess != user_pass):
guess = ""
# generating random passwords using for loop
for letter in range(len(user_pass)):
guess_letter = password[randint(0, 25)]
guess = str(guess_letter) + str(guess)
# printing guessed passwords
print(guess)

# printing the matched password
print("Your password is",guess)

# data[].attributes.body
'''In this tutorial are going to make a real-time GUI to Send OTP Using Python. For this project, we are going to use four modules namely Tkinter, Requests, Random, and JSON.
Tkinter will be used for creating the UI.
Requests will be used to send a GET request to the site.
JSON will be used for setting the parameters and the random module will be used for generating the OTP.
Also, you need to create an account on fast2sms. Creating an account is very simple. Go to http://www.fast2sms.com and create an account for free. As a new user, you will receive 50 rupees balance in your wallet.
Now Goto Dev API and generate your API. Copy your unique API and paste in the JSON part of the code.'''

from tkinter import *
import tkinter.messagebox as tsmg
import requests
import random
import json

root=Tk()

rand=random.randint(1,999999)

msg=f"Your One Time Password(OTP) is {rand}"

def sms_send(a,msg):
url="https://www.fast2sms.com/dev/bulk"
params={
"authorization":"ZctzPjmw1mzJXKcdpPXRJR3c",#paste your api here by going to devapi and login to generate an api
"sender_id":"SMSINI",
"message":msg,
"language":"english",
"route":"p",
"numbers":a
}
rs=requests.get(url,params=params)

def send():
a=num.get()
if(a==""):
tsmg.showerror("Error","Enter Your Mobile Number")
elif (len(a)<10):
tsmg.showerror("Error","Invalid Mobile Number")
num.set("")
else:
b=tsmg.askyesno("Info",f"Your Number is {a}")
if(b==True):
sms_send(a,msg)
else:
num.set("")

def check():
c=otp.get()
if(c==""):
tsmg.showerror("Error","Enter OTP")
else:
if(str(rand)==c):
tsmg.showinfo("Info","Successful")
else:
tsmg.showerror("Error","Invalid OTP")
num.set("")
otp.set("")

root.geometry("500x500")
root.title("OTP-Checker")

num=StringVar()
otp=StringVar()

f1=Frame(root)
Label(f1,text="Check Your OTP",font="SegoeUI 30 bold",fg="purple").pack(padx=5,pady=10)
f1.pack(fill=BOTH)

f2=Frame(root)
Label(f2,text="Enter Your Number",font="SegoeUI 20 bold",fg="teal").pack(padx=5,pady=5)
e1=Entry(f2,textvariable=num,font="SegoeUI 14 bold",fg="black",bg="white",relief=SUNKEN,borderwidth=4,justify="center").pack(ipady=5)
f2.pack(fill=BOTH,padx=5,pady=10)

f3=Frame(root)
Label(f3,text="Enter OTP",font="SegoeUI 20 bold",fg="teal").pack(padx=5,pady=5)
e2=Entry(f3,textvariable=otp,font="SegoeUI 14 bold",fg="black",bg="white",relief=SUNKEN,borderwidth=5,justify="center").pack(ipady=5)
f3.pack(fill=BOTH,padx=5,pady=10)

f4=Frame(root)
Button(f4,text="Send OTP",command=send,font="SegoeUI 10 bold",fg="purple").pack(padx=20,pady=10,side=LEFT)
Button(f4,text="Check OTP",command=check,font="SegoeUI 10 bold",fg="purple").pack(padx=40,pady=10,side=LEFT)
f4.pack()

root.mainloop()

# data[].attributes.body
import pygame
from pygame import mixer
from tkinter import *
import os
def playsong():
currentsong=playlist.get(ACTIVE)
print(currentsong)
mixer.music.load(currentsong)
songstatus.set("Playing")
mixer.music.play()
def pausesong():
songstatus.set("Paused")
mixer.music.pause()
def stopsong():
songstatus.set("Stopped")
mixer.music.stop()
def resumesong():
songstatus.set("Resuming")
mixer.music.unpause()
root=Tk()
root.title('Project Music player project')
mixer.init()
songstatus=StringVar()
songstatus.set("choosing")
#playlist---------------
playlist=Listbox(root,selectmode=SINGLE,bg="DodgerBlue2",fg="white",font=('arial',15),width=40)
playlist.grid(columnspan=5)
os.chdir(r'C:/Users/Swaralaya/Desktop/pattu')
songs=os.listdir()
for s in songs:
playlist.insert(END,s)
playbtn=Button(root,text="play",command=playsong)
playbtn.config(font=('arial',20),bg="DodgerBlue2",fg="white",padx=7,pady=7)
playbtn.grid(row=1,column=0)
pausebtn=Button(root,text="Pause",command=pausesong)
pausebtn.config(font=('arial',20),bg="DodgerBlue2",fg="white",padx=7,pady=7)
pausebtn.grid(row=1,column=1)
stopbtn=Button(root,text="Stop",command=stopsong)
stopbtn.config(font=('arial',20),bg="DodgerBlue2",fg="white",padx=7,pady=7)
stopbtn.grid(row=1,column=2)
Resumebtn=Button(root,text="Resume",command=resumesong)
Resumebtn.config(font=('arial',20),bg="DodgerBlue2",fg="white",padx=7,pady=7)
Resumebtn.grid(row=1,column=3)
mainloop()

# data[].attributes.body
#This is the First Part:

import turtle
import math
import random

window = turtle.Screen()
window.setup(width=600, height=600)
window.title("Star Wars Game ")
window.bgcolor("black")

window.tracer(0)

vertex = ((0,15),(-15,0),(-18,5),(-18,-5),(0,0),(18,-5),(18, 5),(15, 0))
window.register_shape("player", vertex)

asVertex = ((0, 10), (5, 7), (3,3), (10,0), (7, 4), (8, -6), (0, -10), (-5, -5), (-7, -7), (-10, 0), (-5, 4), (-1, 8))
window.register_shape("chattan", asVertex)

####################
#This is the Second Part:

class Ankur(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)

self.speed(0)
self.penup()

def ankur1(t1, t2):
x1 = t1.xcor()
y1 = t1.ycor()

x2 = t2.xcor()
y2 = t2.ycor()

taauko = math.atan2(y1 - y2, x1 - x2)
taauko = taauko * 180.0 / 3.14159

return taauko

player = Ankur()
player.color("white")
player.shape("player")
player.score = 0

####################
#This is the Third Part

missiles = []
for _ in range(3):
missile = Ankur()
missile.color("red")
missile.shape("arrow")
missile.speed = 1
missile.state = "ready"
missile.hideturtle()
missiles.append(missile)

pen = Ankur()
pen.color("white")
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score: 0", False, align = "center", font = ("Arial", 24, "normal"))

####################
#This is the Fourth Part

chattans = []

for _ in range(5):
chattan = Ankur()
chattan.color("brown")
chattan.shape("arrow")

chattan.speed  = random.randint(2, 3)/50
chattan.goto(0, 0)
taauko = random.randint(0, 260)
distance = random.randint(300, 400)
chattan.setheading(taauko)
chattan.fd(distance)
chattan.setheading(ankur1(player, chattan))
chattans.append(chattan)

####################
#This is the Functions for Defence Part

def baanya():
player.lt(20)

def daanya():
player.rt(20)

def fire_missile():
for missile in missiles:
if missile.state == "ready":
missile.goto(0, 0)
missile.showturtle()
missile.setheading(player.heading())
missile.state = "fire"
break

window.listen()
window.onkey(baanya, "Left")
window.onkey(daanya, "Right")
window.onkey(fire_missile, "space")

####################
#This is the Functioning the Code Part-1

sakkyo = False
while True:

window.update()
player.goto(0, 0)

for missile in missiles:
if missile.state == "fire":
missile.fd(missile.speed)

if missile.xcor() > 300 or missile.xcor() < -300 or missile.ycor() > 300 or missile.ycor() < -300:
missile.hideturtle()
missile.state = "ready"

for chattan in chattans:
chattan.fd(chattan.speed)

for missile in missiles:
if chattan.distance(missile) < 20:
taauko = random.randint(0, 260)
distance = random.randint(600, 800)
chattan.setheading(taauko)
chattan.fd(distance)
chattan.setheading(ankur1(player, chattan))
chattan.speed += 0.01

missile.goto(600, 600)
missile.hideturtle()
missile.state = "ready"

player.score += 10
pen.clear()
pen.write("Score: {}".format(player.score), False, align = "center", font = ("Arial", 24, "normal"))

####################
#This is the Functioning the Code Part-2

if chattan.distance(player) < 20:
taauko = random.randint(0, 260)
distance = random.randint(600, 800)
chattan.setheading(taauko)
chattan.fd(distance)
chattan.setheading(ankur1(player, chattan))
chattan.speed += 0.005
sakkyo = True
player.score -= 30
pen.clear()
pen.write("Score: {}".format(player.score), False, align = "center", font = ("Arial", 24, "normal"))
if sakkyo == True:
player.hideturtle()
missile.hideturtle()
for a in chattans:
a.hideturtle()
pen.clear()
break

window.mainloop()

# data[].attributes.body
"""
Sample Breakout Game

Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""

# --- Import libraries used for this program

import math
import pygame

# Define some colors
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)

# Size of break-out blocks
block_width = 23
block_height = 15

class Block(pygame.sprite.Sprite):
"""This class represents each block that will get knocked out by the ball
It derives from the "Sprite" class in Pygame """

def __init__(self, color, x, y):
""" Constructor. Pass in the color of the block,
and its x and y position. """

# Call the parent class (Sprite) constructor
super().__init__()

# Create the image of the block of appropriate size
# The width and height are sent as a list for the first parameter.
self.image = pygame.Surface([block_width, block_height])

# Fill the image with the appropriate color
self.image.fill(color)

# Fetch the rectangle object that has the dimensions of the image
self.rect = self.image.get_rect()

# Move the top left of the rectangle to x,y.
# This is where our block will appear..
self.rect.x = x
self.rect.y = y

class Ball(pygame.sprite.Sprite):
""" This class represents the ball
It derives from the "Sprite" class in Pygame """

# Speed in pixels per cycle
speed = 10.0

# Floating point representation of where the ball is
x = 0.0
y = 180.0

# Direction of ball (in degrees)
direction = 200

width = 10
height = 10

# Constructor. Pass in the color of the block, and its x and y position
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()

# Create the image of the ball
self.image = pygame.Surface([self.width, self.height])

# Color the ball
self.image.fill(white)

# Get a rectangle object that shows where our image is
self.rect = self.image.get_rect()

# Get attributes for the height/width of the screen
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

def bounce(self, diff):
""" This function will bounce the ball
off a horizontal surface (not a vertical one) """

self.direction = (180 - self.direction) % 360
self.direction -= diff

def update(self):
""" Update the position of the ball. """
# Sine and Cosine work in degrees, so we have to convert them
direction_radians = math.radians(self.direction)

# Change the position (x and y) according to the speed and direction
self.x += self.speed * math.sin(direction_radians)
self.y -= self.speed * math.cos(direction_radians)

# Move the image to where our x and y are
self.rect.x = self.x
self.rect.y = self.y

# Do we bounce off the top of the screen?
if self.y <= 0:
self.bounce(0)
self.y = 1

# Do we bounce off the left of the screen?
if self.x <= 0:
self.direction = (360 - self.direction) % 360
self.x = 1

# Do we bounce of the right side of the screen?
if self.x > self.screenwidth - self.width:
self.direction = (360 - self.direction) % 360
self.x = self.screenwidth - self.width - 1

# Did we fall off the bottom edge of the screen?
if self.y > 600:
return True
else:
return False

class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """

def __init__(self):
""" Constructor for Player. """
# Call the parent's constructor
super().__init__()

self.width = 75
self.height = 15
self.image = pygame.Surface([self.width, self.height])
self.image.fill((white))

# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

self.rect.x = 0
self.rect.y = self.screenheight-self.height

def update(self):
""" Update the player position. """
# Get where the mouse is
pos = pygame.mouse.get_pos()
# Set the left side of the player bar to the mouse position
self.rect.x = pos[0]
# Make sure we don't push the player paddle
# off the right side of the screen
if self.rect.x > self.screenwidth - self.width:
self.rect.x = self.screenwidth - self.width

# Call this function so the Pygame library can initialize itself
pygame.init()

# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])

# Set the title of the window
pygame.display.set_caption('Breakout')

# Enable this to make the mouse disappear when over our window
pygame.mouse.set_visible(0)

# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)

# Create a surface we can draw on
background = pygame.Surface(screen.get_size())

# Create sprite lists
blocks = pygame.sprite.Group()
balls = pygame.sprite.Group()
allsprites = pygame.sprite.Group()

# Create the player paddle object
player = Player()
allsprites.add(player)

# Create the ball
ball = Ball()
allsprites.add(ball)
balls.add(ball)

# The top of the block (y position)
top = 80

# Number of blocks to create
blockcount = 32

# --- Create blocks

# Five rows of blocks
for row in range(5):
# 32 columns of blocks
for column in range(0, blockcount):
# Create a block (color,x,y)
block = Block(blue, column * (block_width + 2) + 1, top)
blocks.add(block)
allsprites.add(block)
# Move the top of the next row down
top += block_height + 2

# Clock to limit speed
clock = pygame.time.Clock()

# Is the game over?
game_over = False

# Exit the program?
exit_program = False

# Main program loop
while exit_program != True:

# Limit to 30 fps
clock.tick(30)

# Clear the screen
screen.fill(black)

# Process the events in the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_program = True

# Update the ball and player position as long
# as the game is not over.
if not game_over:
# Update the player and ball positions
player.update()
game_over = ball.update()

# If we are done, print game over
if game_over:
text = font.render("Game Over", True, white)
textpos = text.get_rect(centerx=background.get_width()/2)
textpos.top = 300
screen.blit(text, textpos)

# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player, balls, False):
# The 'diff' lets you try to bounce the ball left or right
# depending where on the paddle you hit it
diff = (player.rect.x + player.width/2) - (ball.rect.x+ball.width/2)

# Set the ball's y position in case
# we hit the ball on the edge of the paddle
ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1
ball.bounce(diff)

# Check for collisions between the ball and the blocks
deadblocks = pygame.sprite.spritecollide(ball, blocks, True)

# If we actually hit a block, bounce the ball
if len(deadblocks) > 0:
ball.bounce(0)

# Game ends if all the blocks are gone
if len(blocks) == 0:
game_over = True

# Draw Everything
allsprites.draw(screen)

# Flip the screen and show what we've drawn
pygame.display.flip()

pygame.quit()