首先,用Pip安装pygame、pygame zero两个库:

pip install pygame

pip install pygame zero

第2章在编程猫海龟编辑器下的代码如下:

import pgzrun
WIDTH = 800
HEIGHT = 600
x = WIDTH/2
y = HEIGHT/2
speed_x = 3
speed_y = 5
r = 30
def draw():
    screen.fill('white')
    screen.draw.filled_circle((x, y), r, 'red')
def update():
    global x,y,speed_x,speed_y
    x = x+speed_x
    y = y+speed_y
    if x >= WIDTH-r or x <= r:
        speed_x = -speed_x
    if y >= HEIGHT-r or y <= r:
        speed_y = -speed_y
pgzrun.go()

需要修改,去掉第一行、最后一行:

WIDTH = 800
HEIGHT = 600
x = WIDTH/2
y = HEIGHT/2
speed_x = 3
speed_y = 5
r = 30
def draw():
    screen.fill('white')
    screen.draw.filled_circle((x, y), r, 'red')
def update():
    global x,y,speed_x,speed_y
    x = x+speed_x
    y = y+speed_y
    if x >= WIDTH-r or x <= r:
        speed_x = -speed_x
    if y >= HEIGHT-r or y <= r:
        speed_y = -speed_y

假设用Python官方IDE中新建文件,拷贝代码,保存到F盘根目录下的tt.py文件。

切换到代码所在的F盘,运行 pgzrun tt.py

就可以看到弹跳的小球了:

另外,海龟编辑器对中文字符串支持比较好。使用Python官方IDE,还需要处理下中文字符串的相关问题。

更多推荐

《Python游戏趣味编程》标准IDE运行游戏代码的配置方法