首页 > 其他分享 >pygame手搓贪吃蛇

pygame手搓贪吃蛇

时间:2024-08-27 16:05:59浏览次数:3  
标签:mypoints self random height width 贪吃蛇 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()

 

效果:

 

标签:mypoints,self,random,height,width,贪吃蛇,pygame
From: https://www.cnblogs.com/xuxiaobo/p/18382902

相关文章

  • pygame手搓五子棋
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomfromwin32apiimportGetSystemMetricspygame.init()pygame.display.set_caption("五子棋")percent=0.6screen_width=GetSystemMetrics(0)screen_height=GetSystemMetrics(1)wi......
  • pygame各类形状
    代码:#coding=utf-8importos,sys,re,time,mathimportpygameimportrandomfromwin32apiimportGetSystemMetricsfrommathimportpipygame.init()pygame.display.set_caption("各种形状测试")percent=0.6screen_width=GetSystemMetrics(0)screen_hei......
  • pygame物体碰撞
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomimportmathfromwin32apiimportGetSystemMetricsfromtkinterimportmessageboxpygame.init()pygame.display.set_caption("我的游戏")percent=0.6screen_width=GetSystemMetri......
  • 线性表小项目(通讯录、贪吃蛇)
    目录通讯录新增联系人 查找联系人 删除联系人修改联系人 贪吃蛇小游戏Win32APIGetStdHandleGetConsoleCursorInfoCONSOLE_CURSOR_INFO SetConsoleCursorInfoSetConsoleCursorPosition GetAsyncKeyState 宽字符介绍贪吃蛇游戏设计游戏开始阶段场景打印:......
  • 使用 Pygame 创建简单的移动方块游戏
    Pygame是一个用于开发图形和多媒体应用的优秀Python库。下面,我们将逐步解释如何创建一个简单的游戏,其中一个蓝色方块可以在屏幕上移动。 安装Pygame首先,确保你已经安装了Pygame。可以通过以下命令安装:pipinstallpygame 游戏结构1.初始化Pygame开始时,需......
  • pygame开发小游戏
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomfromwin32apiimportGetSystemMetricsfromtkinterimportmessageboxfromsqlparse.filtersimportright_margin#pyinstaller-F-wdaziyan.pypygame.init()pygame.display.set_caption(&......
  • JS贪吃蛇
    1.整个简洁版的贪吃蛇完整代码,后面会解析<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>贪吃蛇</title></head><bodystyle="height:90vh;display:flex;justify-content:center;align-items:center;......
  • 【python】pygame开发小游戏原来如此简单,掌握这几步就可以快速上手
    ✨✨欢迎大家来到景天科技苑✨✨......
  • JS贪吃蛇
    1.整个简洁版的贪吃蛇完整代码,后面会解析<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>贪吃蛇</title></head><bodystyle="height:90vh;display:flex;justify-content:center;align-items:cente......
  • 贪吃蛇小游戏(c语言实现,巨细详解,附完整代码)
    文章目录c语言简单实现贪吃蛇(巨细详解,附完整代码)==前言==一、游戏效果及功能实现:1、规则:2、基本功能实现:3、技术要点4、实现思路5、游戏效果呈现二、Win32API介绍1、简单介绍2、控制台程序(Console)cmd命令窗口打开方式:控制cmd控制台长宽度命令title命令(命名)3、vs中的控......