Source

wd_pys60 / wd_pygame.py

Full commit
# -*- coding: utf-8 -*-
import pygame
blue = [ 0, 0,255]
red = [ 0, 255,0]
green = [ 255, 0,0]
black = [ 0, 0,0]
def space(a,b):
    #计算两点的距离
    space=(a[0]-b[0])**2+(a[1]-b[1])**2
    #print space
    return space
import math
# import appuifw2 as appuifw
# from graphics import *
# import e32
# from key_codes import *
import time
import random
def int2rgblist(i):
    h=hex(int(i))
#    return h
    res=list(h[2:])
    while len(res)<6:
        res.insert(0,"0")
#    res.insert(0,"#")
    res=''.join(res)
#    print res
    res=[int(res[0:1],16),int(res[2:3],16),int(res[4:5],16)]
    return [red,green,blue][res.index(max(res))]
    # return [int(res[0:1],16),int(res[2:3],16),int(res[4:5],16)]
#from Tkinter import *  
class Image:
    def  __init__(self,canvas,width=320, height=240):
        self.width,self.height,self.canvas=width,height,canvas
    def point(self,pos,color=0xffffff,width=1):
        pygame.draw.circle(self.canvas,int2rgblist(color),pos,int(width))

    def clear(self,flag=0):
        if flag==0:
            self.canvas.fill(black)
        
class Food:
    def __init__(self,blobsize=19,badNum=9,goodNum=90,SCREEN_SIZE=(240,320)):
        self.blobsize=blobsize
        self.SCREEN_SIZE=SCREEN_SIZE
        self.badFood=[]
        for i in range(badNum):
            self.badFood.append((random.randint(0,self.SCREEN_SIZE[0]),random.randint(0,self.SCREEN_SIZE[1])))
        self.goodFood=[]
        for i in range(goodNum):
            self.goodFood.append((random.randint(0,self.SCREEN_SIZE[0]),random.randint(0,self.SCREEN_SIZE[1])))

class Snake:
    def __init__(self,<fo></fo>od,blobsize=2,length=9,SCREEN_SIZE=(240,320),limit=None,turnSpeed=1,ID=0,color=None):
        self.Lively=True
        self.ID=ID
        if color:
            self.color=color
        elif ID==0:
            self.color=0x00ff00
        else:
            self.color=int(random.randint(0xffffff/(ID+2),0xffffff/(ID+1)))
        self.SCREEN_SIZE=SCREEN_SIZE
        self.turnSpeed=turnSpeed
        self.moveFlag=True
        self.blobsize=blobsize
        self.turnLeft=False
        self.turnRight=False
        if limit:
            self.limit=limit
        else:
            self.limit=self.blobsize*5
        self.snakeBody=[((random.randint(0,self.SCREEN_SIZE[0]),random.randint(0,self.SCREEN_SIZE[1])))]*length
        self.badFood=Food.badFood
        self.goodFood=Food.goodFood
        self.stateDic={"up":90,"down":270,"left":180,"right":0}
        self.state=self.stateDic["up"]
        self.laststate=self.state
    def move(self):
        self.moveFlag=True

    def stop(self):
        self.moveFlag=False

    def turnto(self,state):
        self.laststate=self.state
        self.state=self.stateDic[state]
        #print self.state
    def leftDirection(self):
        self.laststate=self.state
        self.state=(self.state+self.turnSpeed)%360
        #print self.state
    def rightDirection(self):
        self.laststate=self.state
        if self.state==0:
            self.state=360
        self.state=(self.state-self.turnSpeed)%360
        #print self.state
    def quit(self):
        self.Lively=False
        print "ID",self.ID

    def moveOneStep(self,grow=False):
        if self.turnLeft:
            self.leftDirection()
        if self.turnRight:
            self.rightDirection()
        nextPortion=((self.snakeBody[0][0]+int(round((math.cos(2*math.pi*self.state/360)*2))))%self.SCREEN_SIZE[0],(self.snakeBody[0][1]-int(round((math.sin(2*math.pi*self.state/360)*2))))%self.SCREEN_SIZE[1])
        for pos in self.snakeBody:
            if space(nextPortion,pos)<2:
                print "ouch!I bite myself!"
                self.quit()
        for pos in self.badFood:
            if space(nextPortion,pos)<self.limit:
                print "ouch!I eat die!"
                self.quit()
        for pos in self.goodFood:
            if space(nextPortion,pos)<self.limit:
                #print "bravo!"
                grow=True
                self.goodFood.remove(pos)
                if self.goodFood==[]:
                    print "done!"
                    self.quit()
        if not grow:
            self.snakeBody.pop()
        self.snakeBody.insert(0,nextPortion)


