前回、マップ上に敵を出現させてプレイヤーが衝突したらゲームオーバーになるようにしました。
現状敵は、その場に立ち止まったままで動くことはないので、乱数を使って敵を移動させます。
敵の移動をランダムにして不規則なタイミングで動かす方法
毎回同じスクリプトに追記してきたので、敵の動きに関する部分だけ抜粋してプログラムを公開します。流石にごちゃごちゃして分かりにくくなってくるので・・・。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tkinter | |
import random | |
ani = 0 | |
ex = 150 #敵のx座標 | |
ey = 80 #敵のy座標 | |
scene = 0 #シーンを番号で管理する | |
def main(): | |
move() | |
animation() | |
def animation(): | |
global ani,ex,ey | |
canvas.create_image(ex, ey, image=enemy,tag="PLAYER") | |
def move(): | |
global px,py,key,ani,scene | |
canvas.delete("PLAYER") | |
if scene == 0: | |
move_enemy() | |
root.after(100,main) | |
def move_enemy(): | |
global ex,ey,scene | |
muki = random.randint(0,7) | |
if muki == 0:#上 | |
ey = ey - 10 | |
if muki == 1:#下 | |
ey = ey + 10 | |
if muki == 2:#右 | |
ex = ex + 10 | |
if muki == 3:#左 | |
ex = ex - 10 | |
if ex < 10: | |
ex = ex + 10 | |
if ex > 290: | |
ex = ex - 10 | |
if ey < 10: | |
ey = ey + 10 | |
if ey > 290: | |
ey = ey - 10 | |
root = tkinter.Tk() | |
root.title("敵のランダム移動") | |
canvas = tkinter.Canvas(width=300,height=300) | |
canvas.pack() | |
bg = tkinter.PhotoImage(file="field2.png") | |
canvas.create_image(150,150,image=bg) | |
enemy = tkinter.PhotoImage(file="obake_01.png") | |
main() | |
root.mainloop() |
move_enemy関数が敵の動きに関わる部分ですね。プレイヤーも敵も上下左右4方向に移動するようになっているので「random.randint(0,3)」で各方向に移動させるようにするのが簡単でしょう。
0・・・上移動
1・・・下移動
2・・・右移動
3・・・左移動
といった感じですね。単純に移動させたいだけであれば、上記のようにすれば良いと思います。
ただ、私は「random.randint(0,7)」にしています。このように範囲を広げることで、ランダム且つ不規則な動きにすることが出来ます。規則的に動かしたいかどうかの違いですね。
基本的にメイン関数は、root.afterを使って繰り返し実行する必要があるため、もっとゆっくりと敵を動かしたい場合は、別途タイマー変数などを用意すると良いでしょうね。
後は、敵が範囲外に消えないように各座標をチェックして、移動させないようにしています。
アニメーションを付けてないので不気味ですが、まさにお化けらしい動きになりました。