Python代码编程基础第12课 海底世界(1)

知识要点

  1. 逻辑运算符 and
  2. 逻辑运算符 or
  3. 逻辑运算符 not
  4. addshape()函数

一、PPT课件

二、知识要点

1.逻辑运算符

运算符 描述 逻辑表达式
and 布尔“与” x and y
or 布尔“或” x or y
not 布尔“非” not x

2.addshape()函数

三、代码示例

1.case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

# -*- coding: utf-8 -*-
import time
import turtle as t
import random

t.bgpic("bg1.png")
t.shape("turtle")
t.shapesize(2, 2)
t.color("dark blue")
t.penup()


# 按键交互
def turnLeft():
t.left(30)


def turnRight():
t.right(30)


t.listen()
t.onkeypress(turnLeft, "Left")
t.onkeypress(turnRight, "Right")

# 游戏标题
titleT = t.Turtle()
titleT.penup()
titleT.color("gold")
titleT.hideturtle()
titleT.goto(500, 400)
titleT.write("按左右箭头控制海龟的运动方向", align="center",
font=("Times", 16, "bold"))

# 加载食物图片
food = t.Turtle()
t.addshape('food2.gif')
t.addshape('yu2.gif')
t.addshape('xia2.gif')
shapeList = ['food2.gif', 'yu2.gif', 'xia2.gif']


def drawfood():
food.hideturtle()
food.pu()
x = random.randint(-600, 600)
y = random.randint(-400, 400)
t.colormode(255)
food.goto(x, y)
food.shape(shapeList[random.randint(0, 2)])
food.showturtle()


# 小球碰撞检测
def isCollided(a, b):
if a.distance(b) < 15:
return True


# 初始化各种变量
drawfood()

while True:
t.forward(2)
result = isCollided(t, food)

if result == True:
food.clear()
drawfood()

t.done()

2.homework

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8
# 此为第12课作业水族箱的参考答案

import turtle as t1
import random

t1.bgpic('bgpic.png')

t1.addshape('fish.gif')
t1.shape('fish.gif')

t1.colormode(255)


def drawFish(x, y):
# print(x, y)
if (-750 < x < -75 or 80 < x < 760) and (-190 < y < 180):
t1.tracer(0)
t1.pu()
t1.goto(x, y)
t1.seth(random.randint(0, 360))
t1.pd()
t1.fillcolor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
t1.begin_fill()
for i in range(2):
t1.forward(30)
t1.right(60)
t1.forward(30)
t1.right(120)

t1.left(120)
for j in range(3):
t1.forward(10)
t1.left(120)
t1.end_fill()
t1.tracer(1)


t1.onscreenclick(drawFish)

t1.done()