增加了蛇

This commit is contained in:
xnz233 2024-07-15 00:53:49 +08:00
parent 92e6ea8d77
commit db85f0a0ce
Signed by: xnz233
SSH Key Fingerprint: SHA256:6ufAAU+qjfNoOJpvu0bY6QK7NH4mYIQj/lVR/jWsI3g
6 changed files with 150 additions and 135 deletions

2
.gitignore vendored
View File

@ -1 +1,3 @@
__pycache__/ __pycache__/
idea.km
idea.png

View File

@ -14,10 +14,10 @@ def check_events(settings):
sys.exit() sys.exit()
# 按1键选择手动模式 # 按1键选择手动模式
elif event.key == pygame.K_1: elif event.key == pygame.K_1:
settings.game_mode = -1 settings.game_mode = 1
# 按2键选择自动模式 # 按2键选择自动模式
elif event.key == pygame.K_2: elif event.key == pygame.K_2:
settings.game_mode = -1 settings.game_mode = 2
def show_start(settings, screen): def show_start(settings, screen):
@ -44,7 +44,7 @@ def show_start(settings, screen):
def show_end(settings, screen): def show_end(settings, screen):
"""结算界面""" """失败结算界面"""
title_font = pygame.font.Font(settings.font_name, 80) title_font = pygame.font.Font(settings.font_name, 80)
game_image = title_font.render('Game', True, (233, 150, 122)) game_image = title_font.render('Game', True, (233, 150, 122))
over_image = title_font.render('Over', True, (233, 150, 122)) over_image = title_font.render('Over', True, (233, 150, 122))
@ -58,3 +58,84 @@ def show_end(settings, screen):
pygame.display.flip() pygame.display.flip()
pygame.time.wait(1500) pygame.time.wait(1500)
settings.game_mode = 0 settings.game_mode = 0
def draw_grid(settings, screen):
#绘制横向线
for x in range(0, settings.width, settings.cell_size):
pygame.draw.line(screen,(40,40,40),(x,0),(x,settings.height))
#绘制竖向线
for y in range(0, settings.height, settings.cell_size):
pygame.draw.line(screen,(40,40,40),(0, y),(settings.width,y))
def update_screen(settings, screen):
screen.fill(settings.bg_color)
draw_grid(settings, screen)
#绘制蛇
def draw_snake(ai_settings, screen, snake):
#头部用白色
x = snake.coords[0]['x'] * ai_settings.cell_size
y = snake.coords[0]['y'] * ai_settings.cell_size
snake_head_rect = pygame.Rect(x, y, ai_settings.cell_size, ai_settings.cell_size)
pygame.draw.rect(screen,(255,255,255), snake_head_rect)
#蛇身内部用浅绿,外框用深绿
for coord in snake.coords[1: -1]:
x = coord['x'] * ai_settings.cell_size
y = coord['y'] * ai_settings.cell_size
snake_part_rect = pygame.Rect(x, y, ai_settings.cell_size, ai_settings.cell_size)
pygame.draw.rect(screen,(0,155,0), snake_part_rect)
snake_part_inner_rect = pygame.Rect(x + 4, y + 4, ai_settings.cell_size - 8, ai_settings.cell_size - 8)
pygame.draw.rect(screen,(0,255,0), snake_part_inner_rect)
#蛇尾用浅绿
coord = snake.coords[-1]
x = coord['x'] * ai_settings.cell_size
y = coord['y'] * ai_settings.cell_size
snake_tail_rect = pygame.Rect(x, y, ai_settings.cell_size, ai_settings.cell_size)
pygame.draw.rect(screen,(0,255,0), snake_tail_rect)
#绘制游戏界面
def update_screen(settings, screen, snake):
screen.fill(settings.bg_color)
draw_grid(settings, screen)
#移动蛇
del snake.coords[-1]#加蛇头
snake.update()#去蛇尾
if not is_game_over(settings, snake):
settings.game_mode = -1
else:
draw_snake(settings, screen, snake)
pygame.display.flip()
#暂停一下
settings.my_clock.tick(settings.clock_frq)
def is_game_over(settings,snake):
#碰到左右墙壁
if (snake.coords[snake.head_index]['x'] == -1 or snake.coords[snake.head_index]['x'] == settings.cell_w):
return False
#碰到上下墙壁
if(snake.coords[snake.head_index]['y'] == -1 or snake.coords[snake.head_index]['y'] == settings.cell_h):
return False
#碰到自己
if(snake.coords[snake.head_index] in snake.coords[1:]):
return False
return True
#检测游戏过程中的按键
def check_play_events(snake):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == pygame.K_LEFT and not snake.direction == 'right':
snake.direction = 'left'
elif event.key == pygame.K_RIGHT and not snake.direction == 'left':
snake.direction = 'right'
elif event.key == pygame.K_UP and not snake.direction == 'down':
snake.direction = 'up'
elif event.key == pygame.K_DOWN and not snake.direction == 'up':
snake.direction = 'down'

