让球在屏幕上反弹

时间:2018-01-25 20:12:44

标签: python tkinter tkinter-canvas

我正在尝试用Python制作一个非常简单的球和桨游戏,并让球在屏幕上移动,桨从左向右移动。但是,球移动并击中屏幕的底部并且不会改变方向,它会停止并滑向墙壁。

任何帮助或建议将不胜感激。这是代码:

from tkinter import Canvas, Tk
import random

canvas_width = 800
canvas_height = 400

root = Tk()
root.title("Ball and Paddle")
c = Canvas(root,width=canvas_width,height=canvas_height,background='orange')
c.pack()

paddle_color = 'blue'
paddle_width = 60
paddle_height = 10
paddle_start_x = canvas_width/2 - paddle_width/2
paddle_start_y = canvas_height - paddle_height - 20
paddle_start_x2 = canvas_width/2 + paddle_width/2
paddle_start_y2 = canvas_height - 20

paddle = c.create_rectangle(paddle_start_x,paddle_start_y,\
                        paddle_start_x2,paddle_start_y2,\
                        fill='blue', width=0)

ball_color = 'green'
ball_width = 20
ball_height = 20
ball_start_x1 = canvas_width/2 - ball_width/2
ball_start_y1 = canvas_height/2 - ball_height/2
ball_start_x2 = canvas_width/2 + ball_width/2
ball_start_y2 = canvas_height/2 + ball_height/2
ball_speed = 5

ball = c.create_oval(ball_start_x1, ball_start_y1, \
                 ball_start_x2, ball_start_y2, \
                 fill = ball_color, width = 0)
dx = 1
dy = 1

def ball_move():
    global dx, dy
    (bx1,by1,bx2,by2) = c.coords(ball)
    c.move(ball, dx, dy)
    if bx1 <= 0:
    dx = -dx
    if bx2 >= canvas_width:
        dx = -dx
    if by1 <= 0:
        dy = -dy
    if by2 >= canvas_height:
        dy = -dy
    root.after(ball_speed, ball_move)

def move_left(event):
    (x1,y1,x2,y2) = c.coords(paddle)
    if x1>0:
        c.move(paddle,-20,0)

def move_right(event):
    (x1,y1,x2,y2) = c.coords(paddle)
    if x2 < canvas_width:
        c.move(paddle, 20, 0)

c.bind('<Left>',move_left)
c.bind('<Right>',move_right)
c.focus_set()

root.after(ball_speed, ball_move)

root.mainloop()

2 个答案:

答案 0 :(得分:2)

(我假设if bx1 <= 0:缩进问题实际上并未存在于您的真实代码中,而且在撰写此帖时只是一个转录错误。

这是因为球越来越多了#34;进入屏幕的边框,当by2的值为401时。你反转dy,这使得它在下一帧移动到400。但是你再次反转dy ,所以它又回到401。

这是因为您正在创建b *变量,然后移动球,然后对b *变量进行边界检查。你有效地检查了前一帧球的位置。

尝试在边界检查后移动move来电。

def ball_move():
    global dx, dy
    (bx1,by1,bx2,by2) = c.coords(ball)
    if bx1 <= 0:
        dx = -dx
    if bx2 >= canvas_width:
        dx = -dx
    if by1 <= 0:
        dy = -dy
    if by2 >= canvas_height:
        dy = -dy
    c.move(ball, dx, dy)
    root.after(ball_speed, ball_move)

现在你的球应该反弹。

enter image description here

答案 1 :(得分:0)

缩进问题:

def ball_move():
    global dx, dy
    (bx1,by1,bx2,by2) = c.coords(ball)
    c.move(ball, dx, dy)
    if bx1 <= 0:
    dx = -dx
    if bx2 >= canvas_width:
    ..snippet..

应该是:

def ball_move():
    global dx, dy
    (bx1,by1,bx2,by2) = c.coords(ball)
    c.move(ball, dx, dy)
    if bx1 <= 0:
        dx = -dx              # indent corrected here!
    if bx2 >= canvas_width:
    ..snippet..