一直想用pygame做一个小游戏的,可是因为拖延症的缘故一直没有动,结果那天看到了一个12岁的国际友人小盆友用pygame做的一款塔防游戏,突然感觉已经落后超级远了,所以心血来潮做小游戏了。高中陪伴我的游戏就是手机里的贪吃蛇,还记得我和老尹童鞋比拼分数的场景,所以就从贪吃蛇开始吧。

好吧,因为大学老师教导我们,用面向对象的语言写程序的时候,首先考虑建立类,于是乎,我就考虑建立了snake类和food类两个,但是我不准备在我的程序里添加图片,所以这两个类最终沦为贪吃蛇和食物它们各自的位置变换的实现了。

class snake:
def __init__(self):
"""
init the snake
"""
self.poslist = [[10,10]]
def position(self):
"""
return the all of the snake's point
"""
return self.poslist
def gowhere(self,where):
"""
change the snake's point to control the snake's moving direction
"""
count = len(self.poslist)
pos = count-1
while pos > 0:
self.poslist[pos] = copy.deepcopy(self.poslist[pos-1])
pos -= 1
if where is 'U':
self.poslist[pos][1] -= 10
if self.poslist[pos][1] < 0:
self.poslist[pos][1] = 500
if where is 'D':
self.poslist[pos][1] += 10
if self.poslist[pos][1] > 500:
self.poslist[pos][1] = 0
if where is 'L':
self.poslist[pos][0] -= 10
if self.poslist[pos][0] < 0:
self.poslist[pos][0] = 500
if where is 'R':
self.poslist[pos][0] += 10
if self.poslist[pos][0] > 500:
self.poslist[pos][0] = 0
def eatfood(self,foodpoint):
"""
eat the food and add point to snake
"""
self.poslist.append(foodpoint)

在gowhere函数中,之所以与500比较大小,是因为我定义的窗口大小为宽500,高500

class food:
def __init__(self):
"""
init the food's point
"""
self.x = random.randint(10,490)
self.y = random.randint(10,490)
def display(self):
"""
init the food's point and return the point
"""
self.x = random.randint(10,490)
self.y = random.randint(10,490)
return self.position()
def position(self):
"""
return the food's point
"""
return [self.x,self.y]

food 的位置是使用随即函数随即出来的

def main():
moveup = False
movedown = False
moveleft = False
moveright = True
pygame.init()
clock = pygame.time.Clock()
width = 500
height = 500
screen = pygame.display.set_mode([width,height]) #1
restart = True
while restart:
sk = snake()
fd = food()
screentitle = pygame.display.set_caption("eat snake") #2
sk.gowhere('R')
running = True
while running:
# fill the background is white
screen.fill([255,255,255]) #3

程序开始主要是做了一些初始化的工作,moveup/movedown/moveleft/moveright这四个变量使用来标注贪吃蛇的运动方向的,#1标注的那句是初始化显示窗口的(因此所有pygame编写的程序中,这句话有且只能调用一次),#2标注的那句是初始化标题栏显示标题的,#3那句是用来填充整个背景为白色

            for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
# judge the down key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
moveup = True
movedown = False
moveleft = False
moveright = False
if event.key == pygame.K_DOWN:
moveup = False
movedown = True
moveleft = False
moveright = False
if event.key == pygame.K_LEFT:
moveup = False
movedown = False
moveleft = True
moveright = False
if event.key == pygame.K_RIGHT:
moveup = False
movedown = False
moveleft = False
moveright = True

当按下方向键时,设置相应的方向

            # where the snake goes
time_pass = clock.tick(40)
if moveup:
sk.gowhere('U')
if movedown:
sk.gowhere('D')
if moveleft:
sk.gowhere('L')
if moveright:
sk.gowhere('R')

设置视频帧数并设置贪吃蛇的移动方向

            # draw the food
poslist = sk.position()
foodpoint = fd.position()
fdrect = pygame.draw.circle(screen,[255,0,0],foodpoint,15,0)
# draw the snafe
snaferect = []
for pos in poslist:
snaferect.append(pygame.draw.circle(screen,[255,0,0],pos,5,0))

在界面上画上食物和贪吃蛇,其中fdrect和snaferect的存储是后面碰撞检测需要用到的

                # crash test if the snake eat food
if fdrect.collidepoint(pos):
foodpoint = fd.display()
sk.eatfood(foodpoint)
fdrect = pygame.draw.circle(screen,[255,0,0],foodpoint,15,0)
break
# crash test if the snake crash itsself
headrect = snaferect[0]
count = len(snaferect)
while count > 1:
if headrect.colliderect(snaferect[count-1]):
running = False
count -= 1
pygame.display.update()

碰撞检测贪吃蛇是否吃到了食物,以及是否撞到了自己,pygame.display.update()是更新整个界面的意思,前面的画图只是画到了区域里,但是没有更新到窗口,需要此句将其更新到显示窗口

        # game over background
