pygame手搓贪吃蛇

代码:

#coding=utf-8

import os,sys,re,time
import pygame
import random
from win32api import GetSystemMetrics
import copy

pygame.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) / 13

left_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 = 1

perWidth = left_width_nei / maxField
perHeight = left_height_nei / maxLine

dt = 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 = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.text = text
 
    def 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 = text

    def 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 True
        return False
    
def checkPointIsin(mypoints1, testpoint):
    for mypoint in mypoints1:
        if testpoint[0] == mypoint[0] and testpoint[1] == mypoint[1]:
            return True
    return False
    
def 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:
            continue
        
        res.append([x, y, color, mytime])
    return res
    
def 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 res

def has_index(lst, element):
    try:
        lst.index(element)
        return True
    except ValueError:
        return False
        

buttonwidth = 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 = False
        if 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 = 0
                direct = ''
                pauseFlag = False
            if pauseBt.beClicked(mouse_pos, event):
                if pauseFlag == True:
                    pauseFlag = False
                    pauseBt.changeText('暂停')
                else:
                    pauseFlag = True
                    pauseBt.changeText('开始')
            
    keys_pressed = pygame.key.get_pressed()
    
    #ESC键
    if keys_pressed[pygame.K_ESCAPE]:
        running = False
        
    
    if pauseFlag == False:
        if keys_pressed[pygame.K_a]:
            direct = 'a'
            firstpoint = mypoints[0]
            if firstpoint[0] <= 0:
                firstpoint[0] = 0
                mypoints[0] = firstpoint
            else:
                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] -= 1
                mypoints[0] = firstpoint
                
        if keys_pressed[pygame.K_d]:
            direct = 'd'
            firstpoint = mypoints[0]
            if firstpoint[0] >= maxField - 1:
                firstpoint[0] = maxField - 1
                mypoints[0] = firstpoint
            else:
                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] += 1
                mypoints[0] = firstpoint
                
        if keys_pressed[pygame.K_w]:
            direct = 'w'
            firstpoint = mypoints[0]
            if firstpoint[1] <= 0:
                firstpoint[1] = 0
                mypoints[0] = firstpoint
            else:
                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] -= 1
                mypoints[0] = firstpoint
                        
        if keys_pressed[pygame.K_s]:
            direct = 's'
            firstpoint = mypoints[0]
            if firstpoint[1] >= maxLine - 1:
                firstpoint[1] = maxLine - 1
                mypoints[0] = firstpoint
            else:
                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] += 1
                mypoints[0] = firstpoint
        
            
        
    time.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] -= 1
            elif direct == 'd':
                mypoint1[0] += 1
            elif direct == 'w':
                mypoint1[1] -= 1
            elif direct == 's':
                mypoint1[1] += 1
            
            mypoints.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) / 600
    
pygame.quit()

 

效果:

 

posted @ 2024-08-27 16:05  河北大学-徐小波  阅读(6)  评论(0编辑  收藏  举报