sponsored links
自制python+pygame小游戏两枚
前几天在家没事干,花了点心思折腾了两个小东西。第一个射击游戏是跟着pygame官网上下载的一个游戏边学习源码边抄的,抄了个开头就变成自己乱搞加参考了。。虽然有心想装下蒜,但不知道那些协议什么的怎么搞。只能在这提一下了。。第二个是以前小时候玩过的,不知道该怎么叫,是看cs50公开课时课上的作业,他们叫the game of fifteen...。话说我们这边的学习能力真心普遍弱爆了。人家才上到3周课就干这个了,我们学校到了期末了有些人老师手把手教都还不会。。第一个:如图,白色方块是自己的飞机,白色小点是自己子弹,三条命。撞子弹就扣一条,撞敌人没做。。。代码:#! /usr/bin/env python#My Space Shooter
#qq: gmail:.#Importimport os, sys, pygame, random
from pygame.locals import *
pygame.init()
pygame.display.set_caption("My Space Shooter")
screen = pygame.display.set_mode((800, 600))
pygame.mouse.set_visible(0)
#Background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((100, 100, 255))
# TODO:Add music#Plane imagedef get_plane(rect, color = (0, 0, 0)):
surface = pygame.Surface(rect).convert()
surface.fill(color)
rect = surface.get_rect()
return surface, rect
#Playerclass Player(pygame.sprite.Sprite):
def__init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = get_plane((20,20), (255,255,255))
self.rect.center = (400, 500)
self.dx = 0
self.dy = 0
self.bullettimer = 0
self.firespeed = 25
self.life = 3
def update(self):
self.rect.move_ip((self.dx, self.dy))
#Fire the bulletif self.bullettimer & self.firespeed:
self.bullettimer += 1
key = pygame.key.get_pressed()
if key[pygame.K_SPACE] and self.bullettimer == self.firespeed:
bulletSprites.add(Bullet(self.rect.midtop))
self.bullettimer = 0
#Player Boundariesif self.rect.left & 0:
self.rect.left = 0
elif self.rect.right & 800:
self.rect.right = 800
if self.rect.top &= 260:
self.rect.top = 260
elif self.rect.bottom &= 600:
self.rect.bottom = 600
#Check if enemy bullets hit playerif pygame.sprite.groupcollide(playerSprite, enemyBulletSprites, 0, 1):
self.life -= 1
if self.life &= 0:
self.kill()
def reset(self):
self.rect.bottom = 600
self.firespeed = 25
def firespeed_up(self):
self.firespeed -= 5
if self.firespeed &= 5:
self.firespeed == 5
#Enemy classclass Enemy(pygame.sprite.Sprite):
def__init__(self,centerx):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = get_plane((20,20),(150,150,255))
self.reset()
def update(self):
self.rect.centerx += self.dx
self.rect.centery += self.dy
if self.rect.top & screen.get_height():
self.reset()
self.counter += 1
if self.counter &= 60:
enemyBulletSprites.add(EnemyBullet(self.rect.midbottom))
self.counter = 0
#Check if enemy plane touch player bulletsif pygame.sprite.groupcollide(enemySprites, bulletSprites, 1, 1):
#play explode movie and musicpassdef reset(self):
self.counter = random.randint(0, 60)
self.rect.bottom = 0
self.rect.centerx = random.randrange(0, screen.get_width())
self.dy = random.randrange(1, 4)
self.dx = random.randrange(-2, 2)
#Bullet classclass Bullet(pygame.sprite.Sprite):
def__init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = get_plane((5, 5),(255,255,255))
self.rect.center = pos
def update(self):
if self.rect.top & 0:
self.kill()
self.rect.move_ip(0, -5)
#Enemy bullet classclass EnemyBullet(pygame.sprite.Sprite):
def__init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = get_plane((5, 5),(150,150,255))
self.rect.center = pos
def update(self):
if self.rect.top & 0:
self.kill()
self.rect.move_ip(0, 5)
#Class Moduleclass SpaceMenu:
#Define the initalize self optionsdef__init__(self, *options):
self.options = options
self.x = 0
self.y = 0
self.font = pygame.font.Font(None, 32)
self.option = 0
self.width = 1
self.color = [0, 0, 0]
self.hcolor = [0, 0, 0]
self.height = len(options)*self.font.get_height()
for o in options:
text = o[0]
ren = self.font.render(text, 1, (0, 0, 0))
if ren.get_width() & self.width:
self.width = ren.get_width()
#Draw the menudef draw(self, surface):
for o in self.options:
if i == self.option:
clr = self.hcolor
clr = self.color
text = o[0]
ren = self.font.render(text, 1, clr)
if ren.get_width() & self.width:
self.width = ren.get_width()
surface.blit(ren, (self.x, self.y + i * self.font.get_height()))
#Handle eventsdef update(self, events):
for e in events:
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_UP:
self.option -= 1
elif e.key == pygame.K_DOWN:
self.option += 1
elif e.key == pygame.K_RETURN:
self.options[self.option][1]()
if self.option & len(self.options) - 1:
self.option = 0
elif self.option & 0:
self.option = len(self.options) - 1
#Position of menudef set_pos(self, x, y):
self.x = x
self.y = y
#Font Styledef set_font(self, font):
self.font = font
for o in self.options:
text = o[0]
ren = self.font.render(text, 1, (0, 0, 0))
if ren.get_width() & self.width:
self.width = ren.get_width()
#Highlight Colordef set_highlight_color(self, color):
self.hcolor = color
#Font Colordef set_normal_color(self, color):
self.color = color
#Font positiondef center_at(self, x, y):
self.x = x-(self.width/2)
self.y = y-(self.height/2)
def game():
#Game Object#global player
player = Player()
font = pygame.font.Font(None,32)
#Player/enemyglobal playerSprite
playerSprite = pygame.sprite.RenderPlain((player))
global enemySprites
enemySprites = pygame.sprite.RenderPlain(())
enemySprites.add(Enemy(200))
enemySprites.add(Enemy(300))
enemySprites.add(Enemy(400))
#Projectilesglobal bulletSprites
bulletSprites = pygame.sprite.RenderPlain(())
global enemyBulletSprites
enemyBulletSprites = pygame.sprite.RenderPlain(())
clock = pygame.time.Clock()
counter = 0
keepGoing = True
while keepGoing:
clock.tick(30)
#Handle inputfor event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
keepGoing = False
elif event.key == pygame.K_UP:
player.dy = -10
elif event.key == pygame.K_DOWN:
player.dy = 10
elif event.key == pygame.K_LEFT:
player.dx = -10
elif event.key == pygame.K_RIGHT:
player.dx = 10
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
player.dy = 0
elif event.key == pygame.K_DOWN:
player.dy = 0
elif event.key == pygame.K_LEFT:
player.dx = 0
elif event.key == pygame.K_RIGHT:
player.dx = 0
screen.blit(background, (0,0))
playerSprite.update()
enemySprites.update()
bulletSprites.update()
enemyBulletSprites.update()
text = "LIFE:" + str(player.life)
life = font.render(text, True, (255,255,255))
playerSprite.draw(screen)
enemySprites.draw(screen)
bulletSprites.draw(screen)
enemyBulletSprites.draw(screen)
screen.blit(life,(0,0))
pygame.display.flip()
#Create new enemies
counter += 1
if counter &= 20 and len(enemySprites) & 20:
enemySprites.add(Enemy(300))
counter = 0
#if game overif len(playerSprite) == 0:
gameOver()
keepGoing = False
def gameOver():
#Game over screen
menuTitle = SpaceMenu(
["GAME OVER"])
menuTitle.set_font(pygame.font.Font(None, 80))
menuTitle.center_at(400,230)
menuTitle.set_highlight_color((255,255,255))
info = SpaceMenu(
["Press ESC back to menu"])
info.set_font(pygame.font.Font(None, 40))
info.center_at(400,350)
info.set_highlight_color((255,255,255))
keepGoing = True
while keepGoing:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
keepGoing = False
elif event.type == pygame.QUIT:
keepGoing = False
menuTitle.draw(screen)
info.draw(screen)
pygame.display.flip()
def aboutMenu():
#About Menu Text#Title for Option Menu
menuTitle = SpaceMenu(
["Space Shooter"])
info = SpaceMenu(
["My Space Shooter"],
["Use arrow key to move your plane."],
["Contact me"],
["gmail:"],
PRESS ESC TO RETURN
#About Title Font color, aligment, and font type
menuTitle.set_font(pygame.font.Font(None, 60))
menuTitle.center_at(400, 150)
menuTitle.set_highlight_color((255, 255, 255))
#About info Font color, aligment, and font type
info.center_at(400, 320)
info.set_highlight_color((255, 255, 255))
info.set_normal_color((200, 200, 255))
clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(30)
#Handle inputfor event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
keepGoing = False
elif event.type == QUIT:
keepGoing = False
screen.blit(background, (0,0))
menuTitle.draw(screen)
info.draw(screen)
pygame.display.flip()
#Functionsdef option1():
def option2():
aboutMenu()
def option3():
pygame.quit()
sys.exit()
#Maindef main():
menuTitle = SpaceMenu(
["My Space Shooter"])
menu = SpaceMenu(
["Start", option1],
["About", option2],
["Exit", option3])
menuTitle.set_font(pygame.font.Font(None, 60))
menuTitle.center_at(400, 150)
menuTitle.set_highlight_color((255, 255, 255))
#Menu settings
menu.center_at(400, 320)
menu.set_highlight_color((255, 255, 255))
menu.set_normal_color((200, 200, 255))
clock = pygame.time.Clock()
keepGoing = True
while True:
clock.tick(30)
events = pygame.event.get()
#Update Menu
menu.update(events)
#Handle quit eventfor e in events:
if e.type == pygame.QUIT:
pygame.quit()
return#Draw
screen.blit(background, (0, 0))
menu.draw(screen)
menuTitle.draw(screen)
pygame.display.flip()
if__name__ == "__main__":
第二个:键盘输入是几乘几的矩阵,回车确定上下左右键移动方块,把全部方块按顺序拼回去就算结束。话说不是每个局面都一定能拼回去。。公开课的作业还有个黑客版本,就是威力加强版,要求做出来自动解题算法。我对着棋盘琢磨了大半天,无奈能力有限。。有哪位肯赐教的,不胜感激!&&&&&&&&&&&&&&&&&&&&&&&&几经周折了解到了这个叫做八数码问题,而且好像还是蛮经典的。。职高真是坑爹,一定要插本,学历倒是其次,主要是这眼界太搓了。。学校似乎是觉得我们出去能帮人家做个网站拼个音乐播放器什么的就实现了人生目标了。。我可不想这么着。。(编辑)&&&&&&&&&&&&&&&&&&&&&&&&代码:#! /usr/bin/env python#the game of fifteen
#qq: gmail:.#importimport random
import pygame
from pygame.locals import *
from sys import exit
WHITE = (255, 255, 255)
BLUE = (150, 150, 255)
NUMPIECEWIDTH = 50
#initpygame.init()
global screen
screen = pygame.display.set_mode((800, 600))
# NumPiece classclass NumPiece(pygame.Surface):
font = pygame.font.Font(None, 30)
def__init__(self, num):
pygame.surface.Surface.__init__(self, (NUMPIECEWIDTH, NUMPIECEWIDTH))
self.fill(BLUE)
text = NumPiece.font.render(str(num), 1, WHITE)
textRect = text.get_rect()
textRect.center = (NUMPIECEWIDTH / 2, NUMPIECEWIDTH / 2)
self.blit(text, textRect.topleft)
#the game() functiondef game():
numPieces = []
tmpPieces = range(1, num * num)
while len(tmpPieces) & 1:
numPieces.append(NumPiece(tmpPieces.pop(random.randint(0, len(tmpPieces) - 1))))
numPieces.append(NumPiece(tmpPieces.pop()))
numPieces.append(0)
now = num * num - 1
while True:
#Handle event
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
elif event.key == K_UP:
if now / num & 0:
numPieces[now] = numPieces[now - num]
numPieces[now - num] = 0
now = now - num
elif event.key == K_DOWN:
if now / num & num - 1:
numPieces[now] = numPieces[now + num]
numPieces[now + num] = 0
now = now + num
elif event.key == K_LEFT:
if now % num & 0:
numPieces[now] = numPieces[now - 1]
numPieces[now - 1] = 0
now = now - 1
elif event.key == K_RIGHT:
if now % num & num - 1:
numPieces[now] = numPieces[now + 1]
numPieces[now + 1] = 0
now = now + 1
screen.fill(WHITE)
#Draw NumPieces
startPoint = (0, 0)
counter = 0
for np in numPieces:
if np == 0:
counter += 1
continueelse:
xy = (startPoint[0] + (counter%num) * (NUMPIECEWIDTH + 10), startPoint[1] + (counter/num) * (NUMPIECEWIDTH + 10))
screen.blit(np, xy)
counter += 1
pygame.display.flip()
#maindef main():
font = pygame.font.Font(None, 60)
global num
clock = pygame.time.Clock()
while True:
clock.tick(30)
#Handle input
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
elif event.key in range(48, 57 + 1):
num = num * 10 + event.key - 48
elif event.key == K_RETURN:
text = font.render(str(num), 1, BLUE)
textRect = text.get_rect()
textRect.center = (screen.get_width() / 2, screen.get_height() / 2)
screen.fill(WHITE)
screen.blit(text, (textRect.topleft))
pygame.display.flip()
#start hereif__name__ == "__main__":
没有周队那么有情调,自己写故事做rpg,又没什么绘画功底,只能做这样的休闲棋类游戏.本来是用java写的,但里面绘图太麻烦了(或者说我不会多线程),又想起前几天看到的pygame,于是果断python搞起了,从***pygame,连学代做,到基本功能完成一共也不过两三个小时(小自恋一下-),又花了一个下午时间调整修正,终于可以拿出手了--五子连珠是老妈最喜欢的 ...
#^_^coding=gbk ^_^ import linecache #数据分割 f = [ x.replace('\n','') for x in linecache.getlines('a.txt')] items = [filter(lambda k:k.startswith(str(x)),f) for x in range(1,6)] items ...
这是我最后一篇博客了,由于本人的人生规划吧,以后应该也写不出什么好的技术文章了,到现在在博客园写了2年, 今天一看,我也有了120个粉丝,好几万的浏览量,感谢大家的支持啊~~ 半年没有写博客了,由于半年前为了不出差多点时间陪女神果断翻身到甲方麾下,在甲方搞技术果然 so easy~,在甲方的电商部门,主要玩web前端和PHP,没有继续深入研究.net的知 ...
这是我最后一篇博客了,由于本人的人生规划吧,以后应该也写不出什么好的技术文章了,到现在在博客园写了2年, 今天一看,我也有了120个粉丝,好几万的浏览量,感谢大家的支持啊~~ 半年没有写博客了,由于半年前为了不出差多点时间陪女神果断翻身到甲方麾下,在甲方搞技术果然 so easy~,在甲方的电商部门,主要玩web前端和PHP,没有继续深入研究.net的知 ...
你有没有想过电脑游戏是怎样制作出来的?其实它没有你想象的那样复杂!在这个教程里,你要学做一个叫&兔子和獾&的塔防游戏,兔子作为英雄,需要在城堡里抵御獾的进攻.为了写这个游戏的代码,你将会用Python.好吧,我不是指一条大蟒蛇!Python是一种计算机语言.我们在这篇教程里选择Python是因为这门语言很容易上手,学习起来也很简单和有趣.如果你是 ...原创于西周而后沿袭至今的彩礼,虽然被一部分家长奉为圭臬,但越来越多的年轻人对结婚必须要彩礼不以为然。彩礼引发的社会矛盾越来越受到关注,结婚是自己的事,如人饮水冷暖自知,至于要不要彩礼或者要多少彩礼,因人而异,因财力而已,不可一概而论。
在此可输入您对该资料的评论~
(window.slotbydup = window.slotbydup || []).push({
id: '4540180',
container: s,
size: '250,200',
display: 'inlay-fix'
热门资料排行
添加成功至
资料评价:
所需积分:0python 2.7.9 win7 64位***pygame(其他版本都有) | KouKou
& python 2.7.9 win7 64位***pygame(其他版本都有)
6,521 views
在网上苦苦搜索了许多方法都***不了pygame,总是提示一些插件not found 。终于发现了如何***pygame了,现把我的经验分享给大家。1. 首先你的电脑要有 pip 插件,详情查看2. CMD 执行命令 ~
pip install wheelcmd ~
, 出现 wheel ,证明wheel插件***成功!3.然后打开 这个网址 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame找到 pygame 你对应的版本并下载到c盘。32是32位的,64是64位的4. 在c盘下执行cmd 命令 ~ wheel install pygame-1.9.2a0-cp27-none-win_amd64.whl(你下载pygame的对应名称)5. 测试 ,***成功~&&
您可能也喜欢:& & process = subprocess.Popen('cmd命令') & & pid = process.pid & & print(pid)适用于python 3+ pymsql 扩展类,包含增删改查 首先要***pymsql , pip install pymsql #!/usr/bin/env python # -*- coding: utf-8 -*- import pymysql imp...pycharm最新激活方法 2016.2 。 有2种方法,第一种激活方法不行就试试第二种。 1.选License server激活,输入:http://114.215.133.70:41017/ 2.选择第二种激...
8,020 views
7,624 views
6,521 views
3,940 views
3,775 views