1、运动速率
上节中,实现了一辆汽车在马路上由下到上行驶,并使用了pygame.time.delay(200)来进行时间延迟。看了很多参考材料,基本每个材料都会谈到不同配置机器下运动速率的问题,有的是通过设定频率解决,有的是通过设定速度解决,自己本身水平有限,看了几篇,觉得还是《Beginning Game Development with Python and Pygame》这里面提到一个方法比较好。代码如下,代码里更改的地方主要是main里的代码,其中利用clock=pygame.time.Clock()来定义时钟,speed=250.0定义了速度,每秒250像素,time_passed=clock.tick()为上次运行时间单位是毫秒,time_passed_seconds=time_passed/1000.0将单位改为秒,distance_moved=time_passed_seconds*speed时间乘以速度得到移动距离,这样就能保证更加流畅。
import pygame,sys
def lineleft():
plotpoints=[]
for x in range(0,640):
y=-5*x+1000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def lineright():
plotpoints=[]
for x in range(0,640):
y=5*x-2000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def linemiddle():
plotpoints=[]
x=300
for y in range(0,480,20):
plotpoints.append([x,y])
if len(plotpoints)==2:
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
plotpoints=[]
pygame.display.flip()
def loadcar(yloc):
my_car=pygame.image.load('ok1.jpg')
locationxy=[310,yloc]
screen.blit(my_car,locationxy)
pygame.display.flip()
if __name__=='__main__':
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
lineleft()
lineright()
linemiddle()
clock=pygame.time.Clock()
looper=480
speed=250.0
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
pygame.draw.rect(screen,[255,255,255],[310,(looper+132),83,132],0)
time_passed=clock.tick()
time_passed_seconds=time_passed/1000.0
distance_moved=time_passed_seconds*speed
looper-=distance_moved
if looper
looper=480
loadcar(looper)
2、事件
我理解的就是用来解决键盘、鼠标、遥控器等输入后做出什么反映的。例如上面的例子,可以通过按上方向键里向上来使得小车向上移动,按下向下,使得小车向下移动。当小车从下面倒出时,会从上面再出现,当小车从上面驶出时,会从下面再出现。代码如下。event.type == pygame.KEYDOWN用来定义事件类型,if event.key==pygame.K_UP这里是指当按下向上箭头时,车前进。if event.key==pygame.K_DOWN则相反,指按下向下箭头,车后退。
import pygame,sys
def lineleft():
plotpoints=[]
for x in range(0,640):
y=-5*x+1000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def lineright():
plotpoints=[]
for x in range(0,640):
y=5*x-2000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def linemiddle():
plotpoints=[]
x=300
for y in range(0,480,20):
plotpoints.append([x,y])
if len(plotpoints)==2:
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
plotpoints=[]
pygame.display.flip()
def loadcar(yloc):
my_car=pygame.image.load('ok1.jpg')
locationxy=[310,yloc]
screen.blit(my_car,locationxy)
pygame.display.flip()
if __name__=='__main__':
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
lineleft()
lineright()
linemiddle()
looper=480
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key==pygame.K_UP:
looper=looper-50
if looper
looper=480
pygame.draw.rect(screen,[255,255,255],[310,(looper+132),83,132],0)
loadcar(looper)
if event.key==pygame.K_DOWN:
looper=looper+50
if looper>480:
looper=-480
pygame.draw.rect(screen,[255,255,255],[310,(looper-132),83,132],0)
loadcar(looper)
3、字体及字符显示
使用字体模块用来做游戏的文字显示,大部分游戏都会有诸如比分、时间、生命值等的文字信息。pygame主要是使用pygame.font模块来完成,常用到的一些方法是:
pygame.font.SysFont(None, 16),第一个参数是说明字体的,可以是"arial"等,这里None表示默认字体。第二个参数表示字的大小。如果无法知道当前系统中装了哪些字体,可以使用pygame.font.get_fonts()来获得所有可用字体。
pygame.font.Font("AAA.ttf", 16),用来使用TTF字体文件。
render("hello world!", True, (0,0,0), (255, 255, 255)),render方法用来创建文字。第一个参数是写的文字;第二个参数是否开启抗锯齿,就是说True的话字体会比较平滑,不过相应的速度有一点点影响;第三个参数是字体的颜色;第四个是背景色,无表示透明。
下面将上面的例子添加当前汽车坐标:
import pygame,sys
def lineleft():
plotpoints=[]
for x in range(0,640):
y=-5*x+1000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def lineright():
plotpoints=[]
for x in range(0,640):
y=5*x-2000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def linemiddle():
plotpoints=[]
x=300
for y in range(0,480,20):
plotpoints.append([x,y])
if len(plotpoints)==2:
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
plotpoints=[]
pygame.display.flip()
def loadcar(yloc):
my_car=pygame.image.load('ok1.jpg')
locationxy=[310,yloc]
screen.blit(my_car,locationxy)
pygame.display.flip()
def loadtext(xloc,yloc):
textstr='location:'+str(xloc)+','+str(yloc)
text_screen=my_font.render(textstr, True, (255, 0, 0))
screen.blit(text_screen, (50,50))
if __name__=='__main__':
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
my_font=pygame.font.SysFont(None,22)
screen.fill([255,255,255])
loadtext(310,0)
lineleft()
lineright()
linemiddle()
looper=480
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key==pygame.K_UP:
looper=looper-50
if looper
looper=480
if event.key==pygame.K_DOWN:
looper=looper+50
if looper>480:
looper=-132
loadtext(310,looper)
screen.fill([255,255,255])
loadtext(310,looper)
lineleft()
lineright()
linemiddle()
loadcar(looper)
这个例子里直接让背景重绘一下,就不会再像1、2里面那样用空白的rect去覆盖前面的模块了。

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는
