| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛

问题点数：0 回复次数：8

import pygame,sys
from pygame.locals import *
from sys import exit

class Snake(pygame.sprite.Sprite):

def __init__(self,screen):
pygame.sprite.Sprite.__init__(self)
#蛇序列
self.snakeLine=[(400,250),(400-40,250),(400-40*2,250)]

#画板
self.screen=screen

#碰撞检测
self.rect=Rect(400,250,40,40) #蛇头的区域

def show(self,newSnakeLine=None):
#将新的蛇序列设为原蛇序列
if newSnakeLine is not None:
self.snakeLine=newSnakeLine
self.rect=Rect(newSnakeLine[0],(40,40))

self.rect=Rect(self.snakeLine[0],(40,40))

#蛇尾
for cord in self.snakeLine[1:-1]:
self.screen.blit(Snake.snake_body,cord)

#蛇尾
self.screen.blit(Snake.snake_tail,self.snakeLine[-1])

def getDirection(self):
offX=self.snakeLine[0][0]-self.snakeLine[1][0]
offY=self.snakeLine[0][1]-self.snakeLine[1][1]
if (offX==30 or offX==-870) and offY==0:
return K_RIGHT

elif (offX==-30 or offX==870) and offY==0:
return K_LEFT

elif offX==0 and (offY==30 or offY==-570):
return K_DOWN

elif offX==0 and (offY==-30 or offY==570):
return K_UP

def move(self,KEY=None):

#创建一个冲突列表
wrong_list=[{K_RIGHT,K_RIGHT},{K_RIGHT,K_LEFT},{K_LEFT,K_LEFT},{K_UP,K_UP},{K_UP,K_DOWN},{K_DOWN,K_DOWN}]
if KEY is None or {self.getDirection(),KEY} in wrong_list:
KEY=self.getDirection()#按错方向键后，不改变原方向

if KEY==K_RIGHT:#右移就在右侧添加蛇头，蛇尾减少1块
self.snakeLine=[((self.snakeLine[0][0]+40)%900,self.snakeLine[0][1])]+self.snakeLine[0:-1]

elif KEY==K_UP:#上移就在上侧添加蛇头，蛇尾减少1块
self.snakeLine=[(self.snakeLine[0][0],(600+self.snakeLine[0][1]-40)%600)]+self.snakeLine[0:-1]

elif KEY==K_DOWN:#下移就在下侧添加蛇头，蛇尾减少1块
self.snakeLine=[(self.snakeLine[0][0],(self.snakeLine[0][1]+40)%600)]+self.snakeLine[0:-1]

elif KEY==K_LEFT:#左移就在左侧添加蛇头，蛇尾减少1块
self.snakeLine=[((self.snakeLine[0][0]-40+900)%900,self.snakeLine[0][1])]+self.snakeLine[0:-1]

self.show()

pygame.init()

screen=pygame.display.set_mode((900,600))
pygame.display.set_caption('snake')

snake=Snake(screen)

clock=pygame.time.Clock()

while True:

clock.tick(10)

KEY=None

for event in pygame.event.get():#进行事件等待
#如果用户单击关闭窗口按钮就退出
if event.type==QUIT:
pygame.quit()
exit()
if event.type==KEYDOWN:
KEY=event.key

screen.fill('black')

snake.move(KEY)

#循环显示
pygame.display.update()

