前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【程序源代码】python贪吃蛇小游戏

【程序源代码】python贪吃蛇小游戏

作者头像
程序源代码
发布2020-07-20 16:16:34
3.3K0
发布2020-07-20 16:16:34
举报
文章被收录于专栏:程序源代码程序源代码

关键字:python 游戏 贪吃蛇

正文 | 内容

在网络还不发达,没有平板电脑和手机的童年;电视机里的动画片和小游戏曾经陪伴我们度过了欢乐的时光.扫雷、贪吃蛇、俄罗斯方块、58坦克大战、超级玛丽、魂斗罗...每一个都是回忆满满的游戏

02

【一条蛇】

代码语言:javascript
复制
# 无论何时 都在前端增加蛇块
def addnode(self):
left,top = (0,0)
if self.body:
left,top = (self.body[0].left,self.body[0].top)
node = pygame.Rect(left,top,25,25)
if self.dirction == pygame.K_LEFT:
node.left -= 25
elif self.dirction == pygame.K_RIGHT:
node.left += 25
elif self.dirction == pygame.K_UP:
node.top -= 25
elif self.dirction == pygame.K_DOWN:
node.top += 25
self.body.insert(0,node)
# 删除最后一个块
def delnode(self):
self.body.pop()
# 死亡判断
def isdead(self):
# 撞墙
if self.body[0].x  not in range(SCREEN_X):
return True
if self.body[0].y  not in range(SCREEN_Y):
return True
# 撞自己
if self.body[0] in self.body[1:]:
return True
return False
# 移动!
def move(self):
self.addnode()
self.delnode()
# 改变方向 但是左右、上下不能被逆向改变
def changedirection(self,curkey):
LR = [pygame.K_LEFT,pygame.K_RIGHT]
UD = [pygame.K_UP,pygame.K_DOWN]
if curkey in LR+UD:
if (curkey in LR) and (self.dirction in LR):
return
if (curkey in UD) and (self.dirction in UD):
return
self.dirction = curkey
# 食物类
# 方法:放置/移除
# 点以25为单位
class Food:
def __init__(self):
self.rect = pygame.Rect(-25,0,25,25)
def remove(self):
self.rect.x=-25
def set(self):
if self.rect.x == -25:
allpos = []
# 不靠墙太近 25 ~ SCREEN_X-25 之间
for pos in range(25,SCREEN_X-25,25):
allpos.append(pos)
self.rect.left = random.choice(allpos)
self.rect.top  = random.choice(allpos)
print(self.rect)
def show_text(screen, pos, text, color, font_bold = False, font_size = 60, font_italic = False):   
#获取系统字体,并设置文字大小
cur_font = pygame.font.SysFont("宋体", font_size)  
#设置是否加粗属性
cur_font.set_bold(font_bold)  
#设置是否斜体属性
cur_font.set_italic(font_italic)  
#设置文字内容
text_fmt = cur_font.render(text, 1, color)  
#绘制文字
screen.blit(text_fmt, pos)
def main():
pygame.init()
screen_size = (SCREEN_X,SCREEN_Y)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()
scores = 0
isdead = False
# 蛇/食物
snake = Snake()
food = Food()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
snake.changedirection(event.key)
# 死后按space重新
if event.key == pygame.K_SPACE and isdead:
return main()
screen.fill((255,255,255))
# 画蛇身 / 每一步+1分
if not isdead:
scores+=1
snake.move()
for rect in snake.body:
pygame.draw.rect(screen,(20,220,39),rect,0)
# 显示死亡文字
isdead = snake.isdead()
if isdead:
show_text(screen,(100,200),'YOU DEAD!',(227,29,18),False,100)
show_text(screen,(150,260),'press space to try again...',(0,0,22),False,30)
# 食物处理 / 吃到+50分
# 当食物rect与蛇头重合,吃掉 -> Snake增加一个Node
if food.rect == snake.body[0]:
scores+=50
food.remove()
snake.addnode()
# 食物投递
food.set()
pygame.draw.rect(screen,(136,0,21),food.rect,0)
# 显示分数文字
show_text(screen,(50,500),'Scores: '+str(scores),(223,223,223))
pygame.display.update()
clock.tick(10)
if __name__ == '__main__':
main()

02

【两条蛇】

代码语言:javascript
复制
import pygame, sys, time, random
from pygame.locals import *

redColour = pygame.Color(255, 0, 0)
greenColour = pygame.Color(0, 255, 0)
blueColour = pygame.Color(0, 0, 255)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
yellowColour =pygame.Color(255, 255, 0)
purpleColour =pygame.Color(255, 0, 255)
brownColour =pygame.Color(150, 75, 75)
DeepPinkColour=pygame.Color(255 ,20 ,147)

