如何用Python制作游戏?内附代码 详细教学
一、游戏简介
二、编写步骤
1.引入库
代码如下:
###### AUTHOR:破茧狂龙 ############ DATE:20201002 ############ DESCRIPTION:移动的木板 ######import pygamefrom pygame.locals import *import sysimport timeimport random
2.初始化
代码如下:
pygame.init()BLACK = (0, 0, 0) # 黑色WHITE = (255, 255, 255) # 白色bg_color = (0,0,70) # 背景颜色red = (200, 0, 0) green = (0, 200, 0) bright_red = (255, 0, 0) bright_green = (0, 255, 0) smallText = pygame.font.SysFont(SimHei, 20) #comicsansmsmidlText = pygame.font.SysFont(SimHei, 50) barsize = [30, 10] SCREEN_SIZE = [400, 500] # 屏幕大小BALL_SIZE = [15, 15] # 球的尺寸fontcolor = (255,255,255) # 定义字体的颜色myimg = r"img1.jpg"background = pygame.image.load(myimg) # 图片位置 background = pygame.transform.scale(background, SCREEN_SIZE) # ball 初始位置ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2ball_pos_y = 0 # ball 移动方向ball_dir_y = 1 # 1:downball_pos = pygame.Rect(ball_pos_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1]) clock = pygame.time.Clock() # 定时器screen = pygame.display.set_mode(SCREEN_SIZE) # 设置标题pygame.display.set_caption(python小游戏-移动木板) # 设置图标image = pygame.image.load(myimg) pygame.display.set_icon(image)
3.相关自定义函数
代码如下:
###### 自定义函数 ##### #def button(msg, x, y, w, h, ic, ac, action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: pygame.draw.rect(screen, ac, (x, y, w, h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(screen, ic, (x, y, w, h)) textSurf, textRect = text_objects(msg, smallText) textRect.center = ((x + (w / 2)), (y + (h / 2))) screen.blit(textSurf, textRect) def text_objects(text, font): textSurface = font.render(text, True, fontcolor) return textSurface, textSurface.get_rect() def quitgame(): pygame.quit() quit()def message_diaplay(text): largeText = pygame.font.SysFont(SimHei, 115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((screen[0] / 2), (screen[1] / 2)) screen.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop()
4.相关自定义函数
代码如下:
三、完整的代码
代码如下:
结尾
下一篇:
推荐几个还在疯狂输出的前端大佬