class SnakeGame:
    def __init__(self,blobsize=12,length=55,badNum=9,goodNum=28,limit=None,SCREEN_SIZE=(240,320),turnSpeed=8,snakeNum=2,snakeKeyBindDic=[{"move":55,"stop":56,"turnLeft":42,"turnRight":127},{"move":49,"stop":50,"turnLeft":49,"turnRight":51}]):
        self.badColor=0x00ffff
        self.goodColor=0x00ff00
        self.snakeKeyBindDic=snakeKeyBindDic
        self.SCREEN_SIZE=SCREEN_SIZE
        self.snakeNum=snakeNum
        self.food=Food(blobsize=blobsize,badNum=badNum,goodNum=goodNum,SCREEN_SIZE=self.SCREEN_SIZE)
        self.snake=[]
        for i in range(snakeNum):
            self.snake.append(Snake(self.food,blobsize=blobsize,length=length,SCREEN_SIZE=self.SCREEN_SIZE,limit=limit,turnSpeed=turnSpeed,ID=i,color=None))
        # appuifw.app.screen='full'
        self.img=None
        self.myfont=u'Sans MT 936_S60'
        self.running=1
        # self.canvas=appuifw.Canvas(
            # event_callback=self._handle_event,
            # redraw_callback=self._handle_redraw)
        # appuifw.app.body=self.canvas
#        self.tk = Tk()  
#        self.canvas=Canvas(self.tk, width=SCREEN_SIZE[1], height=SCREEN_SIZE[0])  
        # Import a library of functions called 'pygame'
        import pygame
        pygame.init()
        self.canvas=pygame.display.set_mode(self.SCREEN_SIZE)
        # self.img=Image.new(self.canvas.size)
        self.img=Image(canvas=self.canvas,width=SCREEN_SIZE[1], height=SCREEN_SIZE[0])

        # appuifw.app.body.bind(53,lambda:self.move())
        # appuifw.app.body.bind(54,lambda:self.stop())
        # appuifw.app.body.bind(55,lambda:self.quit())
    def move(self):
        for i in range(self.snakeNum):
            self.snake[i].moveFlag=True
    def stop(self):
        for i in range(self.snakeNum):
            self.snake[i].moveFlag=False
    def _handle_redraw(self,rect=None):
        # if self.img:
            # self.canvas.blit(self.img)
#        self.canvas.update()
        pygame.display.flip()
    def _handle_event(self,event=None):
        #print event
        # keyboard_state={}
        # if event['type'] == appuifw.EEventKeyDown:
            # for i in range(self.snakeNum):
                # if event['scancode']==self.snakeKeyBindDic[i]["turnLeft"]:
                    # self.snake[i].turnLeft=True
                    # self.snake[i].turnRight=False
                # elif event['scancode']==self.snakeKeyBindDic[i]["turnRight"]:
                    # self.snake[i].turnRight=True
                    # self.snake[i].turnLeft=False
        # elif event['type'] == appuifw.EEventKeyUp:
            # for i in range(self.snakeNum):
                # if event['scancode']==self.snakeKeyBindDic[i]["turnLeft"]:
                    # self.snake[i].turnLeft=False
                    # self.snake[i].turnRight=False
                # elif event['scancode']==self.snakeKeyBindDic[i]["turnRight"]:
                    # self.snake[i].turnRight=False
                    # self.snake[i].turnLeft=False
        return None
    def quit(self):
        self.running=0
        pygame.quit ()
    def _allDie(self):
        for snake in self.snake:
            if snake.Lively:
                return None
        return True
        
    def dummyKeyPress(self,keycode,type="keyDown"):
        # keyUpDownDic={"keyUp":appuifw.EEventKeyUp,"keyDown":appuifw.EEventKeyDown}
        # return {'scancode': keycode, 'modifiers': 0, 'type': keyUpDownDic[type], 'keycode': keycode}
        pass
    def run(self,cycleTime=0):
        while self.running and not self._allDie():
            color=0x00ff00
            self.img.clear(0)
            #self.state=self.stateDic[random.choice(self.stateDic.keys())]
            for pos in self.food.badFood:
                self.img.point(pos,0x0000ff,width=self.food.blobsize)
            for pos in self.food.goodFood:
                #color=random.randint(0,0xffffff)
                self.img.point(pos,color,width=self.food.blobsize)
            for snake in self.snake:
