Código de Python - Juego de la Serpiente (en ASCII)

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Juego de la Serpiente (en ASCII)gráfica de visualizaciones


Python

Actualizado el 12 de Abril del 2024 por Antonio (75 códigos) (Publicado el 30 de Marzo del 2020)
6.805 visualizaciones desde el 30 de Marzo del 2020
Versión, con caracteres ASCII del popular "Juego de la Serpiente" que incorpora una pantalla de opciones. El control de la serpiente se efectúa mediante las teclas de dirección del teclado. También puede pausarse la partida, presionando la barra espaciadora y una función para salir de partida, mediante la tecla "q".
sg4
sg7
sng

Requerimientos

Lenguaje: Python
Librerías: curses, time, random

1.2
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 12 de Abril del 2024 (Publicado el 30 de Marzo del 2020)gráfica de visualizaciones de la versión: 1.2
6.806 visualizaciones desde el 30 de Marzo del 2020
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
#!/usr/bin/python
# -*- coding: latin-1 -*-
import curses
import time
import random
from curses import textpad
 
menu = ['New Game', 'Quit']
hi_score = 0
 
def print_menu(stdscr, selected_row_idx):
    stdscr.clear()
    h, w = stdscr.getmaxyx()
    texto = "S  N  A  K  E   G  A  M  E"
    x = w//2 - len(texto)//2
    stdscr.addstr(10, x, texto)
    sh, sw = stdscr.getmaxyx()
    box = [[3,3], [sh-3, sw-3]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])
    h, w = stdscr.getmaxyx()
    for idx, row in enumerate(menu):
        x = w//2 - len(row)//2
        y = h//2 - len(menu)//2 + idx
        if idx == selected_row_idx:
            stdscr.attron(curses.color_pair(1))
            stdscr.addstr(y, x, row)
            stdscr.attroff(curses.color_pair(1))
        else:
            stdscr.addstr(y, x, row)
    stdscr.refresh()
 
def center_text(stdscr,text):
    h, w = stdscr.getmaxyx()
    x = w//2 - len(text)//2
    y = h//2
    stdscr.addstr(y, x, text)
 
def print_center(stdscr, text):
    stdscr.clear()
    center_text(stdscr,text)
    stdscr.refresh()
 
def pantalla(stdscr):
    curses.curs_set(0)
    stdscr.nodelay(1)
    stdscr.timeout(100)
 
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
 
    current_row = 0
 
    print_menu(stdscr, current_row)
 
    while 1:
        key = stdscr.getch()
 
        if key == curses.KEY_UP and current_row > 0:
            current_row -= 1
            curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        elif key == curses.KEY_DOWN and current_row < len(menu)-1:
            current_row += 1
            curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_RED)
        elif key == curses.KEY_ENTER or key in [10, 13]:
            if current_row== len(menu)-1:
                print_center(stdscr, "See you later".format(menu[current_row]))
                time.sleep(2)
                break
            else:
                stdscr.clear()
                main(stdscr)
                break
        print_menu(stdscr, current_row)
 
def create_food(snake, box):
    food = None
    while food is None:
        food = [random.randint(box[0][0]+1, box[1][0]-1),
        random.randint(box[0][1]+1, box[1][1]-1)]
        if food in snake:
            food = None
    return food
 
def main(stdscr):
    global FT, hi_score
    curses.curs_set(0)
 
    sh, sw = stdscr.getmaxyx()
    box = [[3,3], [sh-3, sw-3]]
    stdscr.addstr(1,81,"'q'=QUIT  <SPACE BAR>=PAUSE/CONTINUE")
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])
 
    snake = [[sh//2, sw//2+1], [sh//2, sw//2], [sh//2, sw//2-1]]
    direction = curses.KEY_RIGHT
 
    for y,x in snake:
        stdscr.addstr(y, x, '#')
 
    food = create_food(snake, box)
    stdscr.addstr(food[0], food[1], '*')
 
    score = 0
    score_text = "Score: {}".format(score)
    hi_score_text = "Hi-Score: {}".format(hi_score)
    stdscr.addstr(1, sw//2 - len(score_text)//2, score_text)
    stdscr.addstr(1, 4, hi_score_text)
 
    PAUSE = False
 
    while 1:
        key = stdscr.getch()
 
        if key == ord(' '):
            if PAUSE == False:
                PAUSE = True
                center_text(stdscr,"PAUSE")
            else:
                PAUSE = False
                center_text(stdscr,"     ")
 
        if key == ord('q') or key == ord('Q'):
            break
 
        if PAUSE == False:
            if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_DOWN, curses.KEY_UP]:
                direction = key
 
            head = snake[0]
            if direction == curses.KEY_RIGHT:
                new_head = [head[0], head[1]+1]
            elif direction == curses.KEY_LEFT:
                new_head = [head[0], head[1]-1]
            elif direction == curses.KEY_DOWN:
                new_head = [head[0]+1, head[1]]
            elif direction == curses.KEY_UP:
                new_head = [head[0]-1, head[1]]
 
            stdscr.addstr(new_head[0], new_head[1], '#')
            snake.insert(0, new_head)
 
            if snake[0] == food:
                curses.beep()
                score += 1
                if score > hi_score:
                    hi_score+=1
 
                hi_score_text = "Hi-Score: {}".format(hi_score)
                score_text = "Score: {}".format(score)
                stdscr.addstr(1, sw//2 - len(score_text)//2, score_text)
                stdscr.addstr(1, 4, hi_score_text)
 
                food = create_food(snake, box)
                stdscr.addstr(food[0], food[1], '*')
 
                stdscr.timeout(100 - (len(snake)//3)%90)
            else:
                stdscr.addstr(snake[-1][0], snake[-1][1], ' ')
                snake.pop()
 
            if (snake[0][0] in [box[0][0], box[1][0]] or
                snake[0][1] in [box[0][1], box[1][1]] or
                snake[0] in snake[1:]):
                msg = "GAME OVER"
                stdscr.addstr(sh//2, sw//2-len(msg)//2, msg)
                stdscr.getch()
                stdscr.nodelay(0)
                time.sleep(2)
                break
    pantalla(stdscr)
 
curses.wrapper(pantalla)



Comentarios sobre la versión: 1.2 (1)

Imágen de perfil
30 de Marzo del 2020
estrellaestrellaestrellaestrellaestrella
Buenisssimo!!!
Responder

Comentar la versión: 1.2

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s6071