无pygame写一个python贪吃蛇

无pygame写一个python贪吃蛇

这个贪吃蛇是以pynput来监视键盘,os来刷新屏幕,以此实现的贪吃蛇

蛇的结构

贪吃蛇建立在block组成的二维列表里,block包含两个属性``,自己的身份和指向
身份包括:草地,蛇身,蛇头,蛇尾巴,苹果五种。
指向则是从尾巴一格一格地指向蛇头。
这样蛇的移动其实就是丢掉尾巴,头长长一格。

代码展示

import os
import time
import random
from pynput.keyboard import Listener

def bp (s): #用于输出一个屏幕的内容
    os.system('cls') #本程序只适用于Windows
    if s == 'normal':
        print('#'*(L+2))
        for i in range(L//2):
            print('#',end='')
            for j in range(L):
                if Map[i][j].status == 0:
                    print(' ',end='')
                elif Map[i][j].status == 1:
                    print('*',end='')
                elif Map[i][j].status == 2:
                    print('O',end='')
                elif Map[i][j].status == 3:
                    print('@',end='')
                elif Map[i][j].status == 4:
                    print('$',end='')
            print('#')
        print('#'*(L+2))

    elif s == 'over':
        print(
            '''
##############################################################
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#     ____    _    __  __ _____    _____     _______ ____    #
#    / ___|  / \  |  \/  | ____|  / _ \ \   / / ____|  _ \   #
#   | |  _  / _ \ | |\/| |  _|   | | | \ \ / /|  _| | |_) |  #
#   | |_| |/ ___ \| |  | | |___  | |_| |\ V / | |___|  _ <   #
#    \____/_/   \_\_|  |_|_____|  \___/  \_/  |_____|_| \_\  #
#                                                            #
#                                                            #
'''
+'#              你吃到了'+str(speed-30)+'\t个苹果,下次加油             #'+
'''
#                                                            #
#                                                            #
#                                                            #
##############################################################                                          
            ''')
    elif s == 'welcome':
        print(
            '''
##############################################################
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#                                                            #
#     __        _______ _     ____ ___  __  __ _____         #
#     \ \      / / ____| |   / ___/ _ \|  \/  | ____|        #
#      \ \ /\ / /|  _| | |  | |  | | | | |\/| |  _|          #
#       \ V  V / | |___| |__| |__| |_| | |  | | |___         #
#        \_/\_/  |_____|_____\____\___/|_|  |_|_____|        #
#                                                            #
#                                                            #
#                                                            #
#     游戏中只能通过按wasd移动,按下其他非字母键游戏直接等死 #
#     游戏难度 a 地狱 s简单 d普通 w困难                      #
#                                                            #
#     按下他们开始游戏                                       #
#                                                            #
#                                                            #
##############################################################                                              
            ''')


def on_press(key):
    global di
    try:
        di = key.char
    except:
        return False

class block ():
    def __init__ (self, status, direction):
        self.status = status
        self.chD(direction)
    def chD (self,b):
        if b == 'w':
            self.direction = (-1,0)
        elif b == 'a':
            self.direction = (0,-1)
        elif b == 's':
            self.direction = (1,0)
        elif b == 'd':
            self.direction = (0,1)
        else:
            self.direction = -1
            return 0
        return 1
    
def gn (a,b):
    temp = Map[a][b].direction
    return a+temp[0],b+temp[1]

di,L,S,Map = 30,30,30,30
if __name__ == '__main__':
    with Listener(on_press=on_press) as listener:
        bp('welcome')
        while not di in {'w','a','s','d'}:
            time.sleep(0.5)

        #初始化数据
        if di == 'w':
            L,S = 20,2
        elif di == 'a':
            L,S = 30,15
        elif di == 's':
            L,S = 30,15
        elif di == 'd':
            L,S = 20,4
        speed = 30
        head = (7,15)
        tail = (7,12)
        Map = [[block(0,0) for __ in range(L)] for _ in range(L//2)]
        print(len(Map),len(Map[0]))
        Map[7][12] = block(1,'d')
        Map[7][13] = block(2,'d')
        Map[7][14] = block(2,'d')
        Map[7][15] = block(3,'d')
        apple = False
        os.system('cls')

        while 1:
            #apple!
            while not apple:
                a = random.randint(0,L//2-1)
                b = random.randint(0,L-1)
                if Map[a][b].status == 0:
                    Map[a][b].status = 4
                    apple = 1
                    break

            time.sleep(S/speed)
            fh = gn(*head)
            if fh[0]>=L//2 or fh[0]<0 or fh[1]>=L or fh[1]<0 or Map[fh[0]][fh[1]].status in {2,1}:
                bp('over')
                listener.join()
                break
            elif Map[fh[0]][fh[1]].status == 4:
                apple = False
                speed+=1

                Map[head[0]][head[1]].status = 2
                head = fh
                Map[head[0]][head[1]].status = 3
                Map[head[0]][head[1]].chD(di)

            elif Map[fh[0]][fh[1]].status == 0:
                Map[head[0]][head[1]].status = 2
                head = fh
                Map[head[0]][head[1]].status = 3
                Map[head[0]][head[1]].chD(di)
                
                Map[tail[0]][tail[1]].status = 0
                temp = gn(*tail)
                Map[tail[0]][tail[1]].direction = 0
                Map[temp[0]][temp[1]].status = 1
                tail = temp

            bp('normal')

效果在这里插入图片描述

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
一个Python贪吃蛇游戏可以通过使用Pygame库来实现。下面是一个简单的示例代码: ```python import pygame import random # 初始化游戏 pygame.init() # 定义游戏窗口的大小 window_width = 800 window_height = 600 # 定义贪吃蛇的大小和速度 snake_size = 20 snake_speed = 10 # 定义颜色 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # 创建游戏窗口 window = pygame.display.set_mode((window_width, window_height)) pygame.display.set_caption('贪吃蛇') # 定义贪吃蛇的初始位置和移动方向 snake_x = window_width / 2 snake_y = window_height / 2 snake_dx = 0 snake_dy = 0 # 定义食物的初始位置 food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size # 定义贪吃蛇的身体 snake_body = [] snake_length = 1 # 游戏主循环 running = True while running: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 处理键盘事件,控制贪吃蛇的移动方向 if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake_dx = -snake_size snake_dy = 0 elif event.key == pygame.K_RIGHT: snake_dx = snake_size snake_dy = 0 elif event.key == pygame.K_UP: snake_dy = -snake_size snake_dx = 0 elif event.key == pygame.K_DOWN: snake_dy = snake_size snake_dx = 0 # 更新贪吃蛇的位置 snake_x += snake_dx snake_y += snake_dy # 判断贪吃蛇是否吃到食物 if snake_x == food_x and snake_y == food_y: food_x = round(random.randrange(0, window_width - snake_size) / snake_size) * snake_size food_y = round(random.randrange(0, window_height - snake_size) / snake_size) * snake_size snake_length += 1 # 绘制游戏窗口 window.fill(black) pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size]) snake_head = [] snake_head.append(snake_x) snake_head.append(snake_y) snake_body.append(snake_head) if len(snake_body) > snake_length: del snake_body for segment in snake_body[:-1]: if segment == snake_head: running = False for segment in snake_body: pygame.draw.rect(window, white, [segment, segment, snake_size, snake_size]) pygame.display.update() # 控制游戏速度 pygame.time.Clock().tick(snake_speed) # 退出游戏 pygame.quit() ```
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值