#                print snake.snakeBody
                for pos in snake.snakeBody:
                    if snake.snakeBody.index(pos)==0 and snake.Lively:
                        self.img.point(pos,snake.color,width=snake.blobsize)    
                    elif snake.Lively:
                        w=float(snake.blobsize)*(1-float((snake.snakeBody.index(pos)))/float(len(snake.snakeBody)))
                        #print w
                        self.img.point(pos,snake.color,width=w)
                if snake.moveFlag and snake.Lively:
                    snake.moveOneStep()
            for i in range(self.snakeNum):
                getattr(random.choice(self.snake),"leftDirection")()
                getattr(random.choice(self.snake),"rightDirection")()
            self._handle_redraw(())
            # self._handle_event(self.dummyKeyPress(self.snakeKeyBindDic[random.randint(0,self.snakeNum-1)][random.choice(["turnLeft","turnRight"])],"keyDown"))
            # self._handle_event(self.dummyKeyPress(self.snakeKeyBindDic[random.randint(0,self.snakeNum-1)][random.choice(["turnLeft","turnRight"])],"keyUp"))
            
            # e32.ao_sleep(cycleTime)
            # e32.ao_yield()


    
#s=SnakeGame(blobsize=6,length=6,badNum=8,goodNum=108,limit=None,SCREEN_SIZE=(320,240),turnSpeed=9,snakeNum=8,snakeKeyBindDic=[{"move":55,"stop":56,"turnLeft":42,"turnRight":127},{"move":49,"stop":50,"turnLeft":49,"turnRight":51}]*4)


#s=SnakeGame(blobsize=6,length=6,badNum=8,goodNum=108,limit=None,SCREEN_SIZE=(320,640),turnSpeed=9,snakeNum=8,snakeKeyBindDic=[{"move":55,"stop":56,"turnLeft":42,"turnRight":127},{"move":49,"stop":50,"turnLeft":49,"turnRight":51}]*4)

#s=SnakeGame(blobsize=6,length=6,badNum=8,goodNum=108,limit=None,SCREEN_SIZE=(176,208),turnSpeed=9,snakeNum=8,snakeKeyBindDic=[{"move":55,"stop":56,"turnLeft":42,"turnRight":127},{"move":49,"stop":50,"turnLeft":49,"turnRight":51}]*4)


#s=SnakeGame(blobsize=12,length=16,badNum=1,goodNum=108,limit=None,SCREEN_SIZE=(240,320),turnSpeed=9,snakeNum=8,snakeKeyBindDic=[{"move":55,"stop":56,"turnLeft":42,"turnRight":127},{"move":49,"stop":50,"turnLeft":49,"turnRight":51}]*4)

#settings---
blobsize=7#food's size
length=2#snake lenght when it born
badNum=2#number of bad food (eat it ,the snake will die)
goodNum=1300#number of good food (eat it ,the snake will grow)
SCREEN_SIZE=(1280,800)
turnSpeed=12#needn't to mod(the speed snake make trun)
snakeNum=23#the number of snakes

#settings---
s=SnakeGame(blobsize=blobsize,length=length,badNum=badNum,goodNum=goodNum,limit=None,SCREEN_SIZE=SCREEN_SIZE,turnSpeed=turnSpeed,snakeNum=snakeNum)
s.run(cycleTime=0)
# e32.ao_yield()