来源: 最后更新:23-08-25 06:07:33
最近有很多的同学问,能不能用Python做出一个小游戏来,而且最好要讲清楚每一段干嘛是用来干嘛的
那行,今天将来讲解一下用Python pygame做一个贪吃蛇的小游戏
据说是贪吃蛇游戏是1976年,Gremlin公司推出的经典街机游戏,那我们今天用Python制作的这个贪吃蛇小游戏是一个像素版的,虽然简陋,但还是可以玩起来的
import pygame import random import copy
pygame.init() clock = pygame.time.Clock() # 设置游戏时钟 pygame.display.set_caption("贪吃蛇-解答、源码、相关资料可私信我") # 初始化标题 screen = pygame.display.set_mode((500, 500)) # 初始化窗口 窗体的大小为 500 500
snake_list = [[10, 10]]
move_up = False move_down = False move_left = False move_right = True
x = random.randint(10, 490) y = random.randint(10, 490) food_point = [x, y]
running = True while running: # 游戏时钟 刷新频率 clock.tick(20)
screen.fill([255, 255, 255])
for x in range(0, 501, 10): pygame.draw.line(screen, (195, 197, 199), (x, 0), (x, 500), 1) pygame.draw.line(screen, (195, 197, 199), (0, x), (500, x), 1) food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)
snake_rect = [] for pos in snake_list: # 1.7.1 绘制蛇的身子 snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 1
if move_up: snake_list[pos][1] -= 10 if snake_list[pos][1] < 0: snake_list[pos][1] = 500 if move_down: snake_list[pos][1] += 10 if snake_list[pos][1] > 500: snake_list[pos][1] = 0 if move_left: snake_list[pos][0] -= 10 if snake_list[pos][0] < 0: snake_list[pos][0] = 500 if move_right: snake_list[pos][0] += 10 if snake_list[pos][0] > 500: snake_list[pos][0] = 0
for event in pygame.event.get(): # print(event) # 判断按下的按键 if event.type == pygame.KEYDOWN: # 上键 if event.key == pygame.K_UP: move_up = True move_down = False move_left = False move_right = False # 下键 if event.key == pygame.K_DOWN: move_up = False move_down = True move_left = False move_right = False # 左键 if event.key == pygame.K_LEFT: move_up = False move_down = False move_left = True move_right = False # 右键 if event.key == pygame.K_RIGHT: move_up = False move_down = False move_left = False move_right = True
pos = len(snake_list) - 1 while pos > 0: snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) pos -= 1
if food_rect.collidepoint(pos): # 贪吃蛇吃掉食物 snake_list.append(food_point) # 重置食物位置 food_point = [random.randint(10, 490), random.randint(10, 490)] food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0) break
head_rect = snake_rect[0] count = len(snake_rect) while count > 1: if head_rect.colliderect(snake_rect[count - 1]): running = False count -= 1 pygame.display.update()
标签: [db:关键词]
2023火车学生票优惠政策常见问答汇总各位返校生,最全购票乘车攻略来啦。一起来看学生火车票优惠购票政
上海市医疗博士团专家至利津县中心医院坐诊信息 妻子把丈夫情人接回家,单数陪自己双数陪情人,丈夫愁死了|法堂 开封府传奇周儿的结局(开封府周儿最后和谁在一起了) 烟台中小学生竞赛活动有哪些 烟台中小学生竞赛活动有哪些项目