创建界面
print("创建游戏窗口")
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("贪吃蛇")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.quit():
running = False
参数初始化
class Point:
row = 0
clo = 0
def __init__(self, row, clo):
self.row = row
self.clo = clo
def copy(self):
return Point(row=self.row, clo=self.clo)
pygame.init()
GUI_width = 800
GUI_height = 400
ROW = 30
CLO = 40
game_score = 0
direct = 'left'
GUI_screen = pygame.display.set_mode((GUI_width, GUI_height))
pygame.display.set_caption('贪吃蛇游戏')
head = Point(row=int(ROW / 2), clo=int(CLO / 2))
snake = [
Point(row=head.row, clo=head.clo + 1),
Point(row=head.row, clo=head.clo + 2),
Point(row=head.row, clo=head.clo + 3)
]
运行
running = True
clock = pygame.time.Clock()
display_score_text = '得分:' + str(game_score)
try:
score_font = pygame.font.SysFont('bahnschrift', 30)
except FileNotFoundError:
print("没有这个字体,下面是已安装的字体")
print(pygame.font.get_fonts())
score_font = pygame.font.Font(None, 30)
WhiteFont = (255, 255, 255)
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
GUI_screen.blit(score_surface, (10, 5))
if event.key == 273 or event.key == 119:
if direct == 'left' or direct == 'right':
direct = 'top'
if event.key == 274 or event.key == 115:
if direct == 'left' or direct == 'right':
direct = 'bottom'
if event.key == 276 or event.key == 97:
if direct == 'top' or direct == 'bottom':
direct = 'left'
if event.key == 275 or event.key == 100:
if direct == 'top' or direct == 'bottom':
direct = 'right'
eat = (head.row == snake_food_location.row and head.clo == snake_food_location.clo)
if eat:
snake_food_location = Point(row=random.randint(0, ROW - 1), clo=random.randint(0, CLO - 1))
game_score = game_score + 1
snake.insert(0, head.copy())
if not eat:
snake.pop()
if direct == 'left':
head.clo -= 1
if direct == 'right':
head.clo += 1
if direct == 'top':
head.row -= 1
if direct == 'bottom':
head.row += 1
dead = False
if head.clo < 0 or head.row < 0 or head.clo >= CLO or head.row >= ROW:
dead = True
for body in snake:
if head.clo == body.clo and head.row == body.row:
dead = True
break
game_over = False
if dead:
print('Game Over')
game_over = True
pygame.draw.rect(GUI_screen, (245, 135, 155), (0, 0, GUI_width, GUI_height))
score_surface = score_font.render("Score : %s" % str(game_score), True, WhiteFont)
GUI_screen.blit(score_surface, (0, 0), score_surface.get_rect())
rect(head, head_color)
rect(snake_food_location, snake_food_color)
for body in snake:
rect(body, snake_color)
if game_over:
running = False
pygame.display.flip()