n = 10
high_all = 0 #第n次落地时走过的长度
high_each = 0 #每次落地的高度
def ball_lands(n):
global high_all, high_each, high
#小球第一次落地时
if n == 0:
high_each = high
high_all += high_each
#print('1', high_each, high_all)
return high_each
#从小球第n次落地往前推
high_each = high * (1 / 2) ** n
print(u'第%d次小球弹起的高度为:%.2f' %(n, high_each))
high_all += high_each * 2
#print('2', high_each, high_all)
ball_lands(n - 1)
ball_lands(n)
print(u'小球落地%d次,共经过%.2f米。' % (n,high_all))
应该可以的。设计一个阵列,描述墙壁和空间,通过算法使阵列可以旋转。
小球从入口进入以后,在阵列里滚动,通过计算重力和在斜面上的分力,算出小球运动的方向和速度。
到达阵列墙壁时,根据速度和方向以及墙壁的角度,计算反弹的方向和速度。直到小球滚出阵列。
我有一个Python3写的匀速运动弹球的代码,可以参考下
import turtledef stop():
global running
running = False
def main():
global running
screenx, screeny = turtle.Screen().screensize()
x, y = turtle.pos()
stepx = 10
stepy = 10
print(x,y,screenx,screeny)
turtle.clear()
turtle.speed(0)
#turtle.Screen().bgcolor("gray10")
#turtle.Screen().tracer(False)
turtle.up()
turtle.shape("circle")
turtle.shapesize(5,5)
turtle.left(45)
while True:
if x+5>screenx:
stepx = -stepx
turtle.left(90)
if y+5>screeny:
stepy = -stepy
turtle.left(90)
if x+5<-screenx:
stepx = -stepx
turtle.left(90)
if y+5<-screeny:
stepy = -stepy
turtle.left(90)
turtle.fd(10)
x += stepx
y += stepy
if __name__=='__main__':
print(main())
turtle.done()
Python程序开发之简单小程序实例
(11)小 游戏 -跳动的小球
一、项目功能
用户控制挡板来阻挡跳动的小球。
二、项目分析
根据项目功能自定义两个类,一个用于控制小球在窗体中的运动,一个用于接收用户按下左右键时,挡板在窗体中的运动。在控制小球的类中,我们还需要考虑当小球下降时,碰到挡板时的位置判断。
三、程序源代码
源码部分截图:
源码:
#!/usr/bin/python3.6
# -*- coding: GBK -*-
#导入相应模块
from tkinter import *
import random
import time
#自定义小球的类 Ball
class Ball:
# 初始化
def __init__(self,canvas,paddle,color):
#传递画布值
self.canvas=canvas
#传递挡板值
self.paddle=paddle
#画圆并且保存其ID
self.id=canvas.create_oval(10,10,25,25,fill=color)
self.canvas.move(self.id,245,100)
#小球的水平位置起始列表
start=[-3,-2,-1,1,2,3]
#随机化位置列表
random.shuffle(start)
self.x=start[0]
self.y=-2
self.canvas_heigh=self.canvas.winfo_height()#获取窗口高度并保存
self.canvas_width=self.canvas.winfo_width()
#根据参数值绘制小球
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id)#返回相应ID代表的图形的当前坐标(左上角和右上角坐标)
#使得小球不会超出窗口
pad=self.canvas.coords(self.paddle.id)#获取小球挡板的坐标
if pos[1]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]