Python pygame贪吃蛇小游戏

大二时学python的时候,做的贪吃蛇小游戏。

#导入模块
import pygame
import random
import sys
from pygame.locals import *

class Point():
	row = 0
	col = 0
	def __init__(self,row,col):
		self.row = row
		self.col = col
	def copy(self):
		return Point(row=self.row,col=self.col)

# 颜色定义
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
gray = (230, 230, 230)
green = (0, 128, 128)
yellow = (255,225,0)

# 初始化窗口:
pygame.init()
W = 800
H = 600
ROW = 30  # 行
COL = 40  # 列
size = (W, H)
window = pygame.display.set_mode(size)
pygame.display.set_caption("LYH的贪吃蛇小游戏")  # 标题

# 显示开始信息
def show_start(screen):
	font0 = pygame.font.Font("STCAIYUN.TTF",80)
	font1 = pygame.font.Font("SIMYOU.TTF", 40)
	text0= font0.render('贪吃蛇小游戏',True, yellow)
	text1= font1.render('按S键开始游戏~~Esc退出',True, blue)
	screen.fill(white)		#白色背景
	screen.blit(text0, (250, 200))
	screen.blit(text1, (200, 400))
	pygame.display.update()

	while True:  #键盘监听事件
		for event in pygame.event.get():  # event handling loop
			if event.type == QUIT:
				terminate()     #终止程序
			elif event.type == KEYDOWN:
				if event.key == K_ESCAPE:  #终止程序
					terminate() #终止程序
				elif event.key == K_s:
					return running_game()	#开始游戏


def running_game():
	direct = 'left'  # left,right,up,down
	bg_color = white  # 白色
	snake_color = gray  # 灰色
	head_color = green  # 绿色

	head = Point(row=int(ROW / 2), col=int(COL / 2))  # 头初始于屏幕中间
	snakes = [Point(row=head.row, col=head.col + 1),
			  Point(row=head.row, col=head.col + 2)]

	# 生成食物
	def right_food():
		while 1:  # 无限循环
			pos = Point(row=random.randint(2, ROW - 3), col=random.randint(2, COL - 3))
			is_coll = False
			# 食物生成时,是否跟蛇头碰上了
			if head.row == pos.row and head.col == pos.col:
				is_coll = True
			# 蛇身子
			for snake in snakes:
				if snake.row == pos.row and snake.col == pos.col:
					is_coll = True
					break
			if not is_coll:
				break
		return pos

	# 游戏结束
	def show_gameover(screen):
		font = pygame.font.Font("SIMYOU.TTF", 35)
		font1 = pygame.font.Font("STCAIYUN.TTF", 100)
		font2 = pygame.font.Font("STCAIYUN.TTF", 80)
		text = font.render('按ESC退出游戏, 按R键重新开始游戏~~~', True, blue)
		text1 = font1.render('GAME OVER', True, red)	#布尔类型是否抗锯齿
		text2 = font2.render('最终得分%s'%(len(snakes)-2)+'分',True,yellow)
		screen.fill(white)  # 重新填充屏幕背景色
		screen.blit(text, (100, 500))
		screen.blit(text1, (160, 300))
		screen.blit(text2, (250, 100))
		pygame.display.update()
		while True:  # 键盘监听事件
			for event in pygame.event.get():  # event handling loop
				if event.type == QUIT:
					terminate()  # 终止程序
				elif event.type == KEYDOWN:
					if event.key == K_ESCAPE:  # 终止程序
						terminate()  # 终止程序
					elif event.key == K_r:
						return running_game()

	# 食物坐标
	food = right_food()  # 第一个食物
	food1 = right_food()  	#第二个食物
	food2 = right_food()  	#第三个食物
	food_color = red
	food1_color = yellow  	# 黄色
	food2_color = blue		#蓝色

	# 游戏循环
	clock = pygame.time.Clock()  # 游戏时间控制
	while True:
		# 处理事件
		for event in pygame.event.get():
			if event.type == QUIT:
				exit()
			elif event.type == KEYDOWN:  # 按键
				if event.key == K_UP or event.key == K_w:
					if direct == 'left' or direct == 'right':
						direct = 'up'
				elif event.key == K_DOWN or event.key == K_s:
					if direct == 'left' or direct == 'right':
						direct = 'down'
				elif event.key == K_LEFT or event.key == K_a:
					if direct == 'up' or direct == 'down':
						direct = 'left'
				elif event.key == K_RIGHT or event.key == K_d:
					if direct == 'up' or direct == 'down':
						direct = 'right'

		# 吃东西
		eat = (head.row == food.row and head.col == food.col)
		eat1 = (head.row == food1.row and head.col == food1.col)
		eat2 = (head.row == food2.row and head.col == food2.col)
		# 处理身子
		# 1.把原来的头插入到snakcs的头上
		snakes.insert(0, head.copy())
		# 2.把snakes的最后一个删掉
		if not eat or eat1 or eat2:
			snakes.pop()
		# 重新产生食物
		if eat:
			food = right_food()
		if eat1:
			snakes.insert(0, head.copy())
			food1 = right_food()
		if eat2:
			snakes.insert(0, head.copy())
			food2 = right_food()

		# 移动
		if direct == 'left':
			head.col -= 1
		elif direct == 'right':
			head.col += 1
		elif direct == 'up':
			head.row -= 1
		elif direct == 'down':
			head.row += 1

		# 检测
		dead = False
		# 1.撞墙
		if head.col < 0 or head.row < 0 or head.col >= COL or head.row >= ROW:
			dead = True
		# 2.撞自己
		for snake in snakes:
			if head.col == snake.col and head.row == snake.row:
				dead = True
		if dead:
			show_gameover(window)
			pygame.display.update()

		# 背景
		pygame.draw.rect(window, bg_color, (0, 0, W, H))  # 画方块

		# 画方块
		def rect(point, color):
			cell_width = W / COL
			cell_height = H / ROW
			left = point.col * (W / COL)
			top = point.row * (H / ROW)
			pygame.draw.rect(
				window, color, (left, top, cell_width, cell_height)
			)

		# 画成绩
		def draw_score(screen, score):
			font = pygame.font.Font("STCAIYUN.TTF", 45)
			scoreSurf = font.render('得分: %s' %score, True, green)
			scoreRect = scoreSurf.get_rect()
			scoreRect.topleft = (W - 180, 30)
			screen.blit(scoreSurf, scoreRect)

		draw_score(window, len(snakes) - 2)
		for snake in snakes:  # 画三个蛇身
			rect(snake, snake_color)
		rect(head, head_color)
		rect(food, food_color)
		rect(food1, food1_color)
		rect(food2, food2_color)

		# 让出控制权
		pygame.display.flip()

		# 设置帧频
		snake_speed = 15
		clock.tick(snake_speed)  # sleep(1000/60)

# 程序终止
def terminate():
	pygame.quit()
	sys.exit()

show_start(window)

发布了41 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43472877/article/details/103008319