```import random,sys,pygame
from pygame.locals import*
FPS=5
width=640
heigh=480
cellsize=20
cellwidth=int(width/cellsize)
cellheigh=int(heigh/cellsize)
white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
darkgreen=(0,155,0)
darkgray=(40,40,40)
BGcolor=white
Up='up'
Down='down'
Left='left'
Right='right'
def main():
global FPSlock,screen,BASICfont
pygame.init()
FPSlock=pygame.time.Clock()
screen=pygame.display.set_mode([width,heigh])
BASICfont=pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf',20)
pygame.display.set_caption('贪吃蛇')
showstartscreen()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
rungame()
showgameover()
def showstartscreen():
width1=640
heigh1=480
titlefont=pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf',100)
titlesurf1=titlefont.render('贪吃蛇',True,black,darkgreen)
titlesurf2=titlefont.render('贪吃蛇',True,green)
degrees1=0
degrees2=0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
return
screen.fill(BGcolor)
surf1=pygame.transform.rotate(titlesurf1,degrees1)
rect1=surf1.get_rect()
rect1.center=(width1/2,heigh1/2)
screen.blit(surf1,rect1)
surf2=pygame.transform.rotate(titlesurf2,degrees2)
rect2=surf2.get_rect()
rect2.center=(width1/2,heigh1/2)
screen.blit(surf2,rect2)
drawpresskeymsg()
pygame.display.update()
FPSlock.tick(FPS)
degrees1 += 3
degrees2 += 7
def drawpresskeymsg():
presskeysurf=BASICfont.render('按任意键进入游戏',True,black)
presskeyrect=presskeysurf.get_rect()
presskeyrect.topleft=(width-200,heigh-30)
screen.blit(presskeysurf,presskeyrect)
def drawgrid():
for x in range(0,width,cellsize):
pygame.draw.line(screen,darkgreen,(x,0),(x,heigh))
for y in range(0,heigh,cellsize):
pygame.draw.line(screen,darkgreen,(0,y),(width,y))
def getrandomlocation():
return {'x':random.randint(0,cellwidth),'y':random.randint(0,cellheigh-1)}
def drawscore(score):
scoresurf=BASICfont.render('分数:%s'%(score),True,black)
scorerect=scoresurf.get_rect()
scorerect.topleft=(width-120,10)
screen.blit(scoresurf,scorerect)
def rungame():
startx=random.randint(5,cellwidth-6)
starty=random.randint(5,cellheigh-6)
wormcoords=[{'x':startx,'y':starty},{'x':startx-1,'y':starty},{'x':startx-2,'y':starty}]
direction=Right
apple=getrandomlocation()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if (event.key==K_LEFT or event.key==K_a)and direction != Right:
direction=Left
elif (event.key==K_RIGHT or event.key==K_d)and direction != Left:
direction=Right
elif (event.key==K_UP or event.key==K_w)and direction != Down:
direction=Up
elif (event.key==K_DOWN or event.key==K_s)and direction != Up:
direction=Down
elif event.key == K_ESCAPE:
sys.exit()
if wormcoords[0]['x'] == -1 or wormcoords[0]['x'] == cellwidth or wormcoords[0]['y'] == -1 or wormcoords[0]['y'] == cellheigh:
return
for wormbody in wormcoords[1:]:
if wormbody['x'] == wormcoords[0]['x'] and wormbody['y'] == wormcoords[0]['y']:
return
if wormcoords[0]['x'] == apple['x'] and wormcoords[0]['y'] == apple['y']:
apple= getrandomlocation()
else:
del wormcoords[-1]
if direction == Up:
elif direction == Down:
elif direction == Left:
elif direction == Right:
screen.fill(BGcolor)
drawgrid()
drawworm(wormcoords)
drawapple(apple)
drawscore(len(wormcoords)-3)
pygame.display.update()
FPSlock.tick(FPS)
def drawworm(wormcoords):
for coord in wormcoords:
x=coord['x']*cellsize
y=coord['y']*cellsize
wormsegmentrect=pygame.Rect(x,y,cellsize,cellsize)
pygame.draw.rect(screen,darkgreen,wormsegmentrect)
worminnersegmentrect=pygame.Rect(x+4,y+4,cellsize-8,cellsize-8)
pygame.draw.rect(screen,darkgreen,worminnersegmentrect)
def drawapple(coord):
x=coord['x']*cellsize
y=coord['y']*cellsize
applerect=pygame.Rect(x,y,cellsize,cellsize)
pygame.draw.rect(screen,red,applerect)
def showgameover():
gameoverfont=pygame.font.Font('C://Windows//Fonts//msyh.ttc',150)
gamesurf=gameoverfont.render('游戏',True,black)
oversurf=gameoverfont.render('失败',True,black)
gamerect=gamesurf.get_rect()
overrect=oversurf.get_rect()
gamerect.midtop=(width/2,10)
overrect.midtop=(width/2,gamerect.height+10+25)
screen.blit(gamesurf,gamerect)
screen.blit(oversurf,overrect)
drawpresskeymsg()
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
return
if __name__=='__main__':
main()
```

[此贴子已经被作者于2023-9-9 11:21编辑过]

• 9
• 1/1页
• 1