繁体   English   中英

弹跳球游戏 tkinter 画布

[英]Bouncing ball game tkinter canvas

我用 python 编写了一个游戏,其中的目标是将球从平台上弹开。 一切都很好,但平台的运动不是那么流畅。 你能帮我让平台运动更流畅吗? 如果代码不太清楚,我很抱歉,但我是python的新手

import tkinter as tk
import random

root = tk.Tk()

width = 900
height = 500

canvas = tk.Canvas(root, bg='white', width=width, height=height)
canvas.pack()

x = random.randrange(700)

ball = canvas.create_oval(x+10, 10, x+50, 50, fill='green')

platform_y = height - 20
platform = canvas.create_rectangle(width//2-50, platform_y, width//2+50, platform_y+10, fill='black')

xspeed = 2
yspeed = 2
skore = 0
body = 0

def move_ball():
  global xspeed
  global yspeed
  x1, y1, x2, y2 = canvas.coords(ball)
  if x1 <= 0 or x2 >= width:
    xspeed = -xspeed
  if y1 <= 0:
    yspeed = 10
  elif y2 == platform_y: 
    cx = (x1 + x2) // 2
    px1, _, px2, _ = canvas.coords(platform)
    if px1 <= cx <= px2:
      yspeed = -10
    else:
      canvas.create_text(width//2, height//2, text='Game Over', font=('Arial Bold', 32), fill='red')
      return
  canvas.move(ball, xspeed, yspeed)
  canvas.after(20, move_ball)

def board_right(event):
  x1, y1, x2, y2 = canvas.coords(platform) 
  if x2 < width:
    dx = min(width-x2, 10)
    canvas.move(platform, dx, 0)

def board_left(event):
  x1, y1, x2, y2 = canvas.coords(platform)
  if x1 > 0:
    dx = min(x1, 10)
    canvas.move(platform, -dx, 0)

canvas.bind_all('<Right>', board_right)
canvas.bind_all('<Left>', board_left)

move_ball()

root.mainloop()

问题是平台的速度取决于键盘的自动重复速度。

不是为每个<Right><Left>事件移动一次,而是使用按键启动平台向所需方向移动,然后释放按键停止平台移动。 然后,使用after向给定方向重复移动平台。

例子:

after_id = None
def platform_move(direction):
    """
    direction should be -1 to move left, +1 to move right,
    or 0 to stop moving
    """
    global after_id
    speed = 10
    if direction == 0:
        canvas.after_cancel(after_id)
        after_id = None
    else:
        canvas.move(platform, direction*speed, 0)
        after_id = canvas.after(5, platform_move, direction)

canvas.bind_all("<KeyPress-Right>", lambda event: platform_move(1))
canvas.bind_all("<KeyRelease-Right>", lambda event: platform_move(0))
canvas.bind_all("<KeyPress-Left>", lambda event: platform_move(-1))
canvas.bind_all("<KeyRelease-Left>", lambda event: platform_move(0))

上面的代码不能处理您可能同时按下两个键的情况,但可以通过一些额外的逻辑来处理。 重点是展示如何使用键来启动和停止动画。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM