花一晚上使用python写的贪吃蛇

本文介绍了一个简单的贪吃蛇游戏的Python实现。使用Pygame库创建游戏窗口,并通过方向键控制贪吃蛇移动。游戏包括蛇身增长机制及碰撞检测等功能。

使用方向键控制贪吃蛇,有时间再优化。

import pygame
from pygame.sprite import Group,Sprite
import sys
import random

import time


def run_game():
    pygame.init()
    screen = pygame.display.set_mode((500,500))
    pygame.display.set_caption("snake")

    #背景色
    bg = (80,80,80)
    screen.fill(bg)

    #图片
    img = pygame.image.load("QR.png")

    img_rect = img.get_rect()      #获取外接矩形
    screen_rect = screen.get_rect()

    img_rect.centerx = screen_rect.centerx  #中心坐标
    #img_rect.bottom = screen_rect.bottom     #下边缘


    #移动步长
    step_len = 10
    #前进方向
    left = 1
    top = 2
    right = 3
    bottom = 4
    direction = left

    class SnakeItem(Sprite):
        len = 0
        def __init__(self,x,y,color):
            super().__init__()
            self.x = x
            self.y = y
            self.color = color

    #蛇
    item = SnakeItem(screen_rect.centerx,screen_rect.centery,(255,255,255))
    snake = []
    snake.append(item)

    #食物
    def set_food():
        while True:
            x = 0
            y = 0
            while True:
                x = random.randrange(0,screen_rect.width)
                if x % 10 == 0:
                    break
            while True:
                y = random.randrange(0,screen_rect.height)
                if y % 10 == 0:
                    break

            for i in snake:
                if i.x == x and i.y == y:
                    continue

            return SnakeItem(x,y,(255,0,0))

    temp_rect = set_food()

    while True:
        #方向
        for event in pygame.event.get():#键盘 鼠标 事件
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    direction = right
                elif event.key == pygame.K_LEFT:
                    direction = left
                elif event.key == pygame.K_UP:
                    direction = top
                elif event.key == pygame.K_DOWN:
                    direction = bottom

        #screen.blit(img,img_rect)#在指定位置绘制
        #背景
        screen.fill(bg)

        #食物
        rect = pygame.Rect(temp_rect.x,temp_rect.y,10,10)
        pygame.draw.rect(screen,temp_rect.color,rect)
        #蛇
        s = snake[:]
        item_head = s[0]
        xx = s[0].x
        yy = s[0].y

        list_x=[-1]
        list_y=[-1]
        for i in snake:
            list_x.append(i.x)
            list_y.append(i.y)

        list_x = set(list_x)
        list_y = set(list_y)

        print(len(list_x))
        print(len(list_y))

        if direction == left:
            xx = xx - step_len if xx - step_len > screen_rect.left-10*len(list_x) else screen_rect.left-10*len(list_x)
            item_head.x = item_head.x - step_len if item_head.x - step_len > screen_rect.left-10*len(list_x) else screen_rect.left-10*len(list_x)
        elif direction == top:
            item_head.y = item_head.y - step_len if item_head.y - step_len > screen_rect.top-10*len(list_y) else screen_rect.top-10*len(list_y)
            yy = yy -step_len if yy - step_len > screen_rect.top else screen_rect.top
        elif direction == right:
            xx = xx + step_len if xx + step_len < screen_rect.right -10*len(list_x) else screen_rect.right -10*len(list_x)
            item_head.x = item_head.x + step_len if item_head.x + step_len < screen_rect.right-10*len(list_x) else screen_rect.right-10*len(list_x)
        elif direction == bottom:
            yy = yy + step_len if yy + step_len < screen_rect.bottom -10*len(list_y) else screen_rect.bottom -10*len(list_y)
            item_head.y = item_head.y + step_len if item_head.y + step_len < screen_rect.bottom-10*len(list_y) else screen_rect.bottom-10*len(list_y)
        #snake.append(item_head)   #不知为何snake中的坐标是一样的?
        nn = SnakeItem(xx,yy,(255,255,255))
        snake.insert(0,nn)

        for i in snake:
            r = pygame.Rect(i.x,i.y,10,10)
            pygame.draw.rect(screen, i.color, r)

        pygame.display.flip()      #最近绘制的屏幕可见

        if item_head.x >= temp_rect.x and item_head.x <= temp_rect.x+10 and item_head.y >= temp_rect.y and item_head.y <= temp_rect.y+10:
            temp_rect = set_food()
        else:
            snake.pop()
            time.sleep(0.3)

        # print("--------------")
        # for i in snake:
        #     print(i.x,i.y)

run_game()
一个简单的Python贪吃蛇游戏需要一些基本的游戏设计知识以及对Python图形用户界面库如`pygame`的了解。以下是一个简化的示例,演示如何创建一个基础版的贪吃蛇游戏: ```python import pygame import random # 初始化Pygame pygame.init() # 设置窗口大小 window_width = 600 window_height = 400 screen = pygame.display.set_mode((window_width, window_height)) pygame.display.set_caption("贪吃蛇") # 定义颜色 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) # 蛇的位置和方向 snake_pos = [(window_width / 2, window_height / 2)] snake_dir = [0] # 向右 # 食物位置 food_pos = [random.randrange(0, window_width), random.randrange(0, window_height)] clock = pygame.time.Clock() font = pygame.font.SysFont('Arial', 20) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and snake_dir != [1]: snake_dir = [-1, 0] elif keys[pygame.K_RIGHT] and snake_dir != [-1]: snake_dir = [1, 0] elif keys[pygame.K_UP] and snake_dir != [0]: snake_dir = [0, -1] elif keys[pygame.K_DOWN] and snake_dir != [0]: snake_dir = [0, 1] # 更新蛇的位置 new_head = [snake_pos[-1]: # 如果撞到身体,游戏结束 print("Game Over!") break else: snake_pos.append(new_head) # 移动食物 if snake_pos[0] == food_pos: food_pos = [random.randrange(0, window_width), random.randrange(0, window_height)] else: snake_pos.pop(0) screen.fill(black) text = font.render("Score: " + str(len(snake_pos) - 1), True, white) screen.blit(text, [10, 10]) for pos in snake_pos: pygame.draw.rect(screen, red, [pos[0], pos[1], 10, 10]) pygame.draw.rect(screen, white, [food_pos[0], food_pos[1], 10, 10]) pygame.display.update() clock.tick(10) ``` 这个代码创建了一个基本的贪吃蛇环境,玩家通过控制箭头键移动蛇,吃到绿色方块得分。当蛇碰到自己或屏幕边缘时,游戏结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值