《Python遊戲趣味程式設計》標準IDE運行遊戲程式碼的配置方法
首先,用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,還需要處理下中文字串的相關問題。
如果是初學者,也可以使用Mu Editor(Code With Mu),首先選擇模式為Pygame Zero,然後輸入以上在標準編輯器中的程式碼,就可以正常運行了: