pygame库写游戏——入门

[用Python和Pygame写游戏-从入门到精通(1)](http://eyehere.net/2011/python-pygame-novice-professional-1/)

经过断断续续的学习,对python的语法有了一定的认识,并且通过廖雪峰的教程和慕课网上几个课程的学习,模仿了其中几个小程序的编写。但是学习要回到实践中来,想尝试着编写几个小游戏,发现需要学习pygame库,而且脱离教程与模仿教程来编写是两种截然不同的体验。
最终找到这位大神的博客(包含pygame库的教学),代码的每一行都有中文注释,非常有助于我这种新手来理解每一行代码的含义。
因此准备通过他的博客系统的学习pygame库的使用,并且力图达到可编写小游戏的level。
接下来的几篇博客可以看做是自己学习中的总结吧。
1、安装pygame库——非常简单,可百度。
2、检测自己安装的pygame库版本:

import pygame
print(pygame.ver)
```我的版本为1.9.3,不过版本号基本没影响。
3、原博主的编写的hello world!程序片段注释非常的详细,可以去看看。
4、自己尝试编写的程序
`background_filename = 'sushiplate.jpg'
mouse_filename = 'fugu.png'

import pygame
from pygame.locals import *

pygame.init()


pygame.mouse.set_visible(False)
pygame.event.set_grab(True)




<div class="se-preview-section-delimiter"></div>

#这里可以把鼠标(小鱼)上面的鼠标箭头隐藏

screen = pygame.display.set_mode((640,480),NOFRAME,32)




<div class="se-preview-section-delimiter"></div>

#设置无边框,也可尝试其他的样式
mouse_cursor = pygame.display.set_caption('hello world!')

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()
while True:
  for event in pygame.event.get():
    if event.type == KEYDOWN:
      if event.key == K_SPACE:
        pygame.quit()
        #这里做了比较大的改进,按下空格键,退出程序

  screen.blit(background,(0,0))

  x,y = pygame.mouse.get_pos()
  x-= mouse_cursor.get_width() /2
  y-= mouse_cursor.get_height() /2
  #注意这里get_width()和/2中间有空格,否则会有错误

  screen.blit(mouse_cursor,(x,y))
  pygame.display.update()`


    ![新的hello world!程序——界面如下:](http://img.blog.csdn.net/20171128202246611?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwNDk3NzEy/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
    观察截图中被鱼替代的鼠标(显然还有一个黑色的小鼠标没有被完全覆盖),这里需要用到
    `pygame.mouse.set_visible(False)
pygame.event.set_grab(True)`
    ,但是我还没学会-_-




<div class="se-preview-section-delimiter"></div>

for event in pygame.event.get():
if event.type == QUIT:
#接到推出事件后退出程序
pygame.quit()
“`
这是程序的退出机制,但是原博主用的是exit(),但是在我电脑上无法退出程序(程序无反应),因此改成pygame.quit()。

设置无边框,也可尝试其他的样式

mouse_cursor = pygame.display.set_caption(‘hello world!’)

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
pygame.quit()
#这里做了比较大的改进,按下空格键,退出程序

screen.blit(background,(0,0))

x,y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() /2
y-= mouse_cursor.get_height() /2
#注意这里get_width()和/2中间有空格,否则会有错误

screen.blit(mouse_cursor,(x,y))
pygame.display.update()`


新的hello world!程序——界面如下:
观察截图中被鱼替代的鼠标(显然还有一个黑色的小鼠标没有被完全覆盖),这里需要用到
,但是我还没学会-_-

for event in pygame.event.get():
if event.type == QUIT:
#接到推出事件后退出程序
pygame.quit()

这是程序的退出机制,但是原博主用的是exit(),但是在我电脑上无法退出程序(程序无反应),因此改成pygame.quit()。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章