色哟哟视频在线观看-色哟哟视频在线-色哟哟欧美15最新在线-色哟哟免费在线观看-国产l精品国产亚洲区在线观看-国产l精品国产亚洲区久久

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

教你如何通過邊打游戲邊學編程

Linux愛好者 ? 來源:CSDN ? 作者:天天開心學編程 ? 2022-07-13 12:01 ? 次閱讀

經常聽到有朋友說,學習編程是一件非常枯燥無味的事情。其實,大家有沒有認真想過,可能是我們的學習方法不對?比方說,你有沒有想過,可以通過打游戲來學編程?

今天我想跟大家分享幾個Python小游戲,教你如何通過邊打游戲邊學編程

1、吃金幣

c6eea860-025f-11ed-ba43-dac502259ad0.gif

源碼分享:

importos
importcfg
importsys
importpygame
importrandom
frommodulesimport*


'''游戲初始化'''
definitGame():
#初始化pygame,設置展示窗口
pygame.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('catchcoins——九歌')
#加載必要的游戲素材
game_images={}
forkey,valueincfg.IMAGE_PATHS.items():
ifisinstance(value,list):
images=[]
foriteminvalue:images.append(pygame.image.load(item))
game_images[key]=images
else:
game_images[key]=pygame.image.load(value)
game_sounds={}
forkey,valueincfg.AUDIO_PATHS.items():
ifkey=='bgm':continue
game_sounds[key]=pygame.mixer.Sound(value)
#返回初始化數據
returnscreen,game_images,game_sounds


'''主函數'''
defmain():
#初始化
screen,game_images,game_sounds=initGame()
#播放背景音樂
pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
pygame.mixer.music.play(-1,0.0)
#字體加載
font=pygame.font.Font(cfg.FONT_PATH,40)
#定義hero
hero=Hero(game_images['hero'],position=(375,520))
#定義食物組
food_sprites_group=pygame.sprite.Group()
generate_food_freq=random.randint(10,20)
generate_food_count=0
#當前分數/歷史最高分
score=0
highest_score=0ifnotos.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH)elseint(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
#游戲主循環
clock=pygame.time.Clock()
whileTrue:
#--填充背景
screen.fill(0)
screen.blit(game_images['background'],(0,0))
#--倒計時信息
countdown_text='Countdown:'+str((90000-pygame.time.get_ticks())//60000)+":"+str((90000-pygame.time.get_ticks())//1000%60).zfill(2)
countdown_text=font.render(countdown_text,True,(0,0,0))
countdown_rect=countdown_text.get_rect()
countdown_rect.topright=[cfg.SCREENSIZE[0]-30,5]
screen.blit(countdown_text,countdown_rect)
#--按鍵檢測
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed=pygame.key.get_pressed()
ifkey_pressed[pygame.K_a]orkey_pressed[pygame.K_LEFT]:
hero.move(cfg.SCREENSIZE,'left')
ifkey_pressed[pygame.K_d]orkey_pressed[pygame.K_RIGHT]:
hero.move(cfg.SCREENSIZE,'right')
#--隨機生成食物
generate_food_count+=1
ifgenerate_food_count>generate_food_freq:
generate_food_freq=random.randint(10,20)
generate_food_count=0
food=Food(game_images,random.choice(['gold',]*10+['apple']),cfg.SCREENSIZE)
food_sprites_group.add(food)
#--更新食物
forfoodinfood_sprites_group:
iffood.update():food_sprites_group.remove(food)
#--碰撞檢測
forfoodinfood_sprites_group:
ifpygame.sprite.collide_mask(food,hero):
game_sounds['get'].play()
food_sprites_group.remove(food)
score+=food.score
ifscore>highest_score:highest_score=score
#--畫hero
hero.draw(screen)
#--畫食物
food_sprites_group.draw(screen)
#--顯示得分
score_text=f'Score:{score},Highest:{highest_score}'
score_text=font.render(score_text,True,(0,0,0))
score_rect=score_text.get_rect()
score_rect.topleft=[5,5]
screen.blit(score_text,score_rect)
#--判斷游戲是否結束
ifpygame.time.get_ticks()>=90000:
break
#--更新屏幕
pygame.display.flip()
clock.tick(cfg.FPS)
#游戲結束,記錄最高分并顯示游戲結束畫面
fp=open(cfg.HIGHEST_SCORE_RECORD_FILEPATH,'w')
fp.write(str(highest_score))
fp.close()
returnshowEndGameInterface(screen,cfg,score,highest_score)


'''run'''
if__name__=='__main__':
whilemain():
pass

2、打乒乓

c7215468-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importsys
importcfg
importpygame
frommodulesimport*


'''定義按鈕'''
defButton(screen,position,text,button_size=(200,50)):
left,top=position
bwidth,bheight=button_size
pygame.draw.line(screen,(150,150,150),(left,top),(left+bwidth,top),5)
pygame.draw.line(screen,(150,150,150),(left,top-2),(left,top+bheight),5)
pygame.draw.line(screen,(50,50,50),(left,top+bheight),(left+bwidth,top+bheight),5)
pygame.draw.line(screen,(50,50,50),(left+bwidth,top+bheight),(left+bwidth,top),5)
pygame.draw.rect(screen,(100,100,100),(left,top,bwidth,bheight))
font=pygame.font.Font(cfg.FONTPATH,30)
text_render=font.render(text,1,(255,235,205))
returnscreen.blit(text_render,(left+50,top+10))


'''
Function:
開始界面
Input:
--screen:游戲界面
Return:
--game_mode:1(單人模式)/2(雙人模式)
'''
defstartInterface(screen):
clock=pygame.time.Clock()
whileTrue:
screen.fill((41,36,33))
button_1=Button(screen,(150,175),'1Player')
button_2=Button(screen,(150,275),'2Player')
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
ifevent.type==pygame.MOUSEBUTTONDOWN:
ifbutton_1.collidepoint(pygame.mouse.get_pos()):
return1
elifbutton_2.collidepoint(pygame.mouse.get_pos()):
return2
clock.tick(10)
pygame.display.update()


'''結束界面'''
defendInterface(screen,score_left,score_right):
clock=pygame.time.Clock()
font1=pygame.font.Font(cfg.FONTPATH,30)
font2=pygame.font.Font(cfg.FONTPATH,20)
msg='Playeronleftwon!'ifscore_left>score_rightelse'Playeronrightwon!'
texts=[font1.render(msg,True,cfg.WHITE),
font2.render('PressESCAPEtoquit.',True,cfg.WHITE),
font2.render('PressENTERtocontinueorplayagain.',True,cfg.WHITE)]
positions=[[120,200],[155,270],[80,300]]
whileTrue:
screen.fill((41,36,33))
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
ifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_RETURN:
return
elifevent.key==pygame.K_ESCAPE:
sys.exit()
pygame.quit()
fortext,posinzip(texts,positions):
screen.blit(text,pos)
clock.tick(10)
pygame.display.update()


'''運行游戲Demo'''
defrunDemo(screen):
#加載游戲素材
hit_sound=pygame.mixer.Sound(cfg.HITSOUNDPATH)
goal_sound=pygame.mixer.Sound(cfg.GOALSOUNDPATH)
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1,0.0)
font=pygame.font.Font(cfg.FONTPATH,50)
#開始界面
game_mode=startInterface(screen)
#游戲主循環
#--左邊球拍(ws控制,僅雙人模式時可控制)
score_left=0
racket_left=Racket(cfg.RACKETPICPATH,'LEFT',cfg)
#--右邊球拍(↑↓控制)
score_right=0
racket_right=Racket(cfg.RACKETPICPATH,'RIGHT',cfg)
#--球
ball=Ball(cfg.BALLPICPATH,cfg)
clock=pygame.time.Clock()
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit(-1)
screen.fill((41,36,33))
#玩家操作
pressed_keys=pygame.key.get_pressed()
ifpressed_keys[pygame.K_UP]:
racket_right.move('UP')
elifpressed_keys[pygame.K_DOWN]:
racket_right.move('DOWN')
ifgame_mode==2:
ifpressed_keys[pygame.K_w]:
racket_left.move('UP')
elifpressed_keys[pygame.K_s]:
racket_left.move('DOWN')
else:
racket_left.automove(ball)
#球運動
scores=ball.move(ball,racket_left,racket_right,hit_sound,goal_sound)
score_left+=scores[0]
score_right+=scores[1]
#顯示
#--分隔線
pygame.draw.rect(screen,cfg.WHITE,(247,0,6,500))
#--球
ball.draw(screen)
#--拍
racket_left.draw(screen)
racket_right.draw(screen)
#--得分
screen.blit(font.render(str(score_left),False,cfg.WHITE),(150,10))
screen.blit(font.render(str(score_right),False,cfg.WHITE),(300,10))
ifscore_left==11orscore_right==11:
returnscore_left,score_right
clock.tick(100)
pygame.display.update()


'''主函數'''
defmain():
#初始化
pygame.init()
pygame.mixer.init()
screen=pygame.display.set_mode((cfg.WIDTH,cfg.HEIGHT))
pygame.display.set_caption('pingpong——九歌')
#開始游戲
whileTrue:
score_left,score_right=runDemo(screen)
endInterface(screen,score_left,score_right)


'''run'''
if__name__=='__main__':
main()

3、滑雪

c746b71c-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importsys
importcfg
importpygame
importrandom


'''滑雪者類'''
classSkierClass(pygame.sprite.Sprite):
def__init__(self):
pygame.sprite.Sprite.__init__(self)
#滑雪者的朝向(-2到2)
self.direction=0
self.imagepaths=cfg.SKIER_IMAGE_PATHS[:-1]
self.image=pygame.image.load(self.imagepaths[self.direction])
self.rect=self.image.get_rect()
self.rect.center=[320,100]
self.speed=[self.direction,6-abs(self.direction)*2]
'''改變滑雪者的朝向.負數為向左,正數為向右,0為向前'''
defturn(self,num):
self.direction+=num
self.direction=max(-2,self.direction)
self.direction=min(2,self.direction)
center=self.rect.center
self.image=pygame.image.load(self.imagepaths[self.direction])
self.rect=self.image.get_rect()
self.rect.center=center
self.speed=[self.direction,6-abs(self.direction)*2]
returnself.speed
'''移動滑雪者'''
defmove(self):
self.rect.centerx+=self.speed[0]
self.rect.centerx=max(20,self.rect.centerx)
self.rect.centerx=min(620,self.rect.centerx)
'''設置為摔倒狀態'''
defsetFall(self):
self.image=pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
'''設置為站立狀態'''
defsetForward(self):
self.direction=0
self.image=pygame.image.load(self.imagepaths[self.direction])


'''
Function:
障礙物類
Input:
img_path:障礙物圖片路徑
location:障礙物位置
attribute:障礙物類別屬性
'''
classObstacleClass(pygame.sprite.Sprite):
def__init__(self,img_path,location,attribute):
pygame.sprite.Sprite.__init__(self)
self.img_path=img_path
self.image=pygame.image.load(self.img_path)
self.location=location
self.rect=self.image.get_rect()
self.rect.center=self.location
self.attribute=attribute
self.passed=False
'''移動'''
defmove(self,num):
self.rect.centery=self.location[1]-num


'''創建障礙物'''
defcreateObstacles(s,e,num=10):
obstacles=pygame.sprite.Group()
locations=[]
foriinrange(num):
row=random.randint(s,e)
col=random.randint(0,9)
location=[col*64+20,row*64+20]
iflocationnotinlocations:
locations.append(location)
attribute=random.choice(list(cfg.OBSTACLE_PATHS.keys()))
img_path=cfg.OBSTACLE_PATHS[attribute]
obstacle=ObstacleClass(img_path,location,attribute)
obstacles.add(obstacle)
returnobstacles


'''合并障礙物'''
defAddObstacles(obstacles0,obstacles1):
obstacles=pygame.sprite.Group()
forobstacleinobstacles0:
obstacles.add(obstacle)
forobstacleinobstacles1:
obstacles.add(obstacle)
returnobstacles


'''顯示游戲開始界面'''
defShowStartInterface(screen,screensize):
screen.fill((255,255,255))
tfont=pygame.font.Font(cfg.FONTPATH,screensize[0]//5)
cfont=pygame.font.Font(cfg.FONTPATH,screensize[0]//20)
title=tfont.render(u'滑雪游戲',True,(255,0,0))
content=cfont.render(u'按任意鍵開始游戲',True,(0,0,255))
trect=title.get_rect()
trect.midtop=(screensize[0]/2,screensize[1]/5)
crect=content.get_rect()
crect.midtop=(screensize[0]/2,screensize[1]/2)
screen.blit(title,trect)
screen.blit(content,crect)
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
elifevent.type==pygame.KEYDOWN:
return
pygame.display.update()


'''顯示分數'''
defshowScore(screen,score,pos=(10,10)):
font=pygame.font.Font(cfg.FONTPATH,30)
score_text=font.render("Score:%s"%score,True,(0,0,0))
screen.blit(score_text,pos)


'''更新當前幀的游戲畫面'''
defupdateFrame(screen,obstacles,skier,score):
screen.fill((255,255,255))
obstacles.draw(screen)
screen.blit(skier.image,skier.rect)
showScore(screen,score)
pygame.display.update()


'''主程序'''
defmain():
#游戲初始化
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
#設置屏幕
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('滑雪游戲——九歌')
#游戲開始界面
ShowStartInterface(screen,cfg.SCREENSIZE)
#實例化游戲精靈
#--滑雪者
skier=SkierClass()
#--創建障礙物
obstacles0=createObstacles(20,29)
obstacles1=createObstacles(10,19)
obstaclesflag=0
obstacles=AddObstacles(obstacles0,obstacles1)
#游戲clock
clock=pygame.time.Clock()
#記錄滑雪的距離
distance=0
#記錄當前的分數
score=0
#記錄當前的速度
speed=[0,6]
#游戲主循環
whileTrue:
#--事件捕獲
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
ifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_LEFTorevent.key==pygame.K_a:
speed=skier.turn(-1)
elifevent.key==pygame.K_RIGHTorevent.key==pygame.K_d:
speed=skier.turn(1)
#--更新當前游戲幀的數據
skier.move()
distance+=speed[1]
ifdistance>=640andobstaclesflag==0:
obstaclesflag=1
obstacles0=createObstacles(20,29)
obstacles=AddObstacles(obstacles0,obstacles1)
ifdistance>=1280andobstaclesflag==1:
obstaclesflag=0
distance-=1280
forobstacleinobstacles0:
obstacle.location[1]=obstacle.location[1]-1280
obstacles1=createObstacles(10,19)
obstacles=AddObstacles(obstacles0,obstacles1)
forobstacleinobstacles:
obstacle.move(distance)
#--碰撞檢測
hitted_obstacles=pygame.sprite.spritecollide(skier,obstacles,False)
ifhitted_obstacles:
ifhitted_obstacles[0].attribute=="tree"andnothitted_obstacles[0].passed:
score-=50
skier.setFall()
updateFrame(screen,obstacles,skier,score)
pygame.time.delay(1000)
skier.setForward()
speed=[0,6]
hitted_obstacles[0].passed=True
elifhitted_obstacles[0].attribute=="flag"andnothitted_obstacles[0].passed:
score+=10
obstacles.remove(hitted_obstacles[0])
#--更新屏幕
updateFrame(screen,obstacles,skier,score)
clock.tick(cfg.FPS)


'''run'''
if__name__=='__main__':
 main();

4、并夕夕版飛機大戰

c7616df0-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importsys
importcfg
importpygame
frommodulesimport*


'''游戲界面'''
defGamingInterface(num_player,screen):
#初始化
pygame.mixer.music.load(cfg.SOUNDPATHS['CoolSpaceMusic'])
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
explosion_sound=pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
fire_sound=pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
font=pygame.font.Font(cfg.FONTPATH,20)
#游戲背景圖
bg_imgs=[cfg.IMAGEPATHS['bg_big'],cfg.IMAGEPATHS['seamless_space'],cfg.IMAGEPATHS['space3']]
bg_move_dis=0
bg_1=pygame.image.load(bg_imgs[0]).convert()
bg_2=pygame.image.load(bg_imgs[1]).convert()
bg_3=pygame.image.load(bg_imgs[2]).convert()
#玩家,子彈和小行星精靈組
player_group=pygame.sprite.Group()
bullet_group=pygame.sprite.Group()
asteroid_group=pygame.sprite.Group()
#產生小行星的時間間隔
asteroid_ticks=90
foriinrange(num_player):
player_group.add(Ship(i+1,cfg))
clock=pygame.time.Clock()
#分數
score_1,score_2=0,0
#游戲主循環
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
#--玩家一:↑↓←→控制,j射擊;玩家二:wsad控制,空格射擊
pressed_keys=pygame.key.get_pressed()
foridx,playerinenumerate(player_group):
direction=None
ifidx==0:
ifpressed_keys[pygame.K_UP]:
direction='up'
elifpressed_keys[pygame.K_DOWN]:
direction='down'
elifpressed_keys[pygame.K_LEFT]:
direction='left'
elifpressed_keys[pygame.K_RIGHT]:
direction='right'
ifdirection:
player.move(direction)
ifpressed_keys[pygame.K_j]:
ifplayer.cooling_time==0:
fire_sound.play()
bullet_group.add(player.shot())
player.cooling_time=20
elifidx==1:
ifpressed_keys[pygame.K_w]:
direction='up'
elifpressed_keys[pygame.K_s]:
direction='down'
elifpressed_keys[pygame.K_a]:
direction='left'
elifpressed_keys[pygame.K_d]:
direction='right'
ifdirection:
player.move(direction)
ifpressed_keys[pygame.K_SPACE]:
ifplayer.cooling_time==0:
fire_sound.play()
bullet_group.add(player.shot())
player.cooling_time=20
ifplayer.cooling_time>0:
player.cooling_time-=1
if(score_1+score_2)elif(score_1+score_2)else:
background=bg_3
#--向下移動背景圖實現飛船向上移動的效果
screen.blit(background,(0,-background.get_rect().height+bg_move_dis))
screen.blit(background,(0,bg_move_dis))
bg_move_dis=(bg_move_dis+2)%background.get_rect().height
#--生成小行星
ifasteroid_ticks==0:
asteroid_ticks=90
asteroid_group.add(Asteroid(cfg))
else:
asteroid_ticks-=1
#--畫飛船
forplayerinplayer_group:
ifpygame.sprite.spritecollide(player,asteroid_group,True,None):
player.explode_step=1
explosion_sound.play()
elifplayer.explode_step>0:
ifplayer.explode_step>3:
player_group.remove(player)
iflen(player_group)==0:
return
else:
player.explode(screen)
else:
player.draw(screen)
#--畫子彈
forbulletinbullet_group:
bullet.move()
ifpygame.sprite.spritecollide(bullet,asteroid_group,True,None):
bullet_group.remove(bullet)
ifbullet.player_idx==1:
score_1+=1
else:
score_2+=1
else:
bullet.draw(screen)
#--畫小行星
forasteroidinasteroid_group:
asteroid.move()
asteroid.rotate()
asteroid.draw(screen)
#--顯示分數
score_1_text='玩家一得分:%s'%score_1
score_2_text='玩家二得分:%s'%score_2
text_1=font.render(score_1_text,True,(0,0,255))
text_2=font.render(score_2_text,True,(255,0,0))
screen.blit(text_1,(2,5))
screen.blit(text_2,(2,35))
#--屏幕刷新
pygame.display.update()
clock.tick(60)


'''主函數'''
defmain():
pygame.init()
pygame.font.init()
pygame.mixer.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('飛機大戰——九歌')
num_player=StartInterface(screen,cfg)
ifnum_player==1:
whileTrue:
GamingInterface(num_player=1,screen=screen)
EndInterface(screen,cfg)
else:
whileTrue:
GamingInterface(num_player=2,screen=screen)
EndInterface(screen,cfg)


'''run'''
if__name__=='__main__':
main()

5、打地鼠

源碼分享:


importcfg
importsys
importpygame
importrandom
frommodulesimport*


'''游戲初始化'''
definitGame():
pygame.init()
pygame.mixer.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('打地鼠——九歌')
returnscreen


'''主函數'''
defmain():
#初始化
screen=initGame()
#加載背景音樂和其他音效
pygame.mixer.music.load(cfg.BGM_PATH)
pygame.mixer.music.play(-1)
audios={
'count_down':pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
'hammering':pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
}
#加載字體
font=pygame.font.Font(cfg.FONT_PATH,40)
#加載背景圖片
bg_img=pygame.image.load(cfg.GAME_BG_IMAGEPATH)
#開始界面
startInterface(screen,cfg.GAME_BEGIN_IMAGEPATHS)
#地鼠改變位置的計時
hole_pos=random.choice(cfg.HOLE_POSITIONS)
change_hole_event=pygame.USEREVENT
pygame.time.set_timer(change_hole_event,800)
#地鼠
mole=Mole(cfg.MOLE_IMAGEPATHS,hole_pos)
#錘子
hammer=Hammer(cfg.HAMMER_IMAGEPATHS,(500,250))
#時鐘
clock=pygame.time.Clock()
#分數
your_score=0
flag=False
#初始時間
init_time=pygame.time.get_ticks()
#游戲主循環
whileTrue:
#--游戲時間為60s
time_remain=round((61000-(pygame.time.get_ticks()-init_time))/1000.)
#--游戲時間減少,地鼠變位置速度變快
iftime_remain==40andnotflag:
hole_pos=random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event,650)
flag=True
eliftime_remain==20andflag:
hole_pos=random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event,500)
flag=False
#--倒計時音效
iftime_remain==10:
audios['count_down'].play()
#--游戲結束
iftime_remainbreak
count_down_text=font.render('Time:'+str(time_remain),True,cfg.WHITE)
#--按鍵檢測
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
elifevent.type==pygame.MOUSEMOTION:
hammer.setPosition(pygame.mouse.get_pos())
elifevent.type==pygame.MOUSEBUTTONDOWN:
ifevent.button==1:
hammer.setHammering()
elifevent.type==change_hole_event:
hole_pos=random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
#--碰撞檢測
ifhammer.is_hammeringandnotmole.is_hammer:
is_hammer=pygame.sprite.collide_mask(hammer,mole)
ifis_hammer:
audios['hammering'].play()
mole.setBeHammered()
your_score+=10
#--分數
your_score_text=font.render('Score:'+str(your_score),True,cfg.BROWN)
#--綁定必要的游戲元素到屏幕(注意順序)
screen.blit(bg_img,(0,0))
screen.blit(count_down_text,(875,8))
screen.blit(your_score_text,(800,430))
mole.draw(screen)
hammer.draw(screen)
#--更新
pygame.display.flip()
clock.tick(60)
#讀取最佳分數(try塊避免第一次游戲無.rec文件)
try:
best_score=int(open(cfg.RECORD_PATH).read())
except:
best_score=0
#若當前分數大于最佳分數則更新最佳分數
ifyour_score>best_score:
f=open(cfg.RECORD_PATH,'w')
f.write(str(your_score))
f.close()
#結束界面
score_info={'your_score':your_score,'best_score':best_score}
is_restart=endInterface(screen,cfg.GAME_END_IMAGEPATH,cfg.GAME_AGAIN_IMAGEPATHS,score_info,cfg.FONT_PATH,[cfg.WHITE,cfg.RED],cfg.SCREENSIZE)
returnis_restart


'''run'''
if__name__=='__main__':
whileTrue:
is_restart=main()
ifnotis_restart:
break

6、小恐龍

玩法:上下控制起跳躲避

源碼分享:


importcfg
importsys
importrandom
importpygame
frommodulesimport*


'''main'''
defmain(highest_score):
#游戲初始化
pygame.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('九歌')
#導入所有聲音文件
sounds={}
forkey,valueincfg.AUDIO_PATHS.items():
sounds[key]=pygame.mixer.Sound(value)
#游戲開始界面
GameStartInterface(screen,sounds,cfg)
#定義一些游戲中必要的元素和變量
score=0
score_board=Scoreboard(cfg.IMAGE_PATHS['numbers'],position=(534,15),bg_color=cfg.BACKGROUND_COLOR)
highest_score=highest_score
highest_score_board=Scoreboard(cfg.IMAGE_PATHS['numbers'],position=(435,15),bg_color=cfg.BACKGROUND_COLOR,is_highest=True)
dino=Dinosaur(cfg.IMAGE_PATHS['dino'])
ground=Ground(cfg.IMAGE_PATHS['ground'],position=(0,cfg.SCREENSIZE[1]))
cloud_sprites_group=pygame.sprite.Group()
cactus_sprites_group=pygame.sprite.Group()
ptera_sprites_group=pygame.sprite.Group()
add_obstacle_timer=0
score_timer=0
#游戲主循環
clock=pygame.time.Clock()
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
elifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_SPACEorevent.key==pygame.K_UP:
dino.jump(sounds)
elifevent.key==pygame.K_DOWN:
dino.duck()
elifevent.type==pygame.KEYUPandevent.key==pygame.K_DOWN:
dino.unduck()
screen.fill(cfg.BACKGROUND_COLOR)
#--隨機添加云
iflen(cloud_sprites_group)'cloud'],position=(cfg.SCREENSIZE[0],random.randrange(30,75))))
#--隨機添加仙人掌/飛龍
add_obstacle_timer+=1
ifadd_obstacle_timer>random.randrange(50,150):
add_obstacle_timer=0
random_value=random.randrange(0,10)
ifrandom_value>=5andrandom_value<=?7:
????????????????cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
else:
position_ys=[cfg.SCREENSIZE[1]*0.82,cfg.SCREENSIZE[1]*0.75,cfg.SCREENSIZE[1]*0.60,cfg.SCREENSIZE[1]*0.20]
ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'],position=(600,random.choice(position_ys))))
#--更新游戲元素
dino.update()
ground.update()
cloud_sprites_group.update()
cactus_sprites_group.update()
ptera_sprites_group.update()
score_timer+=1
ifscore_timer>(cfg.FPS//12):
score_timer=0
score+=1
score=min(score,99999)
ifscore>highest_score:
highest_score=score
ifscore%100==0:
sounds['point'].play()
ifscore%1000==0:
ground.speed-=1
foritemincloud_sprites_group:
item.speed-=1
foritemincactus_sprites_group:
item.speed-=1
foriteminptera_sprites_group:
item.speed-=1
#--碰撞檢測
foritemincactus_sprites_group:
ifpygame.sprite.collide_mask(dino,item):
dino.die(sounds)
foriteminptera_sprites_group:
ifpygame.sprite.collide_mask(dino,item):
dino.die(sounds)
#--將游戲元素畫到屏幕上
dino.draw(screen)
ground.draw(screen)
cloud_sprites_group.draw(screen)
cactus_sprites_group.draw(screen)
ptera_sprites_group.draw(screen)
score_board.set(score)
highest_score_board.set(highest_score)
score_board.draw(screen)
highest_score_board.draw(screen)
#--更新屏幕
pygame.display.update()
clock.tick(cfg.FPS)
#--游戲是否結束
ifdino.is_dead:
break
#游戲結束界面
returnGameEndInterface(screen,cfg),highest_score


'''run'''
if__name__=='__main__':
highest_score=0
whileTrue:
flag,highest_score=main(highest_score)
ifnotflag:break

7、消消樂

玩法:三個相連就能消除

c7bba5a4-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importos
importsys
importcfg
importpygame
frommodulesimport*


'''游戲主程序'''
defmain():
pygame.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Gemgem——九歌')
#加載背景音樂
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(cfg.ROOTDIR,"resources/audios/bg.mp3"))
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)
#加載音效
sounds={}
sounds['mismatch']=pygame.mixer.Sound(os.path.join(cfg.ROOTDIR,'resources/audios/badswap.wav'))
sounds['match']=[]
foriinrange(6):
sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR,'resources/audios/match%s.wav'%i)))
#加載字體
font=pygame.font.Font(os.path.join(cfg.ROOTDIR,'resources/font/font.TTF'),25)
#圖片加載
gem_imgs=[]
foriinrange(1,8):
gem_imgs.append(os.path.join(cfg.ROOTDIR,'resources/images/gem%s.png'%i))
#主循環
game=gemGame(screen,sounds,font,gem_imgs,cfg)
whileTrue:
score=game.start()
flag=False
#一輪游戲結束后玩家選擇重玩或者退出
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUITor(event.type==pygame.KEYUPandevent.key==pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elifevent.type==pygame.KEYUPandevent.key==pygame.K_r:
flag=True
ifflag:
break
screen.fill((135,206,235))
text0='Finalscore:%s'%score
text1='Presstorestartthegame.'
text2='Presstoquitthegame.'
y=150
foridx,textinenumerate([text0,text1,text2]):
text_render=font.render(text,1,(85,65,0))
rect=text_render.get_rect()
ifidx==0:
rect.left,rect.top=(212,y)
elifidx==1:
rect.left,rect.top=(122.5,y)
else:
rect.left,rect.top=(126.5,y)
y+=100
screen.blit(text_render,rect)
pygame.display.update()
game.reset()


'''run'''
if__name__=='__main__':
main()

8、俄羅斯方塊

玩法:童年經典,普通模式沒啥意思,小時候我們都是玩加速的。

c7e0ebac-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importos
importsys
importrandom
frommodulesimport*
fromPyQt5.QtGuiimport*
fromPyQt5.QtCoreimport*
fromPyQt5.QtWidgetsimport*


'''定義俄羅斯方塊游戲類'''
classTetrisGame(QMainWindow):
def__init__(self,parent=None):
super(TetrisGame,self).__init__(parent)
#是否暫停ing
self.is_paused=False
#是否開始ing
self.is_started=False
self.initUI()
'''界面初始化'''
definitUI(self):
#icon
self.setWindowIcon(QIcon(os.path.join(os.getcwd(),'resources/icon.jpg')))
#塊大小
self.grid_size=22
#游戲幀率
self.fps=200
self.timer=QBasicTimer()
#焦點
self.setFocusPolicy(Qt.StrongFocus)
#水平布局
layout_horizontal=QHBoxLayout()
self.inner_board=InnerBoard()
self.external_board=ExternalBoard(self,self.grid_size,self.inner_board)
layout_horizontal.addWidget(self.external_board)
self.side_panel=SidePanel(self,self.grid_size,self.inner_board)
layout_horizontal.addWidget(self.side_panel)
self.status_bar=self.statusBar()
self.external_board.score_signal[str].connect(self.status_bar.showMessage)
self.start()
self.center()
self.setWindowTitle('Tetris——九歌')
self.show()
self.setFixedSize(self.external_board.width()+self.side_panel.width(),self.side_panel.height()+self.status_bar.height())
'''游戲界面移動到屏幕中間'''
defcenter(self):
screen=QDesktopWidget().screenGeometry()
size=self.geometry()
self.move((screen.width()-size.width())//2,(screen.height()-size.height())//2)
'''更新界面'''
defupdateWindow(self):
self.external_board.updateData()
self.side_panel.updateData()
self.update()
'''開始'''
defstart(self):
ifself.is_started:
return
self.is_started=True
self.inner_board.createNewTetris()
self.timer.start(self.fps,self)
'''暫停/不暫停'''
defpause(self):
ifnotself.is_started:
return
self.is_paused=notself.is_paused
ifself.is_paused:
self.timer.stop()
self.external_board.score_signal.emit('Paused')
else:
self.timer.start(self.fps,self)
self.updateWindow()
'''計時器事件'''
deftimerEvent(self,event):
ifevent.timerId()==self.timer.timerId():
removed_lines=self.inner_board.moveDown()
self.external_board.score+=removed_lines
self.updateWindow()
else:
super(TetrisGame,self).timerEvent(event)
'''按鍵事件'''
defkeyPressEvent(self,event):
ifnotself.is_startedorself.inner_board.current_tetris==tetrisShape().shape_empty:
super(TetrisGame,self).keyPressEvent(event)
return
key=event.key()
#P鍵暫停
ifkey==Qt.Key_P:
self.pause()
return
ifself.is_paused:
return
#向左
elifkey==Qt.Key_Left:
self.inner_board.moveLeft()
#向右
elifkey==Qt.Key_Right:
self.inner_board.moveRight()
#旋轉
elifkey==Qt.Key_Up:
self.inner_board.rotateAnticlockwise()
#快速墜落
elifkey==Qt.Key_Space:
self.external_board.score+=self.inner_board.dropDown()
else:
super(TetrisGame,self).keyPressEvent(event)
self.updateWindow()


'''run'''
if__name__=='__main__':
app=QApplication([])
tetris=TetrisGame()
sys.exit(app.exec_())

9、貪吃蛇

玩法:童年經典,普通魔術也沒啥意思,小時候玩的也是加速的。

源碼分享:


importcfg
importsys
importpygame
frommodulesimport*


'''主函數'''
defmain(cfg):
#游戲初始化
pygame.init()
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('GreedySnake——九歌')
clock=pygame.time.Clock()
#播放背景音樂
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1)
#游戲主循環
snake=Snake(cfg)
apple=Apple(cfg,snake.coords)
score=0
whileTrue:
screen.fill(cfg.BLACK)
#--按鍵檢測
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
elifevent.type==pygame.KEYDOWN:
ifevent.keyin[pygame.K_UP,pygame.K_DOWN,pygame.K_LEFT,pygame.K_RIGHT]:
snake.setDirection({pygame.K_UP:'up',pygame.K_DOWN:'down',pygame.K_LEFT:'left',pygame.K_RIGHT:'right'}[event.key])
#--更新貪吃蛇和食物
ifsnake.update(apple):
apple=Apple(cfg,snake.coords)
score+=1
#--判斷游戲是否結束
ifsnake.isgameover:break
#--顯示游戲里必要的元素
drawGameGrid(cfg,screen)
snake.draw(screen)
apple.draw(screen)
showScore(cfg,score,screen)
#--屏幕更新
pygame.display.update()
clock.tick(cfg.FPS)
returnendInterface(screen,cfg)


'''run'''
if__name__=='__main__':
whileTrue:
ifnotmain(cfg):
break

10、24點小游戲

玩法:通過加減乘除操作,小學生都沒問題的。

c818f7a4-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importos
importsys
importpygame
fromcfgimport*
frommodulesimport*
fromfractionsimportFraction


'''檢查控件是否被點擊'''
defcheckClicked(group,mouse_pos,group_type='NUMBER'):
selected=[]
#數字卡片/運算符卡片
ifgroup_type==GROUPTYPES[0]orgroup_type==GROUPTYPES[1]:
max_selected=2ifgroup_type==GROUPTYPES[0]else1
num_selected=0
foreachingroup:
num_selected+=int(each.is_selected)
foreachingroup:
ifeach.rect.collidepoint(mouse_pos):
ifeach.is_selected:
each.is_selected=noteach.is_selected
num_selected-=1
each.select_order=None
else:
ifnum_selectedifeach.is_selected:
selected.append(each.attribute)
#按鈕卡片
elifgroup_type==GROUPTYPES[2]:
foreachingroup:
ifeach.rect.collidepoint(mouse_pos):
each.is_selected=True
selected.append(each.attribute)
#拋出異常
else:
raiseValueError('checkClicked.group_typeunsupport%s,expect%s,%sor%s...'%(group_type,*GROUPTYPES))
returnselected


'''獲取數字精靈組'''
defgetNumberSpritesGroup(numbers):
number_sprites_group=pygame.sprite.Group()
foridx,numberinenumerate(numbers):
args=(*NUMBERCARD_POSITIONS[idx],str(number),NUMBERFONT,NUMBERFONT_COLORS,NUMBERCARD_COLORS,str(number))
number_sprites_group.add(Card(*args))
returnnumber_sprites_group


'''獲取運算符精靈組'''
defgetOperatorSpritesGroup(operators):
operator_sprites_group=pygame.sprite.Group()
foridx,operatorinenumerate(operators):
args=(*OPERATORCARD_POSITIONS[idx],str(operator),OPERATORFONT,OPREATORFONT_COLORS,OPERATORCARD_COLORS,str(operator))
operator_sprites_group.add(Card(*args))
returnoperator_sprites_group


'''獲取按鈕精靈組'''
defgetButtonSpritesGroup(buttons):
button_sprites_group=pygame.sprite.Group()
foridx,buttoninenumerate(buttons):
args=(*BUTTONCARD_POSITIONS[idx],str(button),BUTTONFONT,BUTTONFONT_COLORS,BUTTONCARD_COLORS,str(button))
button_sprites_group.add(Button(*args))
returnbutton_sprites_group


'''計算'''
defcalculate(number1,number2,operator):
operator_map={'+':'+','-':'-','×':'*','÷':'/'}
try:
result=str(eval(number1+operator_map[operator]+number2))
returnresultif'.'notinresultelsestr(Fraction(number1+operator_map[operator]+number2))
except:
returnNone


'''在屏幕上顯示信息'''
defshowInfo(text,screen):
rect=pygame.Rect(200,180,400,200)
pygame.draw.rect(screen,PAPAYAWHIP,rect)
font=pygame.font.Font(FONTPATH,40)
text_render=font.render(text,True,BLACK)
font_size=font.size(text)
screen.blit(text_render,(rect.x+(rect.width-font_size[0])/2,rect.y+(rect.height-font_size[1])/2))


'''主函數'''
defmain():
#初始化,導入必要的游戲素材
pygame.init()
pygame.mixer.init()
screen=pygame.display.set_mode(SCREENSIZE)
pygame.display.set_caption('24point——九歌')
win_sound=pygame.mixer.Sound(AUDIOWINPATH)
lose_sound=pygame.mixer.Sound(AUDIOLOSEPATH)
warn_sound=pygame.mixer.Sound(AUDIOWARNPATH)
pygame.mixer.music.load(BGMPATH)
pygame.mixer.music.play(-1,0.0)
#24點游戲生成器
game24_gen=game24Generator()
game24_gen.generate()
#精靈組
#--數字
number_sprites_group=getNumberSpritesGroup(game24_gen.numbers_now)
#--運算符
operator_sprites_group=getOperatorSpritesGroup(OPREATORS)
#--按鈕
button_sprites_group=getButtonSpritesGroup(BUTTONS)
#游戲主循環
clock=pygame.time.Clock()
selected_numbers=[]
selected_operators=[]
selected_buttons=[]
is_win=False
whileTrue:
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit(-1)
elifevent.type==pygame.MOUSEBUTTONUP:
mouse_pos=pygame.mouse.get_pos()
selected_numbers=checkClicked(number_sprites_group,mouse_pos,'NUMBER')
selected_operators=checkClicked(operator_sprites_group,mouse_pos,'OPREATOR')
selected_buttons=checkClicked(button_sprites_group,mouse_pos,'BUTTON')
screen.fill(AZURE)
#更新數字
iflen(selected_numbers)==2andlen(selected_operators)==1:
noselected_numbers=[]
foreachinnumber_sprites_group:
ifeach.is_selected:
ifeach.select_order=='1':
selected_number1=each.attribute
elifeach.select_order=='2':
selected_number2=each.attribute
else:
raiseValueError('Unknowselect_order%s,expect1or2...'%each.select_order)
else:
noselected_numbers.append(each.attribute)
each.is_selected=False
foreachinoperator_sprites_group:
each.is_selected=False
result=calculate(selected_number1,selected_number2,*selected_operators)
ifresultisnotNone:
game24_gen.numbers_now=noselected_numbers+[result]
is_win=game24_gen.check()
ifis_win:
win_sound.play()
ifnotis_winandlen(game24_gen.numbers_now)==1:
lose_sound.play()
else:
warn_sound.play()
selected_numbers=[]
selected_operators=[]
number_sprites_group=getNumberSpritesGroup(game24_gen.numbers_now)
#精靈都畫到screen上
foreachinnumber_sprites_group:
each.draw(screen,pygame.mouse.get_pos())
foreachinoperator_sprites_group:
each.draw(screen,pygame.mouse.get_pos())
foreachinbutton_sprites_group:
ifselected_buttonsandselected_buttons[0]in['RESET','NEXT']:
is_win=False
ifselected_buttonsandeach.attribute==selected_buttons[0]:
each.is_selected=False
number_sprites_group=each.do(game24_gen,getNumberSpritesGroup,number_sprites_group,button_sprites_group)
selected_buttons=[]
each.draw(screen,pygame.mouse.get_pos())
#游戲勝利
ifis_win:
showInfo('Congratulations',screen)
#游戲失敗
ifnotis_winandlen(game24_gen.numbers_now)==1:
showInfo('GameOver',screen)
pygame.display.flip()
clock.tick(30)


'''run'''
if__name__=='__main__':
main()

11、平衡木

玩法:也是小時候的經典游戲,控制左右就行,到后面才有一點點難度。

源碼分享:


importcfg
frommodulesimportbreakoutClone


'''主函數'''
defmain():
game=breakoutClone(cfg)
game.run()


'''run'''
if__name__=='__main__':
main()

12、外星人入侵

玩法:這讓我想起了魂斗羅那第幾關的boss,有點類似,不過魂斗羅那個難度肯定高點。

c84334f6-025f-11ed-ba43-dac502259ad0.gif

源碼分享:


importos
importsys
importcfg
importrandom
importpygame
frommodulesimport*


'''開始游戲'''
defstartGame(screen):
clock=pygame.time.Clock()
#加載字體
font=pygame.font.SysFont('arial',18)
ifnotos.path.isfile('score'):
f=open('score','w')
f.write('0')
f.close()
withopen('score','r')asf:
highest_score=int(f.read().strip())
#敵方
enemies_group=pygame.sprite.Group()
foriinrange(55):
ifi'small',i,cfg.WHITE,cfg.WHITE)
elifi'medium',i,cfg.WHITE,cfg.WHITE)
else:
enemy=enemySprite('large',i,cfg.WHITE,cfg.WHITE)
enemy.rect.x=85+(i%11)*50
enemy.rect.y=120+(i//11)*45
enemies_group.add(enemy)
boomed_enemies_group=pygame.sprite.Group()
en_bullets_group=pygame.sprite.Group()
ufo=ufoSprite(color=cfg.RED)
#我方
myaircraft=aircraftSprite(color=cfg.GREEN,bullet_color=cfg.WHITE)
my_bullets_group=pygame.sprite.Group()
#用于控制敵方位置更新
#--移動一行
enemy_move_count=24
enemy_move_interval=24
enemy_move_flag=False
#--改變移動方向(改變方向的同時集體下降一次)
enemy_change_direction_count=0
enemy_change_direction_interval=60
enemy_need_down=False
enemy_move_right=True
enemy_need_move_row=6
enemy_max_row=5
#用于控制敵方發射子彈
enemy_shot_interval=100
enemy_shot_count=0
enemy_shot_flag=False
#游戲進行中
running=True
is_win=False
#主循環
whilerunning:
screen.fill(cfg.BLACK)
foreventinpygame.event.get():
#--點右上角的X或者按Esc鍵退出游戲
ifevent.type==pygame.QUIT:
pygame.quit()
sys.exit()
ifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_ESCAPE:
pygame.quit()
sys.exit()
#--射擊
ifevent.type==pygame.MOUSEBUTTONDOWN:
my_bullet=myaircraft.shot()
ifmy_bullet:
my_bullets_group.add(my_bullet)
#--我方子彈與敵方/UFO碰撞檢測
forenemyinenemies_group:
ifpygame.sprite.spritecollide(enemy,my_bullets_group,True,None):
boomed_enemies_group.add(enemy)
enemies_group.remove(enemy)
myaircraft.score+=enemy.reward
ifpygame.sprite.spritecollide(ufo,my_bullets_group,True,None):
ufo.is_dead=True
myaircraft.score+=ufo.reward
#--更新并畫敵方
#----敵方子彈
enemy_shot_count+=1
ifenemy_shot_count>enemy_shot_interval:
enemy_shot_flag=True
enemies_survive_list=[enemy.numberforenemyinenemies_group]
shot_number=random.choice(enemies_survive_list)
enemy_shot_count=0
#----敵方移動
enemy_move_count+=1
ifenemy_move_count>enemy_move_interval:
enemy_move_count=0
enemy_move_flag=True
enemy_need_move_row-=1
ifenemy_need_move_row==0:
enemy_need_move_row=enemy_max_row
enemy_change_direction_count+=1
ifenemy_change_direction_count>enemy_change_direction_interval:
enemy_change_direction_count=1
enemy_move_right=notenemy_move_right
enemy_need_down=True
#----每次下降提高移動和射擊速度
enemy_move_interval=max(15,enemy_move_interval-3)
enemy_shot_interval=max(50,enemy_move_interval-10)
#----遍歷更新
forenemyinenemies_group:
ifenemy_shot_flag:
ifenemy.number==shot_number:
en_bullet=enemy.shot()
en_bullets_group.add(en_bullet)
ifenemy_move_flag:
ifenemy.numberinrange((enemy_need_move_row-1)*11,enemy_need_move_row*11):
ifenemy_move_right:
enemy.update('right',cfg.SCREENSIZE[1])
else:
enemy.update('left',cfg.SCREENSIZE[1])
else:
enemy.update(None,cfg.SCREENSIZE[1])
ifenemy_need_down:
ifenemy.update('down',cfg.SCREENSIZE[1]):
running=False
is_win=False
enemy.change_count-=1
enemy.draw(screen)
enemy_move_flag=False
enemy_need_down=False
enemy_shot_flag=False
#----敵方爆炸特效
forboomed_enemyinboomed_enemies_group:
ifboomed_enemy.boom(screen):
boomed_enemies_group.remove(boomed_enemy)
delboomed_enemy
#--敵方子彈與我方飛船碰撞檢測
ifnotmyaircraft.one_dead:
ifpygame.sprite.spritecollide(myaircraft,en_bullets_group,True,None):
myaircraft.one_dead=True
ifmyaircraft.one_dead:
ifmyaircraft.boom(screen):
myaircraft.resetBoom()
myaircraft.num_life-=1
ifmyaircraft.num_lifeelse:
#----更新飛船
myaircraft.update(cfg.SCREENSIZE[0])
#----畫飛船
myaircraft.draw(screen)
if(notufo.has_boomed)and(ufo.is_dead):
ifufo.boom(screen):
ufo.has_boomed=True
else:
#----更新UFO
ufo.update(cfg.SCREENSIZE[0])
#----畫UFO
ufo.draw(screen)
#--畫我方飛船子彈
forbulletinmy_bullets_group:
ifbullet.update():
my_bullets_group.remove(bullet)
delbullet
else:
bullet.draw(screen)
#--畫敵方子彈
forbulletinen_bullets_group:
ifbullet.update(cfg.SCREENSIZE[1]):
en_bullets_group.remove(bullet)
delbullet
else:
bullet.draw(screen)
ifmyaircraft.score>highest_score:
highest_score=myaircraft.score
#--得分每增加2000我方飛船增加一條生命
if(myaircraft.score%2000==0)and(myaircraft.score>0)and(myaircraft.score!=myaircraft.old_score):
myaircraft.old_score=myaircraft.score
myaircraft.num_life=min(myaircraft.num_life+1,myaircraft.max_num_life)
#--敵人都死光了的話就勝利了
iflen(enemies_group)#--顯示文字
#----當前得分
showText(screen,'SCORE:',cfg.WHITE,font,200,8)
showText(screen,str(myaircraft.score),cfg.WHITE,font,200,24)
#----敵人數量
showText(screen,'ENEMY:',cfg.WHITE,font,370,8)
showText(screen,str(len(enemies_group)),cfg.WHITE,font,370,24)
#----歷史最高分
showText(screen,'HIGHEST:',cfg.WHITE,font,540,8)
showText(screen,str(highest_score),cfg.WHITE,font,540,24)
#----FPS
showText(screen,'FPS:'+str(int(clock.get_fps())),cfg.RED,font,8,8)
#--顯示剩余生命值
showLife(screen,myaircraft.num_life,cfg.GREEN)
pygame.display.update()
clock.tick(cfg.FPS)
withopen('score','w')asf:
f.write(str(highest_score))
returnis_win


'''主函數'''
defmain():
#初始化
pygame.init()
pygame.display.set_caption('外星人入侵——九歌')
screen=pygame.display.set_mode(cfg.SCREENSIZE)
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
whileTrue:
is_win=startGame(screen)
endInterface(screen,cfg.BLACK,is_win)


'''run'''
if__name__=='__main__':
main()

13、井字棋888

玩法:我打賭大家在課堂上肯定玩過這個,想想當年和同桌玩這個廢了好幾本本子。

源碼分享

fromtkinterimport*
importtkinter.messageboxasmsg

root=Tk()
root.title('TIC-TAC-TOE---ProjectGurukul')
#labels
Label(root,text="player1:X",font="times15").grid(row=0,column=1)
Label(root,text="player2:O",font="times15").grid(row=0,column=2)

digits=[1,2,3,4,5,6,7,8,9]

#forplayer1sign=Xandforplayer2sign=Y
mark=''

#countingtheno.ofclick
count=0

panels=["panel"]*10


defwin(panels,sign):
return((panels[1]==panels[2]==panels[3]==sign)
or(panels[1]==panels[4]==panels[7]==sign)
or(panels[1]==panels[5]==panels[9]==sign)
or(panels[2]==panels[5]==panels[8]==sign)
or(panels[3]==panels[6]==panels[9]==sign)
or(panels[3]==panels[5]==panels[7]==sign)
or(panels[4]==panels[5]==panels[6]==sign)
or(panels[7]==panels[8]==panels[9]==sign))


defchecker(digit):
globalcount,mark,digits

#Checkwhichbuttonclicked

ifdigit==1anddigitindigits:
digits.remove(digit)
##player1willplayifthevalueofcountisevenandforoddplayer2willplay
ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button1.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==2anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button2.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==3anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button3.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==4anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button4.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==5anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button5.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==6anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button6.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==7anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button7.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==8anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button8.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

ifdigit==9anddigitindigits:
digits.remove(digit)

ifcount%2==0:
mark='X'
panels[digit]=mark
elifcount%2!=0:
mark='O'
panels[digit]=mark

button9.config(text=mark)
count=count+1
sign=mark

if(win(panels,sign)andsign=='X'):
msg.showinfo("Result","Player1wins")
root.destroy()
elif(win(panels,sign)andsign=='O'):
msg.showinfo("Result","Player2wins")
root.destroy()

###ifcountisgreaterthen8thenthematchhasbeentied
if(count>8andwin(panels,'X')==Falseandwin(panels,'O')==False):
msg.showinfo("Result","MatchTied")
root.destroy()


####definebuttons
button1=Button(root,width=15,font=('Times16bold'),height=7,command=lambda:checker(1))
button1.grid(row=1,column=1)
button2=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(2))
button2.grid(row=1,column=2)
button3=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(3))
button3.grid(row=1,column=3)
button4=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(4))
button4.grid(row=2,column=1)
button5=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(5))
button5.grid(row=2,column=2)
button6=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(6))
button6.grid(row=2,column=3)
button7=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(7))
button7.grid(row=3,column=1)
button8=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(8))
button8.grid(row=3,column=2)
button9=Button(root,width=15,height=7,font=('Times16bold'),command=lambda:checker(9))
button9.grid(row=3,column=3)

