|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color,Rectangle
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.label import Label
import random
FPS = 6
SPEED = 40
WIDTH = Window.size[0]
HEIGHT = Window.size[1]
class MainBoard(Widget):
head = [(WIDTH/2)//SPEED*SPEED,(HEIGHT/2)//SPEED*SPEED]
body = [[(WIDTH/2)//SPEED*SPEED + SPEED,(HEIGHT/2)//SPEED*SPEED]]
apples = []
direction = "left"
touchDown = []
GameOcer = False
def on_touch_down(self,touch):#点击开始
self.touchDown = [touch.pos[0],touch.pos[1]]
def on_touch_up(self,touch):
hor = touch.pos[0] - self.touchDown[0]
ver = touch.pos[1] - self.touchDown[1]
if abs(hor)>abs(ver):
if hor>0:
self.direction = "right"
else:
self.direction = "left"
else:
if ver>0:
self.direction = "up"
else:
self.direction = "down"
def createApple(self):
while True:
newApple = [random.randint(0,WIDTH-SPEED)//SPEED*SPEED,random.randint(0,HEIGHT-SPEED)//SPEED*SPEED]
if newApple not in self.apples and newApple != self.head and newApple not in self.body:
self.apples.append(newApple)
break
def update(self,dt):
self.canvas.clear()
self.clear_widgets()
if self.GameOver:
self.add_widget(Label(text = "GameOver! score: % d"%(len(self.body) - 1), pos = (WIDTH/3,HEIGHT/2),font_size = 50))
else:
self.body.insert(0,[self.head[0],self.head[1]])
if self.direction == "left":
self.head[0] -= SPEED
elif self.direction == "right":
self.head[0] += SPEED
elif self.directiom == "up":
self.head[1] += SPEED
elif self.direction == "down":
self.head[1] -= SPEED
if self.head[0]<0 or self.head[0]>WIDTH-SPEED or self.head[1]<0 or self.head[1]>HEIGHT-SPEED or self.head in self.body:
self.GameOver = True
if self.head not in self.apples:
self.body.pop(-1)
else:
self.apples.renmove(self.head)
self.createApple()
with self.canvas:
Color(0.6,0.6,0.6)
Rectangle(pos=self.head,size=(SPEED,SPEED))
with self.canvas:
Color(1,1,1)
for i in self.body:
Rectangle(pos=i,size=(SPEED,SPEED))
with self.canvas:
Color(1,0,0)
for apple in self.apples:
Rectangle(pos=apple,size=(SPEED,SPEED))
class SnakeApp(App):
def build(self):
board = MainBoard()
board.createApple()
Clock.schedule_interval(board.update,1/FPS)
return board
运行以后就只有一个黑色的界面,其他什么都没有,请问是什么原因?
你这个有两点错误,
1、需要运行,你只是定义了两个类,却没有去运行,在文件末尾加上
if __name__ == '__main__':
SnakeApp().run()
2、你有些地方写错了,比较粗心
第69行的renmove改为remove
第60行的directiom改为direction
第23行的GameOcer改为GameOver
|
|