1
如何阻止玩家角色離開屏幕邊緣並停止在邊界?停止sprite走出tkinter窗口
這裏是我的代碼:
from tkinter import *
HEIGHT = 800
WIDTH = 500
window = Tk()
window.title('Colour Shooter')
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='black')
c.pack()
ship_id = c.create_rectangle(0, 0, 50, 50, fill='white')
MID_X = (WIDTH/2)-25
c.move(ship_id, MID_X, HEIGHT-50)
left_bound= c.create_line(0, 0, 800, 0,)
right_bound= c.create_line(500, 0, 500, 500,)
SHIP_SPD = 10
def move_ship(event):
if event.keysym == 'Left':
c.move(ship_id, -SHIP_SPD, 0)
elif event.keysym == 'Right':
c.move(ship_id, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)
from math import sqrt
def collision_bound():
dist_left = left_bound.x + ship_id.x
if dist_left < 0:
c.move(ship_id, 50, HEIGHT-50)
dist_right = right_bound.x - ship_id.x
if dist_right > WIDTH:
c.move(ship_id, WIDTH - 50, HEIGHT-50)
我很新的蟒蛇和書我沒能教我如何解決這個問題。所以任何幫助將不勝感激
謝謝你完美的作品 –