1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
|
# -*- coding: utf8 -*-
#################################################################
# #
# Nom du fichier : SerpentC.py #
# #
#################################################################
# #
# Auteur : Pascal St-louis #
# Date : 07/03/2016 --> Version 1 #
# #
# OS : Windows #
# Language : Python 3 #
# #
# Module: #
# os #
# time #
# msvcrt #
# copy #
# random #
# winsound #
# #
# Type : Jeu en console #
# #
# Description: #
# Le jeu du serpent consiste a diriger un être dans #
# un parcours d'obstacle afin de le faire manger des #
# pommes. A chaque pomme manger le serpent s'agrandi. #
# #
# Règle: #
# Le serpent ne doit pas frapper d'obstacle, ni se #
# manger lui-même. Le monde boucle sur lui-même, ce #
# qui fait que si le serpent sort de la carte, il #
# reviendra de l'autre côté #
# #
# Objectif: #
# Accumuler le plus de point possible en mangeant des #
# pommes #
# #
# Controle: #
# Touche flêché = direction #
# Touche s = départ/pause #
# Touche r = reset #
# Touche esc = quitter #
# #
#################################################################
#Importation des modules
import os, time, msvcrt, copy, random, winsound
#Classes
class Map():
def __init__(self, size):
"""Crée une carte avec des bordures"""
self.size = size
#Tableau 2 dimentions
self.map = []
for j in range(0,self.size[1]):
l = []
for i in range(0,self.size[0]):
if i == 0 and j == 0:
l.append("╔")
elif i == self.size[0]-1 and j == 0:
l.append("╗")
elif i == 0 and j == self.size[1]-1:
l.append("╚")
elif i == self.size[0]-1 and j == self.size[1]-1:
l.append("╝")
elif i >= 0 and j == 0:
l.append("═")
elif i == 0 or i == self.size[0]-1:
l.append("║")
elif i >= 0 and j == self.size[1]-1:
l.append("═")
else:
l.append(" ")
self.map.append(l)
def set_map(self, coord, value):
"""Modifie une valeur a l'endroit choisi dans le tableau"""
x,y = coord
self.map[y][x] = value
def get_width(self):
"""Retourne la largueur du tableau"""
return len(self.map[0])
def get_height(self):
"""Retourne la hauteur du tableau"""
return len(self.map)
def get_map(self):
"""Retourne une copie du tableau"""
return copy.deepcopy(self.map)
class Perso():
def __init__(self, lenght, coord, direction):
"""Crée le personnage représenté par une liste de coordonnées"""
self.lenght = lenght
x,y = coord
d1,d2 = direction
self.listCoord = [(x,y,d1,d2)]
#Crée plusieur adresse selon la longueur(lenght) demandé
#une sous l'autre
for i in range(0, lenght-1):
x,y,_,_ = self.listCoord[-1]
self.listCoord.append((x,y+1,d1,d2))
def move(self, coord):
"""Décale les adresses en rajoutant la nouvelle en premier et en effacant
la dernière"""
mx,my = coord
x,y,_,_ = self.listCoord[0]
nX = mx+x
nY = my+y
self.listCoord.insert(0, (nX,nY,mx,my))
self.listCoord.pop()
def add_one(self):
"""Augmente la longueur de la liste"""
#Récupere les deux dernières adresse pour créé la nouvelle derrière les
#autres dans le même sens que la dernière
x,y,_,_ = self.listCoord[-1]
x1,y1,dx,dy = self.listCoord[-2]
a = x-x1
b = y-y1
nX = a+x
nY = b+y
self.listCoord.append((nX,nY,dx,dy))
def set_list(self, liste):
"""Modifie la liste des adresses"""
self.listCoord = copy.deepcopy(liste)
def get_list(self):
"""Retourne une copie de la liste d'adresse"""
return copy.deepcopy(self.listCoord)
class Game():
def __init__(self, **kwarg):
"""Crée une fenetre"""
title = "Screen"
self.w,self.h = 80,25
self.bgColor = 0
self.textColor = 7
for key in kwarg:
if key == "title": title = kwarg[key]
elif key == "screenSize": self.w,self.h = kwarg[key]
elif key == "bgColor": self.bgColor = kwarg[key]
elif key == "textColor": self.textColor = kwarg[key]
else: raise ValueError("Invalid Argument :"+key)
os.system("title "+title)
os.system("color "+str(self.bgColor)+str(self.textColor))
#ScreenSize
if self.w < 43:
self.w = 43
if self.h < 10:
self.h = 10
os.system("mode con cols="+str(self.w)+" lines="+str(self.h))
self.create()
self.loop()
def create(self):
"""Crée les différents objets"""
self.flash = True #Basculeur qui fais clignoter un texte
self.pause = True #Met en pause le programme
self.state = "alive" #Donne l'état actuel du joueur
self.lock = False #Bloque le programme si le joueur meurt
#La carte du jeu
self.map = Map((self.w-1,self.h-1))
#serpent centré dans la carte et regard vers le haut
self.direction = (0,-1)
self.perso = Perso(3, (int(self.map.get_width()/2),int(self.map.get_height()/2)), self.direction)
#Cible pour le serpent
self.listCible = []
for i in range(0,3):
x = random.randrange(1,self.map.get_width()-1)
y = random.randrange(1,self.map.get_height()-1)
self.listCible.append((x,y))
#Obstacle
self.listObs = []
for j in range(1, self.map.get_height()-1):
for i in range(1, self.map.get_width()-1):
chance = random.randrange(0,50)
if chance == 0:
x = random.randrange(1,self.map.get_width()-1)
y = random.randrange(1,self.map.get_height()-1)
#Empeche d'avoir un obstacle devant le joueur
if x == int(self.map.get_width()/2):
x = x-1
#Empeche de placer un obstacle sur une cible
noGood = False
for coord in self.listCible:
if coord == (x,y):
noGood = True
if not noGood:
self.listObs.append((x,y))
def loop(self):
"""Loop sur les différentes partie du programme"""
#Son intro
winsound.Beep(500,100)
winsound.Beep(750,100)
winsound.Beep(650,100)
#Boucle principal
self.run = True
while self.run:
self.display()
self.event()
if not self.pause:
self.move()
self.action()
self.dead()
#Son exit
winsound.Beep(650,100)
winsound.Beep(750,100)
winsound.Beep(500,100)
sys.exit(0)
def event(self):
"""Gère les évènements clavier"""
if msvcrt.kbhit(): #vérifie si une touche a été presser
a = msvcrt.getwch() #retourne la touche pressé
else: #sinon, il en simule une
time.sleep(0.15)
a = ""
if a == "\x1b": #Esc
self.run = False
elif a == "\r": #Enter
None
elif a == "s" and not self.lock: #Pause
winsound.Beep(500,50)
if self.pause:
self.pause = False
else:
self.pause = True
elif a == "r" and self.lock: #Restart
winsound.Beep(1000,50)
os.system("color "+str(self.bgColor)+str(self.textColor))
self.create()
#Touche spécial, retourne "\xe0" si on appuis sur une touche spécial
#et ensuite, lors du deuxième appel de getwch(), retourne le code de
#cette touche, ce qui oblige a appeler la fonction une deuxieme fois
elif a == "\xe0" and not self.pause:
a = msvcrt.getwch()
if a == "H" and self.direction != (0,1): #Haut
self.direction = (0,-1)
elif a == "P" and self.direction != (0,-1): #Bas
self.direction = (0,1)
elif a == "K" and self.direction != (1,0): #Gauche
self.direction = (-1,0)
elif a == "M" and self.direction != (-1,0): #Droit
self.direction = (1,0)
def move(self):
"""Gère les mouvements"""
self.perso.move(self.direction)
l = self.perso.get_list()
x,y,dx,dy = l[0]
#Fais revenir de l'autre côté si on sort de la carte
if x <= 0:
x = self.map.get_width()-2
elif x >= self.map.get_width()-1:
x = 1
if y <= 0:
y = self.map.get_height()-2
elif y >= self.map.get_height()-1:
y = 1
l[0] = (x,y,dx,dy)
self.perso.set_list(l)
def action(self):
"""Gère les interactions entre les objets du programme"""
for coord in self.listCible:
x,y,_,_ = self.perso.get_list()[0]
if coord == (x,y):
self.listCible.remove(coord)
self.perso.add_one()
#Crée une nouvelle cible, et boucle jusqu'à trouver un
#endroit vide pour la placer
find = True
while find:
x = random.randrange(1,self.map.get_width()-1)
y = random.randrange(1,self.map.get_height()-1)
noGood = False
for coord in self.listObs:
if coord == (x,y):
noGood = True
if not noGood:
self.listCible.append((x,y))
find = False
winsound.Beep(800,50) #Son manger
def dead(self):
"""Gère les conditions de mort"""
listPerso = self.perso.get_list()
#Si le joueur se mange lui-même
for coord in listPerso:
x,y,_,_ = coord
listPerso.remove(coord)
for coord2 in listPerso:
x2,y2,_,_ = coord2
if (x,y) == (x2,y2):
self.state = "Dead"
#Si le joueur frappe un mur
for coord in self.listObs:
x,y,_,_ = self.perso.get_list()[0]
if coord == (x,y):
self.state = "Dead"
#Action effectuer s'il y a mort
if self.state == "Dead":
os.system("color 50")
self.pause = True
self.lock = True
winsound.Beep(350,1000) #Son mort
def display(self):
"""Gère et format l'affichage"""
#On prend toute les coordonnées des différents objets du programme,
#que l'on rajoute dans la liste de liste de la carte (listMap) qui
# est un tableau de case, puis on affiche le résultat sur l'écran
os.system("cls")
listMap = self.map.get_map()
listPerso = self.perso.get_list()
for coord in self.listObs:
x,y = coord
listMap[y][x] = "X"
for coord in self.listCible:
x,y = coord
listMap[y][x] = "Ó"
head = True
for coord in listPerso:
x,y,dx,dy = coord
if head: #Si c'est la tête selon la direction
if self.direction == (1,0):
listMap[y][x] = ">"
elif self.direction == (-1,0):
listMap[y][x] = "<"
elif self.direction == (0,-1):
listMap[y][x] = "A"
elif self.direction == (0,1):
listMap[y][x] = "V"
head = False
else:
if (dx == 1 and dy == 0) or (dx == -1 and dy == 0):
listMap[y][x] = "-"
elif (dx == 0 and dy == 1) or (dx == 0 and dy == -1):
listMap[y][x] = "|"
#Affichage du statue
text1 = "╣ State = "+self.state+" ╠"
y = 0
x = 1
for char in text1:
listMap[y][x] = char
x += 1
#Affichage des consignes, flash si en pause ou il y a mort
if self.pause and not self.lock:
if self.flash:
text2 = "╣ Press (S) to start ╠"
self.flash = False
else:
text2 = "╣ ╠"
self.flash = True
elif self.lock: #si le joueur meurt
if self.flash:
text2 = "╣ Press (R) to restart ╠"
self.flash = False
else:
text2 = "╣ ╠"
self.flash = True
else:
text2 = "╣ Press (S) to stop ╠"
y = 0
x = len(listMap[0])-1-len(text2)
for char in text2:
listMap[y][x] = char
x += 1
#Affichage des points
text3 = "╣ Score = "+str(len(self.perso.get_list())- self.perso.lenght)+" ╠"
y = len(listMap)-1
x = 1
for char in text3:
listMap[y][x] = char
x += 1
#Affichage des consignes
text4 = "╣ Press (Esc) to quit ╠"
y = len(listMap)-1
x = len(listMap[0])-1-len(text4)
for char in text4:
listMap[y][x] = char
x += 1
#Rendu final, imprime sur l'écran
a = ""
for ligne in listMap:
a = ""
for element in ligne:
a = a+str(element)
print(a)
if __name__ == "__main__":
Game(title="Serpent", screenSize=(80,20), bgColor=1, textColor="F") |
Partager