#初始化并播放背景音乐
#pygame.mixer.init()  #初始化混音器
#pygame.mixer.music.load('Ken Arai - NEXT TO YOU.mp3')  #加载背景音乐
#pygame.mixer.music.set_volume(0.2)  #设置音量
#pygame.mixer.music.play()   #播放背景音乐


# 定义游戏结束函数。当双方长度相等且头头相撞时,为平局。游戏结束,并显示双方分数。
def gameOver (playSurface,score1,score2):
gameOverFont = pygame.font.SysFont('arial', 32)
gameOverSurf = gameOverFont.render('tie   '+'pink:'+str(score1-3)+'   '+'blue:'+str(score2-3), True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
main()


# 定义游戏结束函数。当1号玩家撞墙或被2号玩家吃了时,游戏结束,显示1号玩家失败,以及双方分数。
def gameOver1(playSurface,score1,score2):
gameOverFont = pygame.font.SysFont('arial', 32)
gameOverSurf = gameOverFont.render('green snake Game Over    '+'pink:'+str(score1-3)+'  '+'blue:'+str(score2-3), True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
main()

# 定义游戏结束函数。当2号玩家撞墙或被1号玩家吃了时,游戏结束,显示2号玩家失败,以及双方分数。
def gameOver2(playSurface,score1,score2):
gameOverFont = pygame.font.SysFont('arial', 32)
gameOverSurf = gameOverFont.render(' blue snake Game Over    '+'pink'+str(score1-3)+'   '+'blue:'+str(score2-3), True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
main()


def main():
pygame.init()  #pygame初始化
#显示欢迎界面,有开始游戏和退出游戏两个选项
title_font = pygame.font.SysFont('arial', 32)
welcome_words = title_font.render('Welcome to My Snake', True, (0, 0, 0), (255, 255, 255))
tips_font = pygame.font.SysFont('arial', 24)
start_game_words = tips_font.render('Click to Start Game', True, (0, 0, 0), (255, 255, 255))
close_game_words = tips_font.render('Press ESC to Close', True, (0, 0, 0), (255, 255, 255))

playSurface = pygame.display.set_mode((640, 480), FULLSCREEN, 32)  #全屏显示
fpsClock = pygame.time.Clock()
pygame.display.set_caption('贪吃蛇')  #欢迎界面,此时未开始游戏
game_started = False

#初始化两条蛇的起始位置和长度
snakePosition1 = [100, 100]
snakeSegments1 = [[100, 100], [80, 100], [60, 100]]
snakePosition2 = [200, 200]
snakeSegments2 = [[200, 200], [180, 200], [160, 200]]
#初始化树莓的起始位置
raspberryPosition = [300, 300]
raspberrySpawned = 1
#初始化两条蛇的起始方向
direction1 = 'right'
direction2 = 'right'
changeDirection1 = direction1
changeDirection2 = direction2

while True:   #游戏循环主体
for event in pygame.event.get():  #获取事件
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:   #键盘输入
#方向键控制玩家1
if event.key == K_RIGHT :
changeDirection1 = 'right'
if event.key == K_LEFT:
changeDirection1 = 'left'
if event.key == K_UP :
changeDirection1 = 'up'
if event.key == K_DOWN :
changeDirection1 = 'down'
#‘W’‘A’‘S’‘D’控制玩家2
if event.key == ord('d'):
changeDirection2 = 'right'
if event.key == ord('a'):
changeDirection2= 'left'
if event.key == ord('w'):
changeDirection2 = 'up'
if event.key == ord('s'):
changeDirection2 = 'down'
if event.key == K_ESCAPE:  #按动ESC退出游戏
pygame.event.post(pygame.event.Event(QUIT))
elif (not game_started) and event.type == pygame.MOUSEBUTTONDOWN: #在游戏欢迎界面时,根据鼠标位置判断是否开始游戏
x, y = pygame.mouse.get_pos()
if 213 <= x <= 422 and 304 <= y <= 342:
game_started = True
playSurface.fill((255, 255, 255))  #游戏画面背景为白色

if game_started: #开始游戏
# 判断是否输入了反方向,如果输入相反方向,则方向不改变
if changeDirection1 == 'right' and direction1 != 'left':
direction1 = changeDirection1
if changeDirection1 == 'left' and direction1 != 'right':
direction1 = changeDirection1
if changeDirection1 == 'up' and direction1 != 'down':
direction1 = changeDirection1
if changeDirection1 == 'down' and direction1 != 'up':
direction1 = changeDirection1
if changeDirection2 == 'right' and direction2 != 'left':
direction2 = changeDirection2
if changeDirection2 == 'left' and direction2 != 'right':
direction2 = changeDirection2
if changeDirection2 == 'up' and direction2 != 'down':
direction2 = changeDirection2
if changeDirection2 == 'down' and direction2 != 'down':
direction2 = changeDirection2
# 根据方向移动蛇头的坐标
if direction1 == 'right':
snakePosition1[0] += 20
if direction1 == 'left':
snakePosition1[0] -= 20
if direction1 == 'up':
snakePosition1[1] -= 20
if direction1 == 'down':
snakePosition1[1] += 20

if direction2 == 'right':
snakePosition2[0] += 20
if direction2 == 'left':
snakePosition2[0] -= 20
if direction2 == 'up':
snakePosition2[1] -= 20
if direction2 == 'down':
snakePosition2[1] += 20
# 增加蛇的长度
snakeSegments1.insert(0, list(snakePosition1))
snakeSegments2.insert(0, list(snakePosition2))
# 判断是否吃掉了树莓
if snakePosition1[0] == raspberryPosition[0] and snakePosition1[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments1.pop()
if snakePosition2[0] == raspberryPosition[0] and snakePosition2[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments2.pop()
# 如果吃掉树莓,则重新生成树莓
if raspberrySpawned == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
raspberryPosition = [int(x * 20), int(y * 20)]  #先随机在任意位置生成一个树莓
while raspberryPosition in snakePosition1 or raspberryPosition in snakePosition2:  #判断树莓是否声称在蛇的身体上,如果是,则重新生成树莓
x = random.randrange(1, 32)
y = random.randrange(1, 24)
raspberryPosition = [int(x * 20), int(y * 20)]
raspberrySpawned = 1



# 刷新pygame显示层,显示两条蛇以及树莓
playSurface.fill(whiteColour)
for position in snakeSegments1:
pygame.draw.rect(playSurface, DeepPinkColour, Rect(position[0], position[1], 20, 20))
for position in snakeSegments2:
pygame.draw.rect(playSurface, blueColour, Rect(position[0], position[1], 20, 20))
colour = random.choice([yellowColour, purpleColour, brownColour, blackColour])
pygame.draw.rect(playSurface, colour, Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()


# 蛇的位置超出边框就算死亡,或者和另一条蛇相撞。
score1 = len(snakeSegments1)   #分数
score2 = len(snakeSegments2)
if snakePosition1[0] > 620 or snakePosition1[0] < 0:
gameOver1(playSurface, score1, score2)
if snakePosition1[1] > 460 or snakePosition1[1] < 0:
gameOver1(playSurface, score1, score2)
for snakeBody1 in snakeSegments1[1:]:  # 玩家二撞上了玩家一,玩家二失败
if snakePosition2[0] == snakeBody1[0] and snakePosition2[1] == snakeBody1[1]:
gameOver2(playSurface, score1, score2)
if snakePosition2[0] > 620 or snakePosition2[0] < 0:
gameOver2(playSurface, score1, score2)
if snakePosition2[1] > 460 or snakePosition2[1] < 0:
gameOver2(playSurface, score1, score2)
for snakeBody2 in snakeSegments2[1:]:  # 玩家一撞上了玩家二,玩家一失败
if snakePosition1[0] == snakeBody2[0] and snakePosition1[1] == snakeBody2[1]:
gameOver1(playSurface, score1, score2)
if snakePosition1[0] == snakePosition2[0] and snakePosition1[1] == snakePosition2[1]:   # 头碰头,谁长谁赢,否则平局。
if len(snakeSegments1) > len(snakeSegments2):
gameOver2(playSurface, score1, score2)
elif len(snakeSegments1) < len(snakeSegments2):
gameOver1(playSurface, score1, score2)
else:
gameOver(playSurface, score1, score2)

else:  # 游戏没有开始,显示欢迎界面
playSurface.blit(welcome_words, (188, 100))
playSurface.blit(start_game_words, (236, 310))
playSurface.blit(close_game_words, (233, 350))
pygame.display.update()
fpsClock.tick(5)


if __name__ == "__main__":
main()

03

最近疫情期,自己憋在家里除了日常的活动外,没有其它事情要做,感觉时间都浪费掉了。同时由于疫情经济和情感上压力也有些大。为了排解压力让自己充实起来,我决定自己用一个月的时候自学一个新语言,选来选去决定学习python。在学习的过程中接有时感觉特别累,每天总体上也坚持自学至少三个小时。学习中发现了一个比较好的软件xmind,通过xmind这个思维导图软件制作了一些自学笔记,把每节的重点整理成图形的方式,很容易直观理解和掌握。最近整理出来一些图例分享给大家一起学习,希望大家能喜欢。自学确实不容易,贵在坚持!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序源代码 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档