pygame.font.init()
screen.fill([100,0,0])
font = pygame.font.Font(None,48)
text = font.render("Game Over !!!",True,(255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery + 24
screen.blit(text,textRect)
# keydown r restart,keydown n exit
while 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
restart = True
del sk
del fd
break
if event.key == pygame.K_n:
restart = False
break
pygame.display.update()

当输了之后,界面上显示game over字样,此时按下“n”退出程序,按下“r"重新开始

自己写的这个贪吃蛇与那位国际友人写的程序比较一下,发现我因为懒所以没有添加图片和音乐,纯是画的图,所以不需要图片的各种操作,我觉得那个图片跟着鼠标转动的效果挺有意思的,以后再做别的游戏的时候再添加吧

源码:http://download.csdn.net/detail/vhghhd/6035283,嘿嘿

pygame编写贪吃蛇的更多相关文章

  1. pygame写贪吃蛇

    python小白尝试写游戏.. 学了点pygame不知道那什么练手好,先拿贪吃蛇开刀吧. 一个游戏可以粗略的分为两个部分: 数据(变量) 处理数据(函数,方法) 设计变量 首先预想下,画面的那些部分需 ...

  2. 用python+pygame写贪吃蛇小游戏

    因为python语法简单好上手,前两天在想能不能用python写个小游戏出来,就上网搜了一下发现了pygame这个写2D游戏的库.了解了两天再参考了一些资料就开始写贪吃蛇这个小游戏. 毕竟最开始的练手 ...

  3. JavaScript版—贪吃蛇小组件

    最近在学习JavaScript,利用2周的时间看完了<JavaScript高级编程>,了解了Js是一门面向原型编程的语言,没有像C#语言中的class,也没有私有.公有.保护等访问限制的级 ...

  4. 【C/C++】10分钟教你用C++写一个贪吃蛇附带AI功能(附源代码详解和下载)

    C++编写贪吃蛇小游戏快速入门 刚学完C++.一时兴起,就花几天时间手动做了个贪吃蛇,后来觉得不过瘾,于是又加入了AI功能.希望大家Enjoy It. 效果图示 AI模式演示 imageimage 整 ...

  5. 初入pygame——贪吃蛇

    一.问题利用pygame进行游戏的编写,做一些简单的游戏比如贪吃蛇,连连看等,后期做完会把代码托管. 二.解决 1.环境配置 python提供一个pygame的库来进行游戏的编写.首先是安装pygam ...

  6. Python实例:贪吃蛇(简单贪吃蛇编写)🐍

    d=====( ̄▽ ̄*)b 叮~ Python -- 简易贪吃蛇实现 目录: 1.基本原理 2.需要学习的库 3.代码实现 1.基本原理 基本贪吃蛇所需要的东西其实很少,只需要有一块让蛇动的屏幕, 在 ...

  7. javascript 编写的贪吃蛇

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. pygame试水,写一个贪吃蛇

    最近学完python基础知识,就想着做一个游戏玩玩,于是就在https://www.pygame.org/docs/学着做了个贪吃蛇游戏. 首先要导入模块. import pygame import ...

  9. Python实战练习_贪吃蛇 (pygame的初次使用)

    正如标题所写的那样,我将一步步的完成本次实战练习——贪吃蛇.废话不多说,感兴趣的伙伴可以一同挑战一下. 首先说明本次实战中我的配备: 开发环境:python 3.7: 开发工具:pycharm2019 ...

随机推荐

  1. 【QT相关】Qt Widgets Module

    Qt Widgets Module:提供了一些列UI元素. 使用: //头文件包含 #include <QtWidgets> //链接模式,在.pro文件中添加行: QT += widge ...

  2. new Intent(String action,Uri uri)构造器说明

    这是myDiary这个工程下MainActivity中的protected void onListItemClick(ListView l, View v, int position, long id ...

  3. python sqlalchemy-migrate 使用方法

    1:下载相关模块     pip install sqlalchemy     pip install sqlalchemy-migrate   2:创建model (model.py),这里用来绑定 ...

  4. CodeForces 22B Bargaining Table 简单DP

    题目很好理解,问你的是在所给的图中周长最长的矩形是多长嗯用坐标(x1, y1, x2, y2)表示一个矩形,暴力图中所有矩形易得递推式:(x1, y1, x2, y2)为矩形的充要条件为: (x1, ...

  5. Firemonkey ListBoxItem自绘

    ListBoxItem1的事件ListBoxItem1Paint procedure TForm1.ListBoxItem1Paint(Sender: TObject; Canvas: TCanvas ...

  6. What’s New in Python 2.7 — Python 3.4.0b2 documentation

    What's New in Python 2.7 - Python 3.4.0b2 documentation What's New in Python 2.7¶

  7. Aizu 1335 Eequal sum sets

    Let us consider sets of positive integers less than or equal to n. Note that all elements of a set a ...

  8. MVC 向页面传值方式总结

    总结发现ASP.NET MVC中Controller向View传值的方式共有6种,分别是: ViewBag ViewData TempData 向普通View页面传一个Model对象 向强类型页面传传 ...

  9. 个人mysql配置命令

    Microsoft Windows [版本 6.1.7601]版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Windows\system32>cd ...

  10. BZOJ 3211: 花神游历各国( 线段树 )

    线段树...区间开方...明显是要处理到叶节点的 之前在CF做过道区间取模...差不多, 只有开方, 那么每个数开方次数也是有限的(0,1时就会停止), 最大的数10^9开方10+次也就不会动了.那么 ...