当前位置:网站首页>[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)
[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)
2022-06-27 15:53:00 【- Salut! Chestnut!】
Préface
- Salut.!Je suis l'élève de Chestnut..Je ne l'ai pas vu depuis longtemps.!Je suis de retour.~

Qu'est - ce que j'écris pour vous aujourd'hui??!Hé! Hé!,Je n'ai pas écrit de code depuis si longtemps.,Les mains ne savent même pas taper.,Le Code ne frappe même pas.
C'est,Laisse - moi prendre mon temps.!Un peu de simplicité.(En fait, je n'ai aucune idée.,La dernière fois que j'ai écrit le dernier jeu de sniper invincible
C'est une petite adaptation du Code.,Paresseux,Parce que je ne sais pas quoi écrire.,Ne me frappe pas.jpg)
Quand je serai inspiré, je vous écrirai.,On s'entraîne.!Source d'amour,Peut - être la prochaine fois.!
Aujourd'hui, je vais vous apprendre à écrire un petit jeu simple.:《Mange tout.》Commençons tout de suite.
Tous les articles+ Le code source est à la fin de l'article public haoPrends - le.!

Texte
Cet article est basé surpygameÉcrivez un petit jeu avec une interface simple.!
Un.、Environnement opérationnel
1)Installation environnementale Python3、 Pycharm 、tkinter、PygameLa partie module n'est pas affichée avec le module lui - même..
(Installer le paquet si nécessaire、Code d'activation, etc. direct Je peux installer des réponses à vos questions en privé. ~)
Installation de bibliothèques tierces:pip install pygame Ou Avec source miroir pip install -i
https://pypi.douban.com/simple/ +Nom du module2)Matériel(Photos: La nourriture et les gens qui mangent )

J'ai l'impression que la nourriture ne correspond pas à la beauté d'une fille. ,Ha ha ha, Juste une seconde. , Vous pouvez changer les photos. !
2.、Procédure principale
import pygame,os,random
from pygame.locals import *
from pygame.sprite import *
def load_image(name):
fullname=os.path.join(os.path.join(os.path.split(os.path.abspath(__file__))[0],"filedata"),name)
image=pygame.image.load(fullname)
return image
def load_sound(name):
fullname=os.path.join(os.path.join(os.path.split(os.path.abspath(__file__))[0],"filedata"),name)
sound=pygame.mixer.Sound(fullname)
return sound
class Tip(Sprite):
def __init__(self,screen,fontrender,waitticks,pos):
super(Tip,self).__init__()
self.screen=screen
self.image=fontrender
self.rect=self.image.get_rect()
self.rates=0
self.waitticks=waitticks
self.rect.center=pos
def update(self):
self.rates+=1
if self.rates>=self.waitticks:
self.kill()
class Surface:
def __init__(self,screen):
self.screen=screen
self.image=load_image("eatingface.png")
self.rect=self.image.get_rect()
self.rect.center=self.screen.get_rect().center
self.speed=3.7
self.caneat=20
self.eat=self.caneat
self.moveUp=False
self.moveDown=False
self.moveLeft=False
self.moveRight=False
self.faceatleft=False
self.punch=0
def update(self):
if self.punch==0:
if self.moveUp and self.rect.top>0:
self.rect.centery-=self.speed
if self.moveDown and self.rect.bottom<HEIGHT:
self.rect.centery+=self.speed
if self.moveLeft and self.rect.left>0:
if not self.faceatleft:
self.faceatleft=True
self.image=pygame.transform.flip(self.image,True,False)
self.rect.centerx-=self.speed
if self.moveRight and self.rect.right<WIDTH:
if self.faceatleft:
self.faceatleft=False
self.image=pygame.transform.flip(self.image,True,False)
self.rect.centerx+=self.speed
else:
self.punched()
def blit(self):
self.screen.blit(self.image,self.rect)
def punched(self):
self.punch+=1
if self.punch>60:
self.punch=0
def eats(self,num):
self.eat+=num
if self.eat>=100:
self.eat=100
return "True"
elif self.eat<=0:
self.eat=0
return "False"
return "None"
def reset(self):
self.image=load_image("eatingface.png")
self.rect=self.image.get_rect()
self.rect.center=self.screen.get_rect().center
self.speed=3.7
self.eat=self.caneat
self.moveUp=False
self.moveDown=False
self.moveLeft=False
self.moveRight=False
self.faceatleft=False
self.punch=0
class Food(Sprite):
def __init__(self,screen,surface,tips,gameFont):
super(Food,self).__init__()
self.screen=screen
self.surface=surface
self.tips=tips
self.gameFont=gameFont
self.screenrect=self.screen.get_rect()
self.image=load_image("eatingfood.png")
self.rect=self.image.get_rect()
self.rectat=random.choice(["top","left","right","bottom"])
self.xspeed=round(random.uniform(1,2),2)
self.yspeed=round(random.uniform(1,2),2)
if self.rectat=="top":
self.rect.center=(random.randint(0,WIDTH),0)
elif self.rectat=="bottom":
self.rect.center=(random.randint(0,WIDTH),HEIGHT)
self.yspeed=-self.yspeed
elif self.rectat=="left":
self.rect.center=(0,random.randint(0,HEIGHT))
elif self.rectat=="right":
self.xspeed=-self.xspeed
self.rect.center=(WIDTH,random.randint(0,HEIGHT))
def update(self):
global toohungry,isfull
if self.surface.faceatleft:
if self.rect.left<self.surface.rect.left<=self.rect.right:
if self.surface.rect.top<self.rect.top<self.surface.rect.bottom or self.surface.rect.bottom>self.rect.bottom>self.surface.rect.top:
self.kill()
if self.surface.eats(2)=="True":
isfull=True
return
else:
if self.rect.right>self.surface.rect.right>=self.rect.left:
if self.surface.rect.top<self.rect.top<self.surface.rect.bottom or self.surface.rect.bottom>self.rect.bottom>self.surface.rect.top:
self.kill()
if self.surface.eats(2)=="True":
isfull=True
return
if collide_rect(self,self.surface):
self.surface.punched()
if self.surface.eats(-1)=="False":
toohungry=True
return
self.tips.add(Tip(self.screen,self.gameFont.render("Dizzy!",True,(255,255,255)),
60,self.surface.rect.center))
self.away()
self.rect.centerx+=self.xspeed
self.rect.centery+=self.yspeed
if self.rect.top>self.screenrect.height or self.rect.bottom<0:
self.kill()
elif self.rect.left>self.screenrect.width or self.rect.right<0:
self.kill()
def away(self):
self.xspeed=-self.xspeed
self.yspeed=-self.yspeed
WIDTH=700
HEIGHT=600
toohungry=False
isfull=False
def initmain():
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Eater")
gameFont=pygame.font.SysFont("Arial",26,True)
fpstime=pygame.time.Clock()
surface=Surface(screen)
foods=Group()
tips=Group()
def mainit():
global toohungry,isfull
foods.empty()
tips.empty()
surface.reset()
rates=0
toohungry=False
isfull=False
while ((not isfull) and (not toohungry)):
fpstime.tick(100)
screen.fill((0,255,0))
screen.blit(gameFont.render("Full "+str(surface.eat)+"%",True,(0,0,0)),(2,2))
rates+=1
if rates%50==0:
foods.add(Food(screen,surface,tips,gameFont))
foods.draw(screen)
foods.update()
surface.blit()
surface.update()
tips.draw(screen)
tips.update()
for event in pygame.event.get():
if event.type==QUIT:
toohungry=True
isfull=True
elif event.type==KEYDOWN:
if event.key==K_RIGHT:
surface.moveRight=True
elif event.key==K_LEFT:
surface.moveLeft=True
elif event.key==K_UP:
surface.moveUp=True
elif event.key==K_DOWN:
surface.moveDown=True
elif event.key==K_SPACE:
surface.speed=5
elif event.type==KEYUP:
if event.key==K_RIGHT:
surface.moveRight=False
elif event.key==K_LEFT:
surface.moveLeft=False
elif event.key==K_UP:
surface.moveUp=False
elif event.key==K_DOWN:
surface.moveDown=False
elif event.key==K_SPACE:
surface.speed=3.5
pygame.display.flip()
notbreak=True
while notbreak:
screen.fill((0,255,0))
if toohungry and isfull:
screen.blit(gameFont.render("Esc To Exit!",True,(128,128,128)),(2,2))
elif toohungry:
screen.blit(gameFont.render("Too hungry!",True,(0,0,0)),(2,2))
elif isfull:
screen.blit(gameFont.render("Full!",True,(0,0,0)),(2,2))
screen.blit(gameFont.render("Space To Retry",True,(128,128,128)),(2,32))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
__import__("sys").exit()
elif event.type==KEYUP:
if event.key==K_ESCAPE:
pygame.quit()
__import__("sys").exit()
elif event.key==K_SPACE:
notbreak=False
pygame.display.flip()
mainit()
mainit()
if __name__=="__main__":
initmain()Résumé
- Salut., C'est très simple. , Je ne vais pas le montrer. , Le bouton gauche de la souris se déplace tout le temps pour manger la nourriture tombée. !
GratuitBase de code source——
Petite compilation de messages privés06Ou cliquez sur la police bleue pour l'obtenir gratuitement!
Votre soutien est ma plus grande motivation.!!Souviens - toi de la troisième série.~mua Bienvenue à la lecture des articles précédents~
Recommandé dans certains articles de la période précédente ——
Projets1.5 PygamePetits jeux:Les Jeux botaniques ont vraiment“Poison.”?Je ne peux pas l'arrêter.~
Projets3.2 【PygamePetits jeux】Tout explose.、 Super bomber “Explosion”On y va., C'est ton enfance. ?
Résumé des articles——
Projets1.0 Python—2021 |Résumé des articles disponibles | Mise à jour continue,Ça suffit de lire ça
(Plus de détails+Le code source est résumé dans l'article.!!Bienvenue à la lecture~)
Résumé des articles——
Résumé: PythonCollection d'articles | (Démarrer sur le terrain、Le jeu、Turtle、Cas, etc.)
(Il y a d'autres cas à étudier.~Le code source peut me trouver gratuitement!)

边栏推荐
- Does polardb-x open source support mysql5.7?
- 关于快速幂
- Numerical extension of 27es6
- 域名绑定动态IP最佳实践
- Vulnerability recurrence ----- 34. Yapi remote command execution vulnerability
- SQL parsing practice of Pisa proxy
- Expert: those who let you go to a good school with a low score are all Scams
- PSS:你距离NMS-free+提点只有两个卷积层 | 2021论文
- 【170】PostgreSQL 10字段类型从字符串修改成整型,报错column cannot be cast automatically to type integer
- 【kotlin】第二天
猜你喜欢
随机推荐
sql注入原理
Luogu_ P1002 [noip2002 popularization group] crossing the river_ dp
3.2 multiple condition judgment
PolarDB-X现在版本的开源兼容什么?mysql8?
Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
February 16, 2022 freetsdb compilation and operation
熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
Can polardb-x be accessed through the client of related tools as long as the client supporting JDBC / ODBC protocol is afraid?
Go error collection | when a function uses a return value with a parameter name
老师能给我说一下固收+产品主要投资于哪些方面?
I want to buy fixed income + products, but I don't know what its main investment is. Does anyone know?
[digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)
What is the London Silver code
带你认识图数据库性能和场景测试利器LDBC SNB
Design of FIR digital filter
On traversal of tree nodes
Derivation of Halcon camera calibration principle
【170】PostgreSQL 10字段类型从字符串修改成整型,报错column cannot be cast automatically to type integer
机械硬盘和ssd固态硬盘的原理对比分析
Luogu_ P1007 single log bridge_ thinking









![Luogu_ P1003 [noip2011 improvement group] carpet laying_ Violence enumeration](/img/65/413ac967cc8fc22f170c8c7ddaa106.png)