一直想用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. 【Eclipse】修改java代码不强制重启

    找到tomcat的server.xml文件,修改以下代码,重新发布重启.然后修改java代码就可以不用重启了. 将reloadable=“true”改成reloadable="false&q ...

  2. 写一方法来实现两个变量的交换。在主调函数中定义两个整型变量,并初始化,调用交换方法,实现这两个变量的交换。(使用ref参数)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. Codeforces Round #253 (Div. 2), problem: (B)【字符串匹配】

    简易字符串匹配,题意不难 #include <stdio.h> #include <string.h> #include <math.h> #include < ...

  4. Ural 1197 - Lonesome Knight

    The statement of this problem is very simple: you are to determine how many squares of the chessboar ...

  5. poj2676解题报告

    题意:有一个9*9的格子 分成了9个3*3的小子格,一些位置上的已有一些数字..现在要求你把没有数字的位置填上数,要求这个数没有出现在这个位置所在的行.列以及所在的子格 分析: 那么我们对于所有的未填 ...

  6. JAVA思维导图系列:多线程0基础

    感觉自己JAVA基础太差了,又一次看一遍,已思维导图的方式记录下来 多线程0基础 进程 独立性 拥有独立资源 独立的地址 无授权其它进程无法訪问 动态性 与程序的差别是:进程是动态的指令集合,而程序是 ...

  7. 再造 “手机QQ” 侧滑菜单(二)——高仿左视图

    代码示例:https://github.com/johnlui/SwiftSideslipLikeQQ 本篇文章中,我们将一起使用 Auto Layout 高仿手Q的左侧视图,力争达成从布局到动画的全 ...

  8. ICE之C/S通信原理

    /* 在ICE文档中只需要声明module名称,接口名称,方法名称 */ #ifndef SIMPLE_ICE #define SIMPLE_ICE module Demo{ //module名称 i ...

  9. CentOS的配置文件

    /etc/profile:此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.并从/etc/profile.d目录的配置文件中搜集shell的设置. /etc/bashrc:为每一个 ...

  10. nginx 解决400 bad request 的方法

    nginx的400错误比较难查找原因,因为此错误并不是每次都会出现的,另外,出现错误的时候,通常在浏览器和日志里看不到任何有关提示. 经长时间观察和大量试验查明,此乃request header过大所 ...