小球游戏2.0
这个改的挺不错的import pygame
from pygame.locals import *
from sys import exit
from random import randint
from time import sleep
#导入
pygame.init()
pygame.mixer.init()
#初始化
pygame.mixer.music.load('你想要的音乐名称,自己下载~')
pygame.mixer.music.play(-1, 250)
num = 0
size_of_window = (640, 480)
my_font = pygame.font.Font('mmrtextb.ttf', 40)
screen = pygame.display.set_mode(size_of_window , 0 , 32)
background_image = pygame.image.load('background.jpg').convert_alpha()
#播放音乐、准备变量、字体和桌面
class Guard:
'''定义一个挡板类,实现用户操作和显示功能'''
def __init__(self, screen):
self.x = randint(1,size_of_window)
self.y = size_of_window - 40
self.toX = 0
self.toY = 0
self.screen = screen
self.picture = pygame.image.load('guard.png')
def display(self):
self.screen.blit(self.picture, (self.x, self.y))
def move(self):
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
self.toX = self.toX - 21
elif event.key == K_RIGHT:
self.toX = self.toX + 21
elif event.key == K_UP:
self.toY = self.toY - 21
elif event.key == K_DOWN:
self.toY = self.toY + 21
elif event.type == KEYUP:
self.toX = 0
self.toY = 0
self.x = self.x + self.toX
self.y = self.y + self.toY
class Ball:
'''定义了一个球类,包含球类的一切,创建一个实例对象就可以有一个随意移动的球了。'''
def __init__(self, screen):
self.x = randint(0, size_of_window)
self.y = randint(0, size_of_window)
self.gotoX = 5
self.gotoY = 5
self.screen = screen
self.picture = pygame.image.load('ball.png')
self.flag = 0
def display(self):
#显示小球
self.screen.blit(self.picture, (self.x, self.y))
def move(self, guard):
#移动小球
if self.x >= size_of_window or self.x <= 0:
self.gotoX = -self.gotoX
if self.y >= size_of_window or self.y <=0:
self.gotoY = -self.gotoY
#如果碰到边界
if self.x >= guard.x and self.x <= guard.x + guard.picture.get_width():
if self.y >= guard.y and self.y <= guard.y + guard.picture.get_height():
self.gotoY = -self.gotoY
self.flag = 1
self.x = self.x + self.gotoX
self.y = self.y + self.gotoY
#赋值
#如果碰到挡板
if self.flag == 1:
self.flag = 0
return num+1
return num
guard = Guard(screen)
ball = Ball(screen)
#创建实例
while True:
'''游戏主循环'''
text_font = my_font.render(u"score: %d"%num, True, (0, 0, 255))
screen.blit(background_image, (0, 0))
screen.blit(text_font, (400, 0))
guard.display()
ball.display()
#显示
guard.move()
num = ball.move(guard)
#输入和移动(小球)
pygame.display.flip()
sleep(0.01)
#pygame.display.update()
#更新
**** Hidden Message *****
回复有惊喜啊~~~
这个游戏实在让我着实感到了Python面向对象的强大~~你可以把游戏主循环改一下,就可以得到你想要的结果~~{:10_256:} 看看惊喜 看看 这个网址可以让你十分方便地下载音乐(回复即可得到) 学习学习! 加精华警告~! 学习 厉害 我看看什么惊喜 惊喜是啥 kankan
期待
6 加油 看看惊喜 跟着学习了,感谢! 回复有惊喜 的
页:
[1]