root.mainloop()



審核編輯:劉清


聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 編程
    +關注

    關注

    88

    文章

    3614

    瀏覽量

    93686
  • python
    +關注

    關注

    56

    文章

    4792

    瀏覽量

    84628

原文標題:用 Python 制作 13 個小游戲,邊玩邊學!(含源碼)

文章出處:【微信號:LinuxHub,微信公眾號:Linux愛好者】歡迎添加關注!文章轉載請注明出處。

收藏 人收藏

    評論

    相關推薦

    通過JTAG接口對MSP430進行編程

    電子發燒友網站提供《通過JTAG接口對MSP430進行編程.pdf》資料免費下載
    發表于 10-31 09:31 ?0次下載
    <b class='flag-5'>通過</b>JTAG接口對MSP430進行<b class='flag-5'>編程</b>

    如何在Cadence的EMX仿真中精準設置長PORT

    請問在Cadence的EMX仿真里,如果需要在一個較長的邊打PORT,需要怎么設置會仿真比較精準?像這樣子直接吸附一個上去可以嗎?
    的頭像 發表于 10-23 10:27 ?613次閱讀
    如何在Cadence的EMX仿真中精準設置長<b class='flag-5'>邊</b>PORT

    LDR6028:一款讓智能設備“用”的PD芯片

    的協商過程不僅確保了充電的高效性,還提高了充電過程的安全性。通過其高效的充電與數據傳輸能力以及創新的OTG功能,LDR6028為用戶帶來了前所未有的便捷體驗,并推動了智能設備產業的升級和發展。LDR6028的廣泛應用,不僅限于充電與數據傳輸,還通過其創新的OTG功能,實現
    的頭像 發表于 09-09 12:34 ?498次閱讀
    LDR6028:一款讓智能設備“<b class='flag-5'>邊</b>充<b class='flag-5'>邊</b>用”的PD芯片

    坡監測設備:保護坡安全的利器

    坡監測設備以其高精度、實時監測、長時間穩定工作等優勢,在坡安全監測領域發揮著重要的作用,是現代社會防災減災、保障坡工程安全的重要技術手段。隨著技術的不斷進步,坡監測設備將更加智
    的頭像 發表于 08-19 16:45 ?333次閱讀

    基于 FPGA 的飛機大戰游戲系統設計

    游戲四個選項。開始游戲后,玩家可以用游戲手柄方便的控制飛機在屏幕上向任意方向移動,通過躲避子彈和射擊敵機得分,在屏幕左上角可以看到當前生命和得分。 1.2 應用領域最近的一些復古
    發表于 07-24 20:03

    請問為什么庫函數頭文件和寄存器頭文件不可共用?

    我現在學著庫函數編程,我想庫函數寄存器,例如做完庫函數編程后我想把CLK_HSIPres
    發表于 04-28 06:22

    AI坡監測識別攝像機

    AI坡監測識別攝像機是一種利用人工智能技術進行坡監測的智能設備,其作用是及時監測坡變化并識別潛在的滑坡、崩塌等危險情況,以提供及時預警和采取必要的安全措施。這種攝像機通過高清攝像
    的頭像 發表于 04-19 10:28 ?476次閱讀
    AI<b class='flag-5'>邊</b>坡監測識別攝像機

    OpenHarmony南向開發實例:【游戲手柄】

    基于TS擴展的聲明式開發范式編程語言,以及OpenHarmony的分布式能力實現的一個手柄游戲
    的頭像 發表于 04-17 10:21 ?749次閱讀
    OpenHarmony南向開發實例:【<b class='flag-5'>游戲</b>手柄】

    通過51單片機實現俄羅斯方塊游戲編程,Proteus仿真,論文,LCD12864液晶

    )、游戲計時等內容。設計獲取,關注公眾號:交院小智。 玩家可以通過四個按鍵,對方塊進行變換、左移、右移和下移。當方塊填滿一行或多行時,消行得分。下圖顯示,游戲已運行1分47秒,玩家得分為2分。 當
    發表于 04-03 19:59

    PCBA為什么要設計工藝

    PCBA工藝也叫工作,是為了SMT加工時留出軌道傳輸位置、放置拼版Mark點而設置的長條形空白板邊。
    發表于 03-25 14:13 ?788次閱讀

    PCBA為什么要設計工藝?設計工藝有什么好處嗎?

    PCBA設計師們在設計線路板的時候,往往會預留工藝。這么做得到原因大家知道是為什么嗎?設計工藝有什么好處嗎?今天給大家講解一下PCBA為什么要設計工藝
    的頭像 發表于 03-22 11:45 ?1376次閱讀

    SEGGER通過增加Microchip的AVR Dx系列擴展Flasher在線編程的支持芯片種類

    SEGGER通過增加Microchip的AVR Dx系列,擴展了Flasher在線編程的支持芯片種類,為AVR芯片提供了增強的編程能力。
    的頭像 發表于 03-19 17:24 ?605次閱讀

    2024 ChinaJoy全新增設硬核游戲主題展區,以主機及PC游戲為主

    為了增強ChinaJoy的游戲特色,更好地迎合廣大硬核游戲愛好者的需求,本屆ChinaJoy計劃首設硬核游戲主題展區。專區將基于游戲類型設定專屬場地,
    的頭像 發表于 02-20 09:52 ?611次閱讀

    電機驅動系統的構成及特點

    電機驅動系統是一種電動汽車的驅動方式,它通過將電動機直接安裝在車輪上,實現對車輛動力的直接控制。與傳統的中央電機驅動系統相比,輪電機驅動系統具有更高的靈活性和效率。本文將對輪
    的頭像 發表于 01-05 17:55 ?2411次閱讀
    輪<b class='flag-5'>邊</b>電機驅動系統的構成及特點

    壓線鉗四形與六形的特征、性質以及應用

    在幾何中,四形和六形是兩個常見的多邊形形狀。它們在不同的方面具有不同的特點和用途。本文將比較壓線鉗四形和六形的特征、性質以及應用,
    的頭像 發表于 12-28 17:05 ?5972次閱讀
    主站蜘蛛池模板: 亚洲国产成人精品无码区99| 成人久久欧美日韩一区二区三区| 国产精品久久大陆| 男人插女人动态图| 亚洲欧洲免费三级网站| 动漫护士被乳羞羞漫| 花蝴蝶在线高清视频观看免费播放| 日本人HD18HD18| 97久久伊人精品影院| 黃色带三级a级| 四虎免费影院| 别停好爽好深好大好舒服视频| 久久热这里面只有精品| 亚洲成人国产| 国产超嫩一线天在线播放| 飘雪在线观看免费高清完整版韩国| 一级毛片西西人体44rt高清| 国产精品一区二区三区四区五区 | 日本精品卡一卡2卡3卡四卡三卡 | a视频在线观看免费| 久久强奷乱码老熟女| 亚洲国产精品久久又爽黄A片| 国产 交换 丝雨 巅峰| 欧洲xxxxx| 97精品国产亚洲AV超碰| 久久人人玩人妻潮喷内射人人| 亚洲精品国偷拍自产在线| 国产精品久久人妻无码网站一区L| 青青涩射射| av无码在线日本天堂| 美女拔萝卜| 最新无码国产在线视频| 久久精品国产男包| 亚洲一区电影在线观看| 国偷自产AV一区二区三区健身房| 无码一区国产欧美在线资源| 公和熄洗澡三级中文字幕| 日韩AV爽爽爽久久久久久| 本庄优花aⅴ全部在线影片 | 羽月希被黑人吃奶dasd585| 精品视频久久久久|