day 4 剪刀石头布
theme: greenwillow
highlight: atelier-seaside-light
theme:nico
highlight: atelier-seaside-light
print("welcome to the game")
number=int(input("enter your number,0,1,or 2\n"))
scissors='''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
rock='''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper='''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
list1=[scissors,rock,paper]
print(f"your choice is {list1[number]}")
import random
computer_number=random.randint(0,2)
print(f"computer choice is {list1[computer_number]}\n")
if number >2 or number<0:
print("game over")
elif number>computer_number:
if number==1 and computer_number==0:
print("you are lose")
elif number==2 and computer_number==1:
print("you are win")
elif number<computer_number:
if number==1 and computer_number==2:
print("you are lose")
elif number==0 and computer_number==1:
print("you are lose")
else:
print("it is a draw")
day5 平均身高和密码生成器
计算学生平均身高
print("welcome to the caculator")
students_height=[180,124,165,173,189,169,146]
total_height=0
counts=0
for height in students_height:
total_height=total_height+height
# total_height+=height
# x+=y x=x+y
counts=len(students_height)
average_height=round(total_height/counts,2)
print(f"the average height is {average_height}")
获取180,124,165,173,189,169,146的正则表达式\d+
fizzbuzz
for number in range(1,101):
if number%3==0 and number%5==0:
print("fizzbuzz")
elif number%3==0:
print("fizz")
elif number%5==0:
print("buzz")
else:
print(number)
密码生成器【easy】随机取数但按连接的顺序生成密码
numbers=['0','1','2','3','4','5','6','7','8','9']
letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','y','z','A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z']
symbols=['!','#','$',"%","&",",","*","+"]
print("welcome to the password generator")
num_letters=int(input("how many letters would you like in your password?\n"))
num_symbols=int(input("how many symbols would you like?\n"))
num_numbers=int(input("how many numbers would you like?\n"))
import random
letter=random.sample(letters,num_letters)
symbol=random.sample(symbols,num_symbols)
number=random.sample(numbers,num_numbers)
passwords=letter+symbol+number
password=''.join(passwords)
print(f"this is your password:{password}")
密码生成器【hard】生成随机密码并打乱顺序
numbers=['0','1','2','3','4','5','6','7','8','9']
letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','y','z','A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z']
symbols=['!','#','$',"%","&",",","*","+"]
print("welcome to the password generator")
num_letters=int(input("how many letters would you like in your password?\n"))
num_symbols=int(input("how many symbols would you like?\n"))
num_numbers=int(input("how many numbers would you like?\n"))
import random
letter=random.sample(letters,num_letters)
symbol=random.sample(symbols,num_symbols)
number=random.sample(numbers,num_numbers)
passwords=letter+symbol+number
random.shuffle(passwords)
password=''.join(passwords)
print(f"this is your password:{password}")
day7 刽子手猜词游戏
from word_list import word_list
import random
chosen_word=random.choice(word_list)
word_length=len(chosen_word)
dis=[]
print(chosen_word)
for letter in range(word_length):
dis+=["_"]
print(dis)
stage=['''
+---------+
|
|
|
|
|
================
''',
'''
+---------+
| |
| O
|
|
|
================
''',
'''
+---------+
| |
| O
| -
|
|
================
''',
'''
+---------+
| |
| O
| -|
|
|
================
''',
'''
+---------+
| |
| O
| -|-
|
|
================
''',
'''
+---------+
| |
| O
| -|-
| /
|
================
''',
'''
+---------+
| |
| O
| -|-
| / \
|
================
''']
lives=6
i=0
end_of_game=False
while not end_of_game:
guess=str(input("guess a letter:").lower())
for position in range(word_length):
letter=chosen_word[position]
if guess==letter:
dis[position]=letter
print(dis)
print(stage[-lives])
if guess not in chosen_word:
lives-=1
if lives==0:
end_of_game=True
print("you lose")
if "_" not in dis:
end_of_game=True
print("you win")
刽子手猜词游戏【引入模块】
from word_list import word_list
import random
chosen_word=random.choice(word_list)
word_length=len(chosen_word)
dis=[]
print(chosen_word)
from stage import stage,logo
print(logo)
for letter in range(word_length):
dis+=["_"]
print(dis)
lives=6
i=0
end_of_game=False
while not end_of_game:
guess=str(input("guess a letter:").lower())
for position in range(word_length):
letter=chosen_word[position]
if guess==letter:
dis[position]=letter
print(dis)
print(stage[-lives])
if guess not in chosen_word:
lives-=1
if lives==0:
end_of_game=True
print("you lose")
if "_" not in dis:
end_of_game=True
print("you win")
day8 caesar密码
caesar【解码和编码思路】
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','y','z']
direction=input("type 'encode'to encrypt,type 'decode'to decrypt:\n")
text=input("type your message:\n").lower()
shift=int(input("type the shift number:\n"))
# 编码
if direction=="encode":
encrypt=""
for z in text:
z=alphabet[alphabet.index(z)+shift]
encrypt+=z
print(encrypt)
# 解码
elif direction=="decode":
decrypt=""
for b in decrypt:
b=alphabet[decrypt.index(b)-shift]
decrypt+=b
print(decrypt)
else:
print("enter wrong")
caesar密码生成器
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','y','z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','y','z']
def caesar(text,shift,direction):
crypt=""
if direction=="decode":
shift*=-1
for i in text:
if i in alphabet:
i=alphabet[alphabet.index(i)+shift]
crypt+=i
else:
crypt+=i
print(crypt)
true_choice=True
while true_choice:
direction=input("type 'encode'to encrypt,type 'decode'to decrypt:\n")
text=input("type your message:\n").lower()
shift=int(input("type the shift number:\n"))%26
caesar(text,shift,direction)
choice=input("type 'yes' if you want to go again.otherwise type'no")
if choice=="no":
true_choice=False
print("goodbye")
day9 出价
print("welcome to the secret auction program.")
zhuangtai=True
while zhuangtai:
name=input("what is your name:\n")
bid=int(input("what is your bid:\n"))
choice=input("are there any other bidders?type'yse'or 'no'")
bid_items={}
bid_items[name]=bid
if choice=="no":
zhuangtai=False
winner=""
highest_price=0
for bidder in bid_items:
zanshi_price=bid_items[bidder]
if zanshi_price>highest_price:
highest_price=zanshi_price
winner=bidder
print(f"the winner is {winner} of bid with {highest_price}")
day10 判断每月天数和计算器
判断每月天数
def days_in_month(year,month):
month_days=[31,28,31,30,31,30,31,31,30,31,30,31]
if year%4==0 and(year%400==0 or year%100==0):
month_days[1]=29
return month_days[month-1]
year=int(input("enter a year:"))
month=int(input("enter a month:"))
days=days_in_month(year,month)
print(days)
calculator计算器
def add(num1,num2):
return num1+num2
def jian(num1,num2):
return num1-num2
def cheng(num1,num2):
return num1*num2
def chu(num1,num2):
return num1/num2
def calculator():
symbols={
"+":add,
"-":jian,
"*":cheng,
"/":chu
}
print("welcome to the calculator")
num1=int(input("what's your number?: "))
for symbol in symbols:
print(symbol)
condition=True
while condition:
choice=input("pick your choice: ")
num2=int(input("what's next number?: "))
calculation=symbols[choice]
answer=calculation(num1,num2)
print(f"{num1} {choice}{num2}={answer}")
if input("type 'y'to continue calculating with{answer} ,or type'n' to start to a new calculator")=='y':
num1=answer
else:
condition=False
print("byebye")
calculator()
day16 咖啡机
caidan = {
"espresso": {
"cailiao": {"water": 50, "coffee": 18, },
"cost": 15,
},
"cappuccino": {
"cailiao": {"water": 250, "milk": 50, "coffee": 24, },
"cost": 3,
},
"latte": {
"cailiao": {"water": 200, "milk": 150, "coffee": 24, },
"cost": 2.5,
},
}
ziyuan = {
"water": 300,
"milk": 200,
"coffee": 100,
}
lirun = 0
def is_enough(order_cailiao):
for item in order_cailiao:
if order_cailiao[item] >= ziyuan[item]:
print(f"sorry,this {item} is not enough")
return False
return True
def total_coins():
print("please insert coins")
total=0
total = int(input("how many dimes?:")) * 0.1
total += int(input("how many nickles?:")) * 0.05
total += int(input("how many pennies?:")) * 0.01
total = int(input("how many quarters?:"))* 0.25
return total
def is_price(money_recevied,drink_cost):
if money_recevied>=drink_cost:
# print("please wait a moment,coffee is cooking")
ling = round(money_recevied - drink_cost, 2)
print(f"this is your money {ling}")
global lirun
lirun += drink_cost
return True
else:
print("sorry,the money is not enough")
return False
def is_coffee(coffee_name,coffee_yuanliao):
for item in coffee_yuanliao:
ziyuan[item]-= coffee_yuanliao[item]
print(f"this is your {coffee_name}🍮,enjoy ")
is_on = True
while is_on:
choice = input("What would you like? (espresso/latte/cappuccino):")
if choice == "off":
is_on = False
elif choice == "report":
print(f"Milk: {ziyuan['milk']}")
print(f"Water: {ziyuan['water']}")
print(f"Coffee: {ziyuan['coffee']}")
print(f"Money: ${lirun}")
else:
drink = caidan[choice]
# print(drink)
# print(drink['cailiao'])
# is_enough(drink['cailiao'])
if is_enough(drink['cailiao']):
pay = total_coins()
print(pay)
if is_price(pay,drink['cost']):
is_coffee(choice,drink['cailiao'])
通过使用oop创建咖啡机
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
my_coffee_maker =CoffeeMaker()
my_money= MoneyMachine()
menu=Menu()
is_on = True
while is_on:
option=menu.get_items()
choice=input(f"What would you like?({option}):")
if choice =="off":
is_on=False
elif choice=="report":
my_coffee_maker.report()
my_money.report()
else:
drink=menu.find_drink(choice)
if my_coffee_maker.is_resource_sufficient(drink):
if my_money.make_payment(drink.cost):
my_coffee_maker.make_coffee(drink)
day17 quiz问答
question_data = [
{"text": "A slug's blood is green.", "answer": "True"},
{"text": "The loudest animal is the African Elephant.", "answer": "False"},
{"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
{"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"},
{"text": "In West Virginia, USA, if you accidentally hit an animal with your car,"
" you are free to take it home to eat.", "answer": "True"},
{"text": "In London, UK, if you happen to die in the House of Parliament, "
"you are entitled to a state funeral.", "answer": "False"},
{"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
{"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
{"text": "Google was originally called 'Backrub'.", "answer": "True"},
{"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
{"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"},
{"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"}
]
class Question:
def __init__(self, q_text,q_answer):
self.text =q_text
self.answer = q_answer
question_bank = []
for question in question_data:
question_text = question["text"]
question_answer = question["answer"]
my_question = Question(question_text,question_answer)
question_bank.append(my_question)
class Quizku:
def __init__(self,q_list):
self.question_number=0
self.question_list = q_list
self.score=0
def next_question(self):
current_question = self.question_list[self.question_number]
self.question_number +=1
choice = input(f"Q.{self.question_number}:{current_question.text}(True/False:)")
self.check_answer(choice,current_question.answer)
def still_has_questions(self):
return self.question_number<len(self.question_list)
def check_answer(self,choice,answer):
if choice.lower()== answer.lower():
self.score +=1
print("The answer is correct,got it")
else:
print("that's wrong.")
print(f"the correct answer is {answer}.")
print(f"your score is {self.score}/{self.question_number}")
print("\n")
new_quiz = Quizku(question_bank)
new_quiz.next_question()
while new_quiz.still_has_questions():
new_quiz.next_question()
更改quiz题库
https://opentdb.com/
生成quiz问题 在pycharm里格式化代码,并更改相关代码
day18 turtle 万花筒&波点图
turtle
from turtle import Turtle,Screen
timmy = Turtle()
my_screen = Screen()
timmy.shape('turtle')
timmy.color('red')
# TODO 正方形
# 移动100 向右旋转 90 循环四次
for _ in range(4):
timmy.forward(100)
timmy.right(90)
timmy.pendown()
# TODO 五边形
for _ in range(5):
timmy.forward(100)
timmy.right(360/5)
timmy.pendown()
import random
colors = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
# 每个图形里的每个边随机一个颜色
for sides in range(3,5):
for _ in range(sides):
color=random.choice(colors)
timmy.color(color)
timmy.forward(100)
timmy.right(360 / sides)
#随机选一个颜色,每个图形
for sides in range(3,5):
color = random.choice(colors)
timmy.color(color)
for _ in range(sides):
timmy.color(color)
timmy.forward(100)
timmy.right(360 / sides)
my_screen.exitonclick()
更改颜色模式:
注意:更改颜色模式是更改turtle模块
turtle.colormode(255)
def random_color():
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
color=(r,g,b)
return color
angle=[0,90,180,270]
timmy.setheading(random.choice(angle)) //随机选择某个角度
for _ in range(50):
timmy.color(random_color())
timmy.forward(30)
timmy.setheading(random.choice(angle))
make a spirograph
import turtle
from turtle import Turtle,Screen
import random
tim=Turtle()
tim_screen=Screen()
tim.speed('fast')
turtle.colormode(255)
def random_color():
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
color=(r,g,b)
return color
# for _ in range(30):
# tim.color(random_color())
# tim.setheading(tim.heading()+10)
# tim.circle(100)
# 偏移量是heading
# 每个圆之间的间隙,一个圆360°,判断要画多少次
# 怎么判断画多少次 360/间隙大小 定义一个函数,把间隙大小作为参数传入
def draw_count(size):
# count=int(360/size)
for _ in range(int(360/size)):
tim.color(random_color())
tim.setheading(tim.heading() + size)
tim.circle(100)
draw_count(20)
tim_screen.exitonclick()
painting 波点图
import turtle
import random
import colorgram
from turtle import Turtle,Screen
# turtle.shape('turtle')
my_screen =Screen()
# 安装colorgram包并导入
# 图片移动到同一层级
# colorgram.extract读取图片的颜色
# colors为列表,对列表里的每一个颜色都进行color.rgb【colorgram颜色格式化】
# colors=colorgram.extract('2.png',15)
# rgb_colors=[]
# for color in colors:
# r= color.rgb.r
# g = color.rgb.g
# b = color.rgb.b
# rgb_color=(r,g,b)
# rgb_colors.append(rgb_color)
# print(rgb_colors)
tom =Turtle()
turtle.colormode(255)
# tom.hideturtle()
# tom.penup()
# 更改起始位置
# 先移动到起始点,再从起始点沿着水平方向移动
# tom.penup()
tom.setheading(225)
tom.forward(480)
tom.setheading(0)
color_list=[(214, 217, 114), (170, 139, 190), (134, 195, 222), (238, 151, 173), (245, 235, 241), (147, 205, 226), (193, 180, 213), (184, 203, 88)]
dot_number=100
# 总数100个点,10*10的,间隔50,如果画满一行10就上移50,水平方向移动500,再往回跑点
for dot_count in range(1,dot_number+1):
tom.dot(20, random.choice(color_list))
tom.forward(50)
if dot_count % 10==0:
tom.setheading(90)
tom.forward(50)
tom.setheading(180)
tom.forward(500)
tom.setheading(0)
my_screen.exitonclick()
day 19 贪吃蛇&赛跑
wasd上下左右移动
from turtle import Turtle,Screen
tim = Turtle()
my_screen = Screen()
def forward():
tim.forward(10)
def backward():
tim.backward(10)
def turn_left():
tim.left(10)
def turn_right():
tim.right(10)
def clear():
tim.clear()
tim.penup()
tim.home()
tim.pendown()
my_screen.listen()
my_screen.onkey(forward,"w")
my_screen.onkey(backward,"s")
my_screen.onkey(turn_left,"a")
my_screen.onkey(turn_right,"d")
my_screen.onkey(clear,"c")
my_screen.exitonclick()
赛跑
import random
from turtle import Turtle,Screen
my_screen = Screen()
my_screen.setup(600,500)
# 创建赌注
choice= my_screen.textinput('make your bet','please input your choice')
colors=['red','yellow','green','blue','purple','orange']
turtles=[]
# y轴上创建多个不同位置的乌龟,y轴上的位置设置一个列表,然后再通过循环
y_position=[-200,-140,-80,-20,40,100]
for n in range(0,6):
object=Turtle(shape='turtle')
object.penup()
object.goto(-280,y_position[n])
object.color(colors[n])
turtles.append(object)
# 各乌龟随机移动
# 每只乌龟都要随机移动,并且一直循环下去,直到乌龟的移动距离等于屏幕的宽度为止
is_on =True
while is_on:
for object in turtles:
instance = random.randint(0, 10)
new_distance =object.forward(instance)
# 怎么判断乌龟停止 这个270的距离怎么取得,总宽度600/2=300,乌龟是60*40的对象,300-60/2=270
if object.xcor() >270 :
is_on =False
win_color=object.pencolor()
if win_color == choice:
print(f"you win.the{win_color}turtle is winner")
else:
print(f"you lose.the {win_color} turtle is winner")
my_screen.exitonclick()
贪吃蛇
from turtle import Turtle,Screen
import time
screen = Screen()
screen.setup(600,600)
screen.bgcolor("black")
screen.tracer(0)
positions=[(0,0),(-20,0),(-40,0)]
segments=[]
# 创建贪吃蛇的起始身子,创建3个正方形
for position in positions:
segment=Turtle(shape="square")
segment.penup()
segment.color("white")
segment.goto(position)
segments.append(segment)
# 贪吃蛇的移动和转向
# seg1向前移动20,seg2移动到seg1的位置,seg3移动到seg2d位置
is_on=True
while is_on:
screen.update()
time.sleep(0.1)
# 一直移动的循环
for seg in range(len(segments)-1,0,-1):
new_x = segments[seg-1].xcor()
new_y = segments[seg-1].ycor()
segments[seg].goto(new_x,new_y)
segments[0].forward(20)
# 当seg=2,seg2移动到seg1位置,取seg1的x和y坐标
# 当seg=3,seg3移动到seg2位置,取seg2的x和y坐标
# 当seg=1,移动20 【最后一个的时候要退出循环】
screen.exitonclick()
day20-21 贪吃蛇OOP
main.py
from turtle import Screen
import time
from snake import Snake
from food import Food
from score import Score
screen = Screen()
screen.setup(600, 600)
screen.bgcolor("black")
screen.tracer(0)
snake = Snake()
food = Food()
score = Score()
# 创建对象
# 定义鼠标事件
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
is_on = True
while is_on:
screen.update()
time.sleep(0.1)
snake.move()
# 检测食物与蛇相撞
if snake.head.distance(food) < 75:
food.refresh()
score.increase_score()
# 每次吃到食物蛇身长一节
snake.extend()
# 检测蛇头与墙壁相撞game over
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
is_on = False
score.game_over()
# 检测snake与蛇身相撞
for segment in snake.segments:
if segment == snake.head:
pass
elif snake.head.distance(segment) < 10:
is_on = False
score.game_over()
screen.exitonclick()
snake.py
from turtle import Turtle
positions = [(0, 0), (-20, 0), (-40, 0)]
distance=20
UP=90
DOWN=270
LEFT=180
RIGHT=0
# 常量定义在这里
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head =self.segments[0]
# self.segments[0] 这个后面一直在调用,赋值给一个变量
# 对象的初始化设置
# 蛇的初始属性【创建蛇的身子-高阶函数,先定义创建蛇身的方法,再在初始化设置调用】,【设置蛇头,不理解】
# 定义蛇能做什么的方法【蛇的移动】
def create_snake(self):
for position in positions:
segment = Turtle(shape="square")
segment.penup()
segment.color("white")
segment.goto(position)
self.segments.append(segment)
def move(self):
for seg in range(len(self.segments)-1,0,-1):
new_x = self.segments[seg-1].xcor()
new_y = self.segments[seg-1].ycor()
self.segments[seg].goto(new_x,new_y)
self.segments[0].forward(distance)
# 新长一节蛇身,再追加到蛇尾上
def add_segment(self,position):
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
# 新长的一节蛇身放在哪,给予一个参数position
new_segment.goto(position)
# 再将新的一节蛇身添加到列表里
self.segments.append(new_segment)
# 扩展蛇身
def extend(self):
# 获取当前蛇尾的位置
# self.segments[-1].positions
self.add_segment(self.segments[-1].position())
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != LEFT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != RIGHT:
self.head.setheading(RIGHT)
# 定义蛇的上下左右移动
# 上90 下270 左180 右0 逆时针方向
# 上90 下270 右180 左0 顺时针方向
food.py
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
# 继承Turtle类的方法和属性
self.shape("circle")
self.penup()
self.shapesize(0.5, 0.5)
self.color("red")
self.refresh()
# 食物重新刷新
def refresh(self):
random_x = random.randint(-280, 280)
random_y = random.randint(-280, 280)
self.goto(random_x, random_y)
score.py
from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.hideturtle()
self.penup()
self.goto(0, 270)
self.score = 0
self.scoreboard()
def scoreboard(self):
self.write(f"score:{self.score}",align="center",font=("arial",18,"normal"))
def increase_score(self):
self.score += 1
self.clear()
self.scoreboard()
def game_over(self):
self.goto(0,0)
self.write("Game Over", align="center", font=("arial", 18, "normal"))