当前位置:网站首页>[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!)

边栏推荐
- 保留有效位数;保留小数点后n位;
- [digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)
- Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
- Li Chuang EDA learning notes 16: array copy and array distribution
- I want to buy fixed income + products, but I don't know what its main investment is. Does anyone know?
- 跨域图像的衡量新方式Style relevance:论文解读和代码实战
- MySQL中符号@的作用
- Cannot determine value type from string ‘<p>1</p>‘
- SQL parsing practice of Pisa proxy
- Does polardb-x currently not support self-made database service Das?
猜你喜欢

Distributed session solution

Google Earth Engine(GEE)——Export. image. The difference and mixing of toasset/todrive, correctly export classification sample data to asset assets and references

漏洞复现----34、yapi 远程命令执行漏洞

洛谷入门1【顺序结构】题单题解

洛谷入门2【分支结构】题单题解

3.2 multiple condition judgment

一场分销裂变活动,不止是发发朋友圈这么简单!

Knowledge map model

Eolink 推出面向中小企业及初创企业支持计划,为企业赋能!

Programming skills: script scheduling
随机推荐
洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举
FPGA based analog I ² C protocol system design (with main code)
Creation and use of static library (win10+vs2022
Does polardb-x currently not support self-made database service Das?
[interview questions] common interview questions (I)
Indexeddb learning materials
Leetcode daily practice (Yanghui triangle)
Weekly snapshot of substrate technology 20220411
设计原则和思想:设计原则
[high concurrency] deeply analyze the callable interface
Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
16 -- remove invalid parentheses
Introduction to TTCAN brick moving
Cannot determine value type from string ‘<p>1</p>‘
Leetcode daily practice (longest substring without repeated characters)
2022-2-15 learning the imitated Niuke project - Section 5 shows comments
Design of UART controller based on FPGA (with code)
专用发票和普通发票的区别
E modulenotfounderror: no module named 'psychopg2' (resolved)
Go error collection | when a function uses a return value with a parameter name