Python 在pygame中出现游戏结束屏幕后重新启动蛇游戏
在我在github上发现的游戏中,屏幕上有一个游戏显示了你的分数,现在我想让游戏重新启动,如果你按空格键,那么你就不需要关闭程序并再次打开它来再次玩。问题不在于当你按下空格键时如何让游戏重新启动,而在于如何让它真正重新启动。代码如下:Python 在pygame中出现游戏结束屏幕后重新启动蛇游戏,python,python-3.x,pygame,Python,Python 3.x,Pygame,在我在github上发现的游戏中,屏幕上有一个游戏显示了你的分数,现在我想让游戏重新启动,如果你按空格键,那么你就不需要关闭程序并再次打开它来再次玩。问题不在于当你按下空格键时如何让游戏重新启动,而在于如何让它真正重新启动。代码如下: import pygame import random import sys import time # Difficulty settings # Easy -> 10 # Medium -> 25 # Hard -&
import pygame
import random
import sys
import time
# Difficulty settings
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
difficulty = 25
# Window size
frame_size_x = 720
frame_size_y = 480
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Game Over
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x / 2, frame_size_y / 4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times', 20)
pygame.display.update()
time.sleep(3)
pygame.quit()
sys.exit()
# Score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (frame_size_x - 100, 15)
else:
score_rect.midtop = (frame_size_x / 2, frame_size_y / 1.25)
game_window.blit(score_surface, score_rect)
# pygame.display.flip()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawning food on the screen
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# Game Over conditions
# Getting out of bounds
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x - 10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > frame_size_y - 10:
game_over()
# Touching the snake body
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score(1, white, 'consolas', 20)
# Refresh game screen
pygame.display.update()
# Refresh rate
fps_controller.tick(difficulty)
导入pygame
随机输入
导入系统
导入时间
#难度设置
#轻松->10
#中等->25
#硬->40
#更硬->60
#不可能->120
难度=25
#窗口大小
框架尺寸x=720
框架尺寸y=480
#检查遇到的错误
check_errors=pygame.init()
#pygame.init()示例输出->(6,0)
#元组中的第二个数字表示错误数
如果检查错误[1]>0:
打印(f'[!]在初始化游戏时有{check_errors[1]}错误,正在退出…)
系统出口(-1)
其他:
打印(“[+]游戏已成功初始化”)
#初始化游戏窗口
pygame.display.set_标题('Snake Eater')
game\u window=pygame.display.set\u模式((帧大小x,帧大小y))
#颜色(R、G、B)
黑色=pygame.Color(0,0,0)
白色=pygame.Color(255、255、255)
红色=pygame.Color(255,0,0)
绿色=pygame.Color(0,255,0)
蓝色=pygame.Color(0,0255)
#FPS(每秒帧数)控制器
fps_controller=pygame.time.Clock()
#博弈变量
snake_pos=[100,50]
蛇身=[[100,50],[100-10,50],[100-(2*10),50]]
食物位置=[random.randrange(1,(帧大小x//10))*10,random.randrange(1,(帧大小y//10))*10]
食物产卵=真
方向=‘右’
将_改为=方向
分数=0
#游戏结束
def game_over():
my_font=pygame.font.SysFont('times new roman',90)
game\u over\u surface=my\u font.render('YOU dead',True,red)
game_over_rect=game_over_surface.get_rect()
game_over_rect.midtop=(帧大小x/2,帧大小y/4)
游戏窗口填充(黑色)
game_window.blit(game_over_surface,game_over rect)
显示分数(0,红色,'times',20)
pygame.display.update()
时间。睡眠(3)
pygame.quit()
sys.exit()
#得分
def显示分数(选项、颜色、字体、大小):
score\u font=pygame.font.SysFont(字体、大小)
score\u surface=score\u font.render('score:'+str(score),True,color)
score\u rect=score\u surface.get\u rect()
如果选项==1:
score_rect.midtop=(帧大小\u x-100,15)
其他:
score_rect.midtop=(帧大小x/2,帧大小y/1.25)
游戏窗口。blit(分数曲面,分数直线)
#pygame.display.flip()
#主要逻辑
尽管如此:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
pygame.quit()
sys.exit()
#只要按下一个键
elif event.type==pygame.KEYDOWN:
#W->Up;S->Down;A->左;D->右
如果event.key==pygame.K_UP或event.key==ord('w'):
将_更改为='UP'
如果event.key==pygame.K_DOWN或event.key==ord('s'):
将_更改为='DOWN'
如果event.key==pygame.K_左或event.key==ord('a'):
将_更改为='左'
如果event.key==pygame.K_RIGHT或event.key==ord('d'):
将_更改为='右'
#Esc->创建事件退出游戏
如果event.key==pygame.K_退出:
pygame.event.post(pygame.event.event(pygame.QUIT))
#确保蛇不能瞬间朝相反方向移动
如果将_更改为==‘向上’和方向!='向下':
方向=‘向上’
如果将_更改为==‘向下’和方向!='向上':
方向=‘向下’
如果将_更改为=='左'和方向!='对":
方向=‘左’
如果将_更改为=='右'和方向!='左':
方向=‘右’
#移动蛇
如果方向==“向上”:
蛇_位置[1]-=10
如果方向==“向下”:
snake_pos[1]+=10
如果方向==“左”:
snake_位置[0]-=10
如果方向=='右':
snake_pos[0]+=10
#蛇体生长机理
蛇体。插入(0,列表(蛇体位置))
如果蛇[0]==食物[0]和蛇[1]==食物[1]:
分数+=1
食物产卵=错误
其他:
蛇_body.pop()
#屏幕上的产卵食物
如果不是食物产卵:
食物位置=[random.randrange(1,(帧大小x//10))*10,random.randrange(1,(帧大小y//10))*10]
食物产卵=真
#GFX
游戏窗口填充(黑色)
对于蛇形体中的位置:
#蛇身
#.draw.rect(播放曲面、颜色、xy坐标)
#xy坐标->.Rect(x,y,尺寸x,尺寸y)
pygame.draw.rect(游戏窗口,绿色,pygame.rect(位置[0],位置[1],10,10))
#蛇食
pygame.draw.rect(游戏窗口,白色,pygame.rect(食物位置[0],食物位置[1],10,10))
#条件博弈
#出界
如果snake_pos[0]<0或snake_pos[0]>帧大小\u x-10:
游戏结束
如果snake_pos[1]<0或snake_pos[1]>帧尺寸y-10:
游戏结束
#触摸蛇身
对于蛇形体[1:]中的块:
如果snake_pos[0]==块[0]和snake_pos[1]==块[1]:
游戏结束
显示分数(1,白色,'consolas',20)
#刷新游戏屏幕
pygame.display.update()
#刷新率
fps_控制器。勾选(难度)
实现一个初始化所有全局游戏状态的函数:
def init_game():
全球蛇体位置
全球食物位置,食物产卵
全局方向,更改为,得分
#博弈变量
snake_pos=[100,50]
蛇身=[[100,50],[100-10,50],[100-(2*10),50]]
食物位置=[random.randrange(1,(帧大小x//10))*10,random.randrange(1,(帧大小y//10))*10]
食物产卵=真
方向=‘右’
将_改为=方向
分数=0
按下空格键时调用该函数:
为True时:
活动一