代码:
#coding=utf-8import os,sys,re,time import pygame import random from win32api import GetSystemMetrics import copypygame.init() pygame.display.set_caption("贪吃蛇")percent = 0.6 screen_width = GetSystemMetrics(0) screen_height = GetSystemMetrics(1) window_width = int(screen_width*percent) window_height = int(screen_height*percent)maxLine = 25 maxField = 25 empty_width = window_height / (maxLine + 2) / 13left_width = window_height left_height = window_height left_width_nei = left_width - 2 * empty_width left_height_nei = left_height - 2 * empty_width right_width = window_width - left_width right_height = window_height line_border_width = 1perWidth = left_width_nei / maxField perHeight = left_height_nei / maxLinedt = 0 clock = pygame.time.Clock()screen = pygame.display.set_mode((window_width-right_width/1.3, window_height))#停止处理输入法事件 pygame.key.stop_text_input()font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')class Button:def __init__(self, x, y, width, height, color, text):self.x = xself.y = yself.width = widthself.height = heightself.color = colorself.text = textdef draw(self, win, outline=None, line_width = 1):pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))if outline:pygame.draw.rect(win, outline, (self.x, self.y, self.width, self.height), 1)myfont = pygame.font.Font(font_path, int(19*percent))text = myfont.render(self.text, 1, (0, 0, 0))myw = self.x + (self.width / 2 - text.get_width() / 2)myy = self.y + (self.height / 2 - text.get_height() / 2)win.blit(text, (myw, myy))def changeText(self, text):self.text = textdef beClicked(self, mouse_pos, event):if self.x + self.width > event.pos[0] > self.x and self.y + self.height > event.pos[1] > self.y:return Truereturn Falsedef checkPointIsin(mypoints1, testpoint):for mypoint in mypoints1:if testpoint[0] == mypoint[0] and testpoint[1] == mypoint[1]:return Truereturn Falsedef getRandpoints(randpoint1):res = []for i in range(3):x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000 + random.randint(1, 10000)))if randpoint1[0] == x and randpoint1[1] == y:continueres.append([x, y, color, mytime])return resdef restElsepoints(elsepoints, mypoints1):res = []for i,point in enumerate(elsepoints):if int(round(time.time() * 1000)) - point[3] > 12000:x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000))if checkPointIsin(mypoints1, [x, y, color, mytime]) == False:res.append([x, y, color, mytime])else:res.append(point)if len(res) < 1:x = random.randint(0, maxLine-1)y = random.randint(0, maxField-1)color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))mytime = int(round(time.time() * 1000))if checkPointIsin(mypoints1, [x, y, color, mytime]) == False:res.append([x, y, color, mytime])return resdef has_index(lst, element):try:lst.index(element)return Trueexcept ValueError:return Falsebuttonwidth = 80*percent randpoint1 = [random.randint(0, maxLine-1), random.randint(0, maxField-1), 'red'] mypoints = [randpoint1] elsepoints = getRandpoints(randpoint1) sleepTime = 0 direct = '' pauseFlag = False restartBt = Button(window_width-right_width+2, 1, buttonwidth, 25, 'Gold3', '重新开始') pauseBt = Button(window_width-right_width+buttonwidth+4, 1, buttonwidth, 25, 'Gold3', '暂停')running = True while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseif event.type == pygame.MOUSEBUTTONDOWN:mouse_pos = pygame.mouse.get_pos()if restartBt.beClicked(mouse_pos, event):randpoint1 = [random.randint(0, maxLine-1), random.randint(0, maxField-1), 'red']mypoints = [randpoint1]elsepoints = getRandpoints(randpoint1)sleepTime = 0direct = ''pauseFlag = Falseif pauseBt.beClicked(mouse_pos, event):if pauseFlag == True:pauseFlag = FalsepauseBt.changeText('暂停')else:pauseFlag = TruepauseBt.changeText('开始')keys_pressed = pygame.key.get_pressed()#ESC键if keys_pressed[pygame.K_ESCAPE]:running = Falseif pauseFlag == False:if keys_pressed[pygame.K_a]:direct = 'a'firstpoint = mypoints[0]if firstpoint[0] <= 0:firstpoint[0] = 0mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[0] -= 1mypoints[0] = firstpointif keys_pressed[pygame.K_d]:direct = 'd'firstpoint = mypoints[0]if firstpoint[0] >= maxField - 1:firstpoint[0] = maxField - 1mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[0] += 1mypoints[0] = firstpointif keys_pressed[pygame.K_w]:direct = 'w'firstpoint = mypoints[0]if firstpoint[1] <= 0:firstpoint[1] = 0mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[1] -= 1mypoints[0] = firstpointif keys_pressed[pygame.K_s]:direct = 's'firstpoint = mypoints[0]if firstpoint[1] >= maxLine - 1:firstpoint[1] = maxLine - 1mypoints[0] = firstpointelse:mypointsold = copy.deepcopy(mypoints)for i in range(1, len(mypoints)):mypoints[i][0] = mypointsold[i-1][0]mypoints[i][1] = mypointsold[i-1][1]firstpoint[1] += 1mypoints[0] = firstpointtime.sleep(0.1)screen.fill("purple")#左侧块rect1 = pygame.Rect(empty_width, empty_width, perWidth*maxField, perHeight*maxLine)pygame.draw.rect(screen, 'LightYellow1', rect1)#右侧块rect2 = pygame.Rect(left_width, 0, right_width, right_height)pygame.draw.rect(screen, 'Honeydew', rect2)restartBt.draw(screen, 'black')pauseBt.draw(screen, 'black')#横线for i in range(0, maxLine+1):start = (empty_width, empty_width+i*perHeight)end = (empty_width+left_width_nei, empty_width+i*perHeight)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#竖线for i in range(0, maxField+1):start = (empty_width+i*perWidth, empty_width)end = (empty_width+i*perWidth, empty_width+left_height_nei)pygame.draw.aaline(screen, 'black', start, end, line_border_width)#蛇头myrect = pygame.Rect(empty_width+mypoints[0][0]*perWidth, empty_width+mypoints[0][1]*perHeight, perWidth, perHeight)#随机块if pauseFlag == False:elsepoints = restElsepoints(elsepoints, mypoints)for i,mypoint1 in enumerate(elsepoints):myrect1 = pygame.Rect(empty_width+mypoint1[0]*perWidth, empty_width+mypoint1[1]*perHeight, perWidth, perHeight)pygame.draw.rect(screen, mypoint1[2], myrect1)if myrect.colliderect(myrect1):if direct == 'a':mypoint1[0] -= 1elif direct == 'd':mypoint1[0] += 1elif direct == 'w':mypoint1[1] -= 1elif direct == 's':mypoint1[1] += 1mypoints.insert(0, [mypoint1[0], mypoint1[1], mypoint1[2]])del elsepoints[i]#蛇块for i,mypoint1 in enumerate(mypoints):myrect1 = pygame.Rect(empty_width+mypoint1[0]*perWidth, empty_width+mypoint1[1]*perHeight, perWidth, perHeight)pygame.draw.rect(screen, mypoint1[2], myrect1)if i == 0:pygame.draw.rect(screen, 'black', myrect1, 3)#更新显示 pygame.display.flip()#pygame.display.update() dt = clock.tick(60) / 600pygame.quit()
效果: