最近开始学python,感觉挺好玩的,既有脚本语言的灵活性,又有丰富的类库与面向对象的特点,开发起来很方便。
游戏的规则和乒乓球一样,如果妙蛙种子掉地上了就算输,你可以用蓝色的跷跷板弹它,使他不落到地面上。
game over后可按任意键继续游戏或选择退出。
代码如下:
import sys, pygame
from random import *
from pygame.locals import *
from pygame.font import *
class myplayer(pygame.sprite.sprite):
def __init__(self, image_file, location, speed):
pygame.sprite.sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
self.status = true
def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]
if self.rect.top < 0:
self.speed[1] = -self.speed[1]
if self.rect.bottom > height:
#game over
self.status = false
class reflector(pygame.sprite.sprite):
if self.rect.top < 0 or self.rect.bottom > height:
def animate(players):
screen.fill([255,255,255])
for player in players:
player.move()
for player in players:
players.remove(player)
if pygame.sprite.spritecollide(player,players,false):
player.speed[0] = -player.speed[0]
player.speed[1] = -player.speed[1]
players.add(player)
screen.blit(player.image,player.rect)
pygame.display.flip()
pygame.time.delay(10)
pygame.init()
size = width,height = 640,480
screen = pygame.display.set_mode(size)
screen.fill([255,255,255])
pygame.display.set_caption("miaowa game")
def play():
img_player = "c:\users\dswu\desktop\player.png"
players = pygame.sprite.group()
for row in range(0,1):
for column in range(0,1):
playerlocation = [column*250+10,row*250+10]
playerspeed = [choice([-2,2]), choice([-2,2])]
player = myplayer(img_player, playerlocation, playerspeed)
players.add(player)
img_ref_path = "c:\users\dswu\desktop\reflector.png"
ref_pos = [0,464]
ref_speed = [0,0]
reflector = reflector(img_ref_path, ref_pos, ref_speed)
players.add(reflector)
running = true
while running:
key_pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.quit:
game.quit()
if event.type == keydown:
if event.key == k_left:
ref_speed[0] = -2
elif event.key == k_right:
ref_speed[0] = +2
animate(players)
if player.status == false:
running = false
final_text = "game over!"
ft_font = pygame.font.font(none, 100)
ft_surf = ft_font.render(final_text, 1, (0,0,0))
screen.blit(ft_surf, [screen.get_width()/2 - ft_surf.get_width()/2, 100])
tip_text = "type any key to continue"
tip_font = pygame.font.font(none, 50)
tip_surf = tip_font.render(tip_text, 1, (0,0,0))
screen.blit(tip_surf, [screen.get_width()/2 - tip_surf.get_width()/2, 200])
keepon = true
while keepon:
pygame.quit()
play()
play()
主要是通过pygame.sprite.sprite类实现碰撞的监控,通过事件的捕捉及判断实现这种弹力球类的游戏,其中涉及到文字在界面上的显示,游戏中的循环控制,以及重新开始游戏等。
把上面这段代码贴到你的idle中,找到下面这两行替换成你机器中的图片路径,按f5就可以运行了。
img_player = "c:\users\dswu\desktop\player.png"
img_ref_path = "c:\users\dswu\desktop\reflector.png"
由于比较简单,看看代码运行一下应该就差不多明白了,如果有不明白的地方请给我留言,方便一起学习与进步。
平时都在线,欢迎交流。
来源:51cto