pygame写贪吃蛇,供借鉴

这篇博客分享了一位python初学者使用pygame库编写的简单贪吃蛇游戏。作者在学习pygame的过程中尝试实践,并提供了自己的QQ号以供交流讨论代码问题。
摘要由CSDN通过智能技术生成

简单的用python写的贪吃蛇

(我是菜鸟)学python的我学了下pygame,试着写了写贪吃蛇,下面是代码,有问题也可以问我
QQ2036693779,废话不多说上代码

#贪吃蛇简单版
import pygame,sys,time,random
from pygame.locals import *
from PIL import Image
class Snake():
    def __init__(self,x,y):
        self.x=x
        self.y=y
def drawpic(screen,self):
     pic=pygame.image.load('snake.png')
     screen.blit(pic,(self.x,self.y))
def drawmap(screen):
    for i in range(25):
        pygame.draw.line(screen,(0,0,0),(0,i*20),(500,i*20))
    for j in range(25):
        pygame.draw.line(screen,(0,0,0),(j*20,0),(j*20,500))
def drawfood(screen):
    x=random.randint(0,25)*20
    y=random.randint(0,25)*20
    pygame.draw.rect(screen,(255,0,0),(x,y,20,20))
    return (x+10,y+10)
def drawfood_1(screen,x,y):
    pygame.draw.rect(screen,(255,0,0),(x,y,20,20))
def move(screen,manyske):#蛇头前进方向
    direction='right'
    head=manyske[0]
    newx=head.x
    newy=head.y
    screen.fill((255,255,255))
    fx,fy=drawfood(screen)
    while True:
        if direction=='left':
            newx=head.x-20
        elif direction=='right':
            newx=head.x+20
        elif direction=='up':
            newy=head.y-20
        elif direction=='down':
            newy=head.y+20
        screen.fill((255,255,255))
        drawmap(screen)
        if (fx,fy)==(newx+10,newy+10):
            fx,fy=drawfood(screen)
            snake=Snake(manyske[-1].x,manyske[-1].y)
            manyske.append(snake)
        else:
            pygame.draw.rect(screen,(255,0,0),(fx-10,fy-10,20,20))
        j=len(manyske)-1
        for i in range(len(manyske)):
            manyske[j].x=manyske[j-1].x
            manyske[j].y=manyske[j-1].y
            j-=1;
            head.x=newx
            head.y=newy
        for i in range(len(manyske)):
             drawpic(screen,manyske[i])
        event=pygame.event.poll()
        if event.type==KEYDOWN:
            if event.key==pygame.K_LEFT and direction!='right':
                direction='left'
            elif event.key==pygame.K_RIGHT and direction!='left':
                direction='right'
            elif event.key==pygame.K_DOWN and direction!='up':
                direction='down'
            elif event.key==pygame.K_UP and direction!='down':
                direction='up'
        elif event.type==QUIT:
            pygame.quit()
            sys.exit()
        pygame.display.update()
        time.sleep(0.25)
#全局变量
pygame.init()
screen=pygame.display.set_mode((500,500))
pygame.display.set_caption('贪吃蛇')
screen.fill((255,255,255))
drawmap(screen)
#食物
manyske=[]
head=Snake(0,0)
manyske.append(head)
move(screen,manyske)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值