经过一段时间的python学习,爬取数据已经无法满足我的需求,于是想起了游戏。
下面做一个最简单的游戏,人物循环走动。
python中我们用到强大的库pygame
Pygame是被设计用来写游戏的python模块集合,Pygame是在优秀的SDL库之上开发的功能性包。使用python可以导入pygame来开发具有全部特性的游戏和多媒体软件,Pygame是极度轻便的并且可以运行在几乎所有的平台和操作系统上
pycharm如何安装pygame,这里重点说一下,以下是
https://pypi.org/project/pygame/1.9.3/
如果你使用命令pip install pygame==1.9.3 安装失败,并且安装下载.whl依然失败的话,你可以尝试安装他的稳定版本 pygame2.1.2版本,直接下面的命令
pip install pygame
安装完成后,建一个纯净版的python工程,这里就不赘述了。
下面是精华版代码
pygame.init()
2.设置游戏屏幕宽高
# 设置屏幕宽高 screen = pygame.display.set_mode((500, 500))
3.定义游戏名称
# 设置游戏名称 pygame.display.set_caption("小孩运动")

然后设置游戏背景图片
# 设置游戏的背景图片 bg = pygame.image.load("static/back.png") screen.blit(bg, (0, 0))
# 设置小孩初始运动位置 child = pygame.image.load("static/child.png") screen.blit(child, (200, 200))
接下来是关键,小孩要循环在X轴一定,而且有一定的速度,当移动超过屏幕的时候,要循环走动,接下来要怎么处理呢,请看代码
# 创建时钟对象,可以控制游戏循环的频率 clock = pygame.time.Clock() # 记录小孩移动的位置,定义了初始位置,在200 * 200的坐标, childRect = pygame.Rect(200, 200, 102, 126) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() else: # 通过时钟对象指定循环频率 clock.tick(60) # 向右移动 childRect.x += 1 if childRect.x > 500: # 这里的意思是当移动超过屏幕,让它重新到一个点,再次运动 childRect.x = 0 screen.blit(bg, (0, 0)) screen.blit(child, childRect) # 屏幕填充数据 pygame.display.update()
# -*- coding:utf-8 -*- # @Time:2022-2-22 17:24 # @Author:luoshao # @FileName:swore.py # @Software:PyCharm import sys import pygame pygame.init() # 设置屏幕宽高 screen = pygame.display.set_mode((500, 500)) # 设置游戏名称 pygame.display.set_caption("小孩运动") # 设置游戏的背景图片 bg = pygame.image.load("static/back.png") screen.blit(bg, (0, 0)) # 设置小孩初始运动位置 child = pygame.image.load("static/child.png") screen.blit(child, (200, 200)) # # 设置运行速度 # speed = [1, 1] # 设置背景颜色 # White = 255, 255, 255 # 创建时钟对象,可以控制游戏循环的频率 clock = pygame.time.Clock() # 记录小孩移动的位置 childRect = pygame.Rect(200, 200, 102, 126) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() else: # 通过时钟对象指定循环频率 clock.tick(60) # 向右移动 childRect.x += 1 if childRect.x > 500: childRect.x = 0 screen.blit(bg, (0, 0)) screen.blit(child, childRect) pygame.display.update()
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/228473.html原文链接:https://javaforall.net
