﻿ Program Arcade Games With Python And Pygame

# Program Arcade GamesWith Python And Pygame

 < Previous Home Next >

# Chapter 9: 函数

## 9.1 函数入门

pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
pygame.draw.polygon(screen, GREEN, [[150, 400], [75, 250], [0, 400]])
pygame.draw.polygon(screen, GREEN, [[140, 350], [75, 230], [10, 350]])


def draw_tree():
pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
pygame.draw.polygon(screen, GREEN, [[150, 400], [75, 250], [0, 400]])
pygame.draw.polygon(screen, GREEN, [[140, 350], [75, 230], [10, 350]])


draw_tree()


draw_tree()
draw_house()
draw_car()
draw_killer_bunny()


## 9.2 Function Parameters

def draw_tree(screen, x, y):
pygame.draw.rect(screen, BROWN, [60+x, 170+y, 30, 45])
pygame.draw.polygon(screen, GREEN, [[150+x,170+y],[75+x,20+y], [x,170+y]])
pygame.draw.polygon(screen, GREEN, [[140+x,120+y], [75+x,y], [10+x,120+y]])


draw_tree(screen, 0, 230)
draw_tree(screen, 200, 230)
draw_tree(screen, 400, 230)


def volume_sphere(radius):
pi = 3.141592653589
volume = (4 / 3) * pi * radius ** 3
print("The volume is", volume)


volume_sphere(22)


def volume_cylinder(radius, height):
pi = 3.141592653589
volume = pi * radius ** 2 * height
print("The volume is", volume)


volume_cylinder(12, 3)


## 9.3 返回数值

def volume_cylinder(radius, height):
pi = 3.141592653589
volume = pi * radius ** 2 * height
return volume


Return不是一个函数，也不使用圆括号。不要写成return(volume).

six_pack_volume = volume_cylinder(2.5, 5) * 6


volume_cylinder返回的值会代入等式并乘以6。

prints一个值的函数和returns一个值的函数有巨大的区别。 观察下下段代码并运行试试卡。

# 打印结果的函数
def sum_print(a, b):
result = a + b
print(result)

# 返回解雇的函数
def sum_return(a, b):
result = a + b
return result

# 这可以打印4+4的和
sum_print(4, 4)

# 而这不可以
sum_return(4, 4)

# 这不会不会把和赋值给x1
# x1实际上得到的值是'None'
x1 = sum_print(4, 4)

# 这个可以
x2 = sum_return(4, 4)


def calculate_average(a, b):
""" 计算两个数的平均值 """
result = (a * b) / 2
return result

# 假设你这有些代码
x = 45
y = 56

# 等下，我如何打印结果?
calculate_average(x, y)


def calculate_average(a, b):
""" 计算两个数的平均值 """
result = (a * b) / 2
return result

# 假设你这里有些代码
x = 45
y = 56

average = calculate_average(x, y)
print(average)


## 9.4 函数描述

Python中的函数通常以一句注释来作为第一条语句。 这条注释用3个引号包围起来，被叫做docstring。就像这个样子:

def volume_cylinder(radius, height):
"""Returns volume of a cylinder given radius, height."""
pi = 3.141592653589
volume = pi * radius ** 2 * height
return volume


## 9.5 变量范围

# 定义一个简单的函数
# 把x设置成22
def f():
x = 22

# 调用这个函数
f()
# 这会失败，因为x只存在于f()之中
print(x)


# 创造一个变量x，并设为44
x = 44

# 定义一个打印x的函数
def f():
print(x)

# 调用这个函数
f()


# 创造一个变量x，并设为44
x = 44

# 定义一个打印x的函数
def f():
x += 1
print(x)

# 调用这个函数
f()


## 9.6 通过复制来传递

# 定义一个打印x的函数
def f(x):
x += 1
print(x)

# 设置y
y = 10
# 调用这个函数
f(y)
# 打印y看看值是否改变了
print(y)


y的值并没有改变，即使f()函数增加了传递给它的值。每一个在函数中列为参数的变量是一个崭新的变量。 那个变量的值是从被调用的地方复制过来的。

# 定义一个打印x的函数
def f(x):
x += 1
print(x)

# 设置x
x = 10
# 调用这个函数
f(x)
# 打印x看看值是否改变了
print(x)


## 9.7 函数调用函数

def arm_out(whichArm, palmUpOrDown):
# 代码写在这里

def hand_grab(hand, arm):
# 代码写在这里


def macarena():
arm_out("right", "down")
arm_out("left", "down")
arm_out("right", "up")
arm_out("left", "up")
hand_grab("right", "left arm")
hand_grab("left", "right arm")
# 等等


## 9.8 主函数和全局

def main():
print("Hello world.")

main()


def main():
print("Hello world.")

if __name__ == "__main__":
main()


## 9.9 举例

# 例1
def a():
print("A")

def b():
print("B")

def c():
print("C")

a()

# 例2
def a():
b()
print("A")

def b():
c()
print("B")

def c():
print("C")

a()

# 例3
def a():
print("A")
b()

def b():
print("B")
c()

def c():
print("C")

a()

# 例4
def a():
print("A start")
b()
print("A end")

def b():
print("B start")
c()
print("C end")

def c():
print("C start and end")

a()

# 例5
def a(x):
print("A start, x =",x)
b(x + 1)
print("A end, x =",x)

def b(x):
print("B start, x =",x)
c(x + 1)
print("C end, x =",x)

def c(x):
print("C start and end, x =",x)

a(5)

# 例6
def a(x):
x = x + 1

x = 3
a(x)

print(x)

# 例7
def a(x):
x = x + 1
return x

x = 3
a(x)

print(x)

# 例8
def a(x):
x = x + 1
return x

x = 3
x = a(x)

print(x)

# 例9
def a(x, y):
x = x + 1
y = y + 1
print(x, y)

x = 10
y = 20
a(y, x)

print(z)

# 例10
def a(x, y):
x = x + 1
y = y + 1
return x
return y

x = 10
y = 20
z = a(x, y)

print(z)

# 例11
def a(x, y):
x = x + 1
y = y + 1
return x, y

x = 10
y = 20
z = a(x, y)

print(z)

# 例12
def a(x, y):
x = x + 1
y = y + 1
return x, y

x = 10
y = 20
x2, y2 = a(x, y) # Most computer languages don't support this

print(x2)
print(y2)

# 例13
def a(my_data):
print("function a, my_data =  ", my_data)
my_data = 20
print("function a, my_data =  ", my_data)

my_data = 10

print("global scope, my_data =", my_data)
a(my_data)
print("global scope, my_data =", my_data)

# 例14
def a(my_list):
print("function a, list =  ", my_list)
my_list = [10, 20, 30]
print("function a, list =  ", my_list)

my_list = [5, 2, 4]

print("global scope, list =", my_list)
a(my_list)
print("global scope, list =", my_list)

# 例15
# 新概念!
# 更多介绍在第12章节
def a(my_list):
print("function a, list =  ", my_list)
my_list[0] = 1000
print("function a, list =  ", my_list)

my_list = [5, 2, 4]

print("global scope, list =", my_list)
a(my_list)
print("global scope, list =", my_list)

"""
This is a sample text-only game that demonstrates the use of functions.
The game is called "Mudball" and the players take turns lobbing mudballs
at each other until someone gets hit.
"""

import math
import random

def print_instructions():
""" This function prints the instructions. """

# You can use the triple-quote string in a print statement to
# print multiple lines.
print("""
Welcome to Mudball! The idea is to hit the other player with a mudball.
Enter your angle (in degrees) and the amount of PSI to charge your gun
with.
""")

def calculate_distance(psi, angle_in_degrees):
""" Calculate the distance the mudball flies. """
return distance

def get_user_input(name):
""" Get the user input for psi and angle. Return as a list of two
numbers. """
# Later on in the 'exceptions' chapter, we will learn how to modify
# this code to not crash the game if the user types in something that
# isn't a valid number.
psi = float(input(name + " charge the gun with how many psi? "))
angle = float(input(name + " move the gun at what angle? "))
return psi, angle

def get_player_names():
""" Get a list of names from the players. """
print("Enter player names. Enter as many players as you like.")
done = False
players = []
while not done:
player = input("Enter player (hit enter to quit): ")
if len(player) > 0:
players.append(player)
else:
done = True

print()
return players

def process_player_turn(player_name, distance_apart):
""" The code runs the turn for each player.
If it returns False, keep going with the game.
If it returns True, someone has won, so stop. """
psi, angle = get_user_input(player_name)

distance_mudball = calculate_distance(psi, angle)
difference = distance_mudball - distance_apart

# By looking ahead to the chapter on print formatting, these
# lines could be made to print the numbers is a nice formatted
# manner.
if difference > 1:
print("You went", difference, "yards too far!")
elif difference < -1:
print("You were", difference * -1, "yards too short!")
else:
print("Hit!", player_name, "wins!")
return True

print()
return False

def main():
""" Main program. """

# Get the game started.
print_instructions()
player_names = get_player_names()
distance_apart = random.randrange(50, 150)

# Keep looking until someone wins
done = False
while not done:
# Loop for each player
for player_name in player_names:
# Process their turn
done = process_player_turn(player_name, distance_apart)
# If someone won, 'break' out of this loop and end the game.
if done:
break

if __name__ == "__main__":
main()