115
idea.km
View File

@ -1,115 +0,0 @@
{
"root": {
"data": {
"id": "d2oi0jx7h6o0",
"created": 1720882729134,
"text": "Astar贪吃蛇"
},
"children": [
{
"data": {
"id": "d2oi1r6uoww0",
"created": 1720882823319,
"text": "游戏本体(Pygame)",
"layout_mind_offset": {
"x": -29,
"y": 1
}
},
"children": [
{
"data": {
"id": "d2oi2k2ygw00",
"created": 1720882886210,
"text": "蛇",
"expandState": "expand",
"layout_right_offset": {
"x": 8,
"y": -54
}
},
"children": [
{
"data": {
"id": "d2oi21ezqoo0",
"created": 1720882845579,
"text": "如何表示蛇"
},
"children": []
},
{
"data": {
"id": "d2oi2vcyync0",
"created": 1720882910760,
"text": "蛇如何移动"
},
"children": []
},
{
"data": {
"id": "d2oi30i8aj40",
"created": 1720882921962,
"text": "如何判定游戏结束?"
},
"children": []
}
]
},
{
"data": {
"id": "d2oi3jwwljc0",
"created": 1720882964209,
"text": "食物"
},
"children": [
{
"data": {
"id": "d2oi3vw1ujc0",
"created": 1720882990278,
"text": "如何生成食物"
},
"children": []
}
]
},
{
"data": {
"id": "d2oi7hsyoao0",
"created": 1720883273073,
"text": "界面"
},
"children": []
}
]
},
{
"data": {
"id": "d2oijamyvjc0",
"created": 1720884197843,
"text": "游戏玩法"
},
"children": [
{
"data": {
"id": "d2oi4mwhxi80",
"created": 1720883049078,
"text": "自动(A*寻路算法)"
},
"children": []
},
{
"data": {
"id": "d2oijfl72io0",
"created": 1720884208620,
"text": "手动"
},
"children": []
}
]
}
]
},
"template": "default",
"theme": "snow",
"version": "1.4.43"
}

BIN
idea.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

19
main.py
View File

@ -1,12 +1,19 @@
import pygame
from settings import Settings from settings import Settings
import game_functions as gf import game_functions as gf
import pygame from snake import Snake
settings = Settings() settings = Settings()
#设置屏幕
screen = pygame.display.set_mode((settings.width, settings.height))
#添加游戏标题
pygame.display.set_caption('贪吃蛇')
#创建蛇
snake = Snake(settings)
screen = pygame.display.set_mode((settings.width, settings.height)) # 设置屏幕 def run_game1():
pygame.display.set_caption('贪吃蛇') # 添加游戏标题 gf.check_play_events(snake)
gf.update_screen(settings, screen, snake)
def run_game(): def run_game():
while True: while True:
@ -14,7 +21,9 @@ def run_game():
gf.show_start(settings,screen) gf.show_start(settings,screen)
elif settings.game_mode == -1: elif settings.game_mode == -1:
gf.show_end(settings,screen) gf.show_end(settings,screen)
snake.reset(settings)
elif settings.game_mode == 1:
run_game1()
if __name__ == "__main__": if __name__ == "__main__":
pygame.init() pygame.init()

38
snake.py Normal file
View File

@ -0,0 +1,38 @@
import random
class Snake():
def __init__(self,settings):
self.reset(settings)
#蛇的初始化
def reset(self,settings):
#蛇头的坐标
self.start_x = random.randint(5, settings.cell_w - 6)
self.start_y = random.randint(5, settings.cell_h - 6)
self.head_index = 0
#蛇的初始运动方向
self.direction = 'right'
#蛇的初始坐标字典,初始蛇为蛇头位置及其左边的两个格子
self.coords = [{'x' : self.start_x, 'y': self.start_y},
{'x' : self.start_x - 1, 'y': self.start_y},
{'x' : self.start_x - 2, 'y': self.start_y}]
#更新蛇,每次蛇移动一步,因此相当于每次移动在蛇的坐标字典中再插入一个新蛇头
#按常识,每次移动后,不仅仅是蛇头向前移动一个,更重要的是蛇尾也要向前移,但是在该函数中先不处理蛇尾
#因为如果蛇吃了食物,此时蛇尾其实并没有移动
def update(self):
newHead = {}
#根据移动方向确定蛇头
if self.direction == 'up':
newHead = {'x' : self.coords[self.head_index]['x'],
'y' : self.coords[self.head_index]['y'] - 1}
elif self.direction == 'down':
newHead = {'x' : self.coords[self.head_index]['x'],
'y' : self.coords[self.head_index]['y'] + 1}
elif self.direction == 'left':
newHead = {'x' : self.coords[self.head_index]['x'] - 1,
'y' : self.coords[self.head_index]['y']}
elif self.direction == 'right':
newHead = {'x' : self.coords[self.head_index]['x'] + 1,
'y' : self.coords[self.head_index]['y']}
self.coords.insert(0,newHead)