别让精灵离开风

2024-05-12 13:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能阻止玩家角色离开屏幕的边缘并在边界处停下来?在

这是我的代码:

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)

我对python还很陌生,这本书没有教我如何解决这个问题。所以任何帮助都会很感激的


Tags: righteventidmoveifdistcreatewindow
1条回答
网友
1楼 · 发布于 2024-05-12 13:03:54

您可以使用c.coords(ship_id)来获取船的位置,然后检查是否允许它们移动。在

尝试更换

if event.keysym == 'Left':
    c.move(ship_id, -SHIP_SPD, 0)
elif event.keysym == 'Right':
    c.move(ship_id, SHIP_SPD, 0)

^{pr2}$

它只允许玩家在其位置大于左边界的x位置时向左移动,并且只允许玩家在其位置小于右边界的x位置时向右移动。在

但是,由于船的位置是由左侧决定的,您可能需要将其更改为

elif event.keysym == 'Right' and shipPosition[0] < c.coords(right_bound)[0] - 50:
    c.move(ship_id, SHIP_SPD, 0)

其中50是船的大小。在

相关问题 更多 >