Форум программистов, компьютерный форум, киберфорум
Python: PyGame
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/3: Рейтинг темы: голосов - 3, средняя оценка - 4.67
Чугунные скороходы
 Аватар для ARRAYBOW
17 / 16 / 3
Регистрация: 25.12.2022
Сообщений: 367

Неправильно удлиняется змейка!

25.12.2022, 12:25. Показов 783. Ответов 2

Студворк — интернет-сервис помощи студентам
Пытался всеми способами удлинять, но выходит что либо их колбасит или они двигаются неправильно. Нужно очень пожалуйста!
Python
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
import pygame
from ctypes import *
from pygame import *
import random
import copy
import time
 
debug_active = True
 
color = [(0,0,0),(150,0,0),(0,255,0),(255,0,0)]
pygame.init()
pygame.mixer.init()
score = 0
pygame.display.set_caption("Snake. Score: "+str(score))
if(debug_active == True):
    size = [int((windll.user32.GetSystemMetrics(0)) / 10 // 1 * 10),
            int((windll.user32.GetSystemMetrics(1) - 70) / 10 // 1 * 10)]
    screen = pygame.display.set_mode((size))
else:
    size = [int((windll.user32.GetSystemMetrics(0))),
            int((windll.user32.GetSystemMetrics(1)))]
    screen = pygame.display.set_mode((size),pygame.FULLSCREEN)
font = pygame.font.SysFont(None, 24)
background_image = pygame.image.load(f"bg{random.randint(1,7)}.png").convert()
background_image = pygame.transform.scale(background_image, (size[0],size[1]))
background_rect = background_image.get_rect(topleft=(0,0))
 
background_sound = pygame.mixer.Sound("bg.mp3")
eat_sound = pygame.mixer.Sound("eating.mp3")
death_sound = pygame.mixer.Sound("death.mp3")
 
plr_coords = [[int(random.randint(0,size[0])/10//1*10),int(random.randint(0,size[1])/10//1*10)]]
plr_rect = [Rect(plr_coords[0][0],plr_coords[0][1],10,10)]
pygame.draw.rect(screen,color[2], plr_rect[0])
plr_eat_coords = [int(random.randint(0,size[0])/10//1*10),int(random.randint(0,size[1])/10//1*10)]
plr_eat_rect = Rect(plr_eat_coords[0],plr_eat_coords[1],10,10)
pygame.draw.rect(screen,color[3],plr_eat_rect)
 
play = True
direction=[[0,0],[-10,0],[10,0],[0,-10],[0,10]]
direction_index = [0]
plr_death_active = False
text = font.render('Score: ' + str(score), True, (255, 255, 255))
plr_eat_active = False
plr_eat_head_active = False
direction_old = 0
plr_key_active = False
plr_key_active_timer = 0
plr_pause_active = False
plr_info = [[0,plr_coords[-1],direction_index[0]]]
background_sound.play(-1)
while(play):
     pygame.time.Clock().tick(20)
     plr_key = pygame.key.get_pressed()
     for event in pygame.event.get():
         if (event.type == pygame.QUIT or plr_key[K_ESCAPE]):
             play = False
     if (plr_key[K_a] and plr_eat_active == False and plr_key_active_timer == 0 and plr_pause_active == False and plr_death_active == False):
         plr_key_active = True
         direction_index.insert(0,1)
     elif (plr_key[K_d] and plr_eat_active == False and plr_key_active_timer == 0 and plr_pause_active == False and plr_death_active == False):
         plr_key_active = True
         direction_index.insert(0,2)
     elif (plr_key[K_w] and plr_eat_active == False and plr_key_active_timer == 0 and plr_pause_active == False and plr_death_active == False):
         direction_index.insert(0,3)
         plr_key_active = True
     elif (plr_key[K_s] and plr_eat_active == False and plr_key_active_timer == 0 and plr_pause_active == False and plr_death_active == False):
         direction_index.insert(0,4)
         plr_key_active = True
     elif (plr_key[K_h] and plr_eat_active == False and plr_key_active_timer == 0):
         plr_key_active = True
         if(plr_pause_active==False):
             plr_pause_active = True
         else:
             plr_pause_active = False
         if (direction_index[0] != 0):
             direction_old = copy.deepcopy(direction_index[0])
             direction_index.insert(0,0)
             text = font.render('Pause. Score: ' + str(score), True, (255, 255, 255))
         else:
             direction_index.insert(0,copy.deepcopy(direction_old))
             text = font.render('Score: ' + str(score), True, (255, 255, 255))
     if (plr_coords[0][0]==-10 or plr_coords[0][1]==-10 or plr_coords[0][0]==size[0] or plr_coords[0][1]==size[1]):
         plr_death_active = True
         direction_index = 0
         plr_coords = [[-300, -200]]
         plr_rect = [Rect(plr_coords[0][0], plr_coords[0][1], 10, 10)]
         plr_eat_rect = Rect(-300, -100, 10, 10)
         death_sound.play()
         text = font.render('You Lost. Score: ' + str(score) + ".", True, (255, 255, 255))
     count=0
     while(count<len(plr_rect) and plr_info[count][1]==plr_eat_coords):
         if (plr_info[0][1]==plr_eat_coords):
             score += 1
             eat_sound.play()
             plr_coords.append([plr_coords[0][0] - direction[direction_index[0]][0], plr_coords[0][1] - direction[direction_index[0]][1]])
             pygame.draw.rect(screen, color[3], plr_eat_rect)
             text = font.render('Score: ' + str(score), True, (255, 255, 255))
             plr_info.append([plr_info[-1][0] + 1, plr_coords[-1], direction_index[0]])
             plr_rect.append(Rect(plr_info[-1][1][0], plr_info[-1][1][1], 10, 10))
         plr_eat_coords = [int(random.randint(0, size[0]) / 10 // 1 * 10), int(random.randint(0, size[1]) / 10 // 1 * 10)]
         plr_eat_rect = Rect(plr_eat_coords[0], plr_eat_coords[1], 10, 10)
         count+=1
     pygame.display.update()
     if(plr_key_active_timer == 3):
         plr_key_active = False
         plr_key_active_timer = 0
     if(plr_key_active==True):
         plr_key_active_timer+=1
     screen.blit(background_image,background_rect)
     pygame.draw.rect(screen, color[3], plr_eat_rect)
     count = 0
     while(count<len(plr_rect)):
          plr_coords.append([plr_info[-1][1][0]+direction[plr_info[-1][2]][0],   # <---
                             plr_info[-1][1][1]+direction[plr_info[-1][2]][1]])  # <---
          plr_coords.pop(0)
          plr_info.append([count, plr_coords[count], plr_info[-1][2]])
          plr_info.pop(0)
          plr_rect[count] = Rect(plr_info[count][1][0],plr_info[count][1][1],10,10)
          pygame.draw.rect(screen, color[2], plr_rect[count])
          count+=1
     if (debug_active == True):
         pygame.display.set_caption("Snake. Score: " + str(score) + str(plr_coords) + str(plr_rect)
                                    + str(plr_info))
     else:
         pygame.display.set_caption("Snake. Score: " + str(score))
     screen.blit(text, (20, 20))
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
25.12.2022, 12:25
Ответы с готовыми решениями:

Появилась полоска на экране и медленно удлиняется
Добрый день! Сегодня появилась вот такая полоска на экране ноута + &quot;пятнышко&quot; под ней. Изначально она была гораздо меньше, где-то 0.75 см,...

Игра "Змейка": чтобы змейка не съедала сама себя
Здравствуйте! Пишу змейку на VB 2010. Не получается составить условие того, что бы змейка не ползла в направлении обратному...

"Змейка": нужно, чтобы змейка проходила сквозь стены
import sys import random from PIL import Image, ImageTk from tkinter import Tk, Frame, Canvas, ALL, NW class Cons: ...

2
Модератор
Эксперт Python
 Аватар для Fudthhh
2695 / 1601 / 513
Регистрация: 21.02.2017
Сообщений: 4,210
Записей в блоге: 1
26.12.2022, 16:20
ARRAYBOW, Нечитабельная дичь, в обработке нажатий вообще бред какой-то.
0
Чугунные скороходы
 Аватар для ARRAYBOW
17 / 16 / 3
Регистрация: 25.12.2022
Сообщений: 367
27.12.2022, 17:36  [ТС]
Да знаю, не очень читабельно, но я понял, где ошибка, но как исправить я не знаю:
Python
1
2
3
4
5
6
7
        if(count==0):
            plr_coords[count] = [plr_info[count][1][0] + direction[plr_info[count][2]][0],       # error
                                 plr_info[count][1][1] + direction[plr_info[count][2]][1]]       # error
            plr_info[count] = [count, plr_coords[count], direction_index[0]]
        else:
            plr_coords[count] = [plr_info[count-1][1][0],   # error
                                 plr_info[count-1][1][1]]   # error
Если надо, то вот наверно более читабельный код:
Python
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
import pygame
from ctypes import *
from pygame import *
import random
import copy
import time
 
debug_active = True
 
color = [(0, 0, 0), (150, 0, 0), (0, 255, 0), (255, 0, 0)]
direction = [[0, 0], [-10, 0], [10, 0], [0, -10], [0, 10]]
direction_index = [0]
plr_death_active = False
plr_eat_active = False
plr_eat_head_active = False
direction_old = 0
plr_key_active = False
plr_key_active_timer = 0
plr_pause_active = False
 
def init():
    def pygameinit():
        pygame.init()
        pygame.mixer.init()
        score = 0
        pygame.display.set_caption("Snake. Score: " + str(score))
        if (debug_active == True):
            size = [int((windll.user32.GetSystemMetrics(0)) / 10 // 1 * 10),
                    int((windll.user32.GetSystemMetrics(1) - 70) / 10 // 1 * 10)]
            screen = pygame.display.set_mode((size))
        else:
            size = [int((windll.user32.GetSystemMetrics(0))),
                    int((windll.user32.GetSystemMetrics(1)))]
            screen = pygame.display.set_mode((size), pygame.FULLSCREEN)
        font = pygame.font.SysFont(None, 24)
        return size,screen,font,score
    size,screen,font,score=pygameinit()
 
    def plrinit():
        plr_coords = [[int(random.randint(0, size[0]) / 10 // 1 * 10), int(random.randint(0, size[1]) / 10 // 1 * 10)]]
        plr_rect = [Rect(plr_coords[0][0], plr_coords[0][1], 10, 10)]
        pygame.draw.rect(screen, color[2], plr_rect[0])
        plr_eat_coords = [int(random.randint(0, size[0]) / 10 // 1 * 10),
                          int(random.randint(0, size[1]) / 10 // 1 * 10)]
        plr_eat_rect = Rect(plr_eat_coords[0], plr_eat_coords[1], 10, 10)
        plr_info = [[0, plr_coords[-1], direction_index[0]]]
        pygame.draw.rect(screen, color[3], plr_eat_rect)
        return plr_coords,plr_rect,plr_eat_coords,plr_eat_rect,plr_info
    plr_coords,plr_rect,plr_eat_coords,plr_eat_rect,plr_info = plrinit()
 
    def fileinit():
        background_image = pygame.image.load(f"bg{random.randint(1, 7)}.png").convert()
        background_image = pygame.transform.scale(background_image, (size[0], size[1]))
        background_rect = background_image.get_rect(topleft=(0, 0))
        background_sound = pygame.mixer.Sound("bg.mp3")
        eat_sound = pygame.mixer.Sound("eating.mp3")
        death_sound = pygame.mixer.Sound("death.mp3")
        return background_image,background_rect,background_sound,eat_sound,death_sound
    background_image,background_rect,background_sound,eat_sound,death_sound = fileinit()
 
    return size,screen,font,score,plr_coords,plr_rect,plr_eat_coords,plr_eat_rect,plr_info,background_image,\
           background_rect,background_sound,eat_sound,death_sound
 
size,screen,font,score,plr_coords,plr_rect,plr_eat_coords,plr_eat_rect,plr_info,\
background_image,background_rect,background_sound,eat_sound,death_sound = init()
 
text = font.render('Score: ' + str(score), True, (255, 255, 255))
 
def keydetect(plr_key):
    global direction_old
    global plr_pause_active
    global plr_key_active_timer
    global play
    global plr_key_active
    global plr_eat_active
    global plr_death_active
    global text
    global score
    for event in pygame.event.get():
        if (event.type == pygame.QUIT or plr_key[K_ESCAPE]):
            exit(0)
    if (plr_key[K_a] and plr_eat_active == False and plr_key_active_timer == 0
            and plr_pause_active == False and plr_death_active == False):
        plr_key_active = True
        direction_index.insert(0, 1)
    elif (plr_key[K_d] and plr_eat_active == False and plr_key_active_timer == 0
            and plr_pause_active == False and plr_death_active == False):
        plr_key_active = True
        direction_index.insert(0, 2)
    elif (plr_key[K_w] and plr_eat_active == False and plr_key_active_timer == 0
            and plr_pause_active == False and plr_death_active == False):
        direction_index.insert(0, 3)
        plr_key_active = True
    elif (plr_key[K_s] and plr_eat_active == False and plr_key_active_timer == 0
          and plr_pause_active == False and plr_death_active == False):
        direction_index.insert(0, 4)
        plr_key_active = True
    elif (plr_key[K_h] and plr_eat_active == False and plr_key_active_timer == 0):
        plr_key_active = True
        if (plr_pause_active == False):
            plr_pause_active = True
        else:
            plr_pause_active = False
        if (direction_index[0] != 0):
            direction_old = copy.deepcopy(direction_index[0])
            direction_index.insert(0, 0)
            text = font.render('Pause. Score: ' + str(score), True, (255, 255, 255))
        else:
            direction_index.insert(0, copy.deepcopy(direction_old))
            text = font.render('Score: ' + str(score), True, (255, 255, 255))
 
def deathcheck():
    global plr_coords
    if (plr_coords[0][0] == -10 or plr_coords[0][1] == -10 or plr_coords[0][0] == size[0] or plr_coords[0][1] == size[
        1]):
        plr_death_active = True
        direction_index = 0
        plr_coords = [[-300, -200]]
        plr_rect = [Rect(plr_coords[0][0], plr_coords[0][1], 10, 10)]
        plr_eat_rect = Rect(-300, -100, 10, 10)
        death_sound.play()
        text = font.render('You Lost. Score: ' + str(score) + ".", True, (255, 255, 255))
 
def eatcheck():
    global plr_eat_coords
    global plr_eat_rect
    global score
    count = 0
    while (count < len(plr_rect) and plr_info[count][1] == plr_eat_coords):
        if (plr_info[0][1] == plr_eat_coords):
            score += 1
            eat_sound.play()
            plr_coords.append([plr_coords[-1][0],
                               plr_coords[-1][1]])
            pygame.draw.rect(screen, color[3], plr_eat_rect)
            text = font.render('Score: ' + str(score), True, (255, 255, 255))
            plr_info.append([plr_info[-1][0] + 1, plr_coords[-1], direction_index[0]])
            plr_rect.append(Rect(plr_info[-1][1][0], plr_info[-1][1][1], 10, 10))
        plr_eat_coords = [int(random.randint(0, size[0]) / 10 // 1 * 10),
                          int(random.randint(0, size[1]) / 10 // 1 * 10)]
        plr_eat_rect = Rect(plr_eat_coords[0], plr_eat_coords[1], 10, 10)
        count += 1
 
def timer(plr_key_active_timer):
    global plr_key_active
    if (plr_key_active_timer == 3):
        plr_key_active = False
        plr_key_active_timer = 0
    if (plr_key_active == True):
        plr_key_active_timer += 1
 
def title(debug_active):
    if (debug_active == True):
        pygame.display.set_caption("Snake. Score: " + str(score) + str(plr_coords) + str(plr_rect)
                                   + str(plr_info))
    else:
        pygame.display.set_caption("Snake. Score: " + str(score))
 
def dispupdate():
    pygame.display.update()
    screen.blit(background_image, background_rect)
    pygame.draw.rect(screen, color[3], plr_eat_rect)
    count = 0
    while(count<len(plr_rect)):
        pygame.draw.rect(screen, color[2], plr_rect[count])
        count+=1
    screen.blit(text, (20, 20))
 
def plrupdate():
    count = 0
    while (count < len(plr_rect)):
        if(count==0):
            plr_coords[count] = [plr_info[count][1][0] + direction[plr_info[count][2]][0],       # error
                                 plr_info[count][1][1] + direction[plr_info[count][2]][1]]       # error
            plr_info[count] = [count, plr_coords[count], direction_index[0]]
        else:
            plr_coords[count] = [plr_info[count-1][1][0],   # error
                                 plr_info[count-1][1][1]]   # error
            plr_info[count] = [count, plr_info[count-1][1], plr_info[count-1][2]]
        plr_rect[count] = Rect(plr_info[count][1][0], plr_info[count][1][1], 10, 10)
        count += 1
 
def wndactive():
    background_sound.play(-1)
    while (True):
        pygame.time.Clock().tick(20)
        plr_key = pygame.key.get_pressed()
        keydetect(plr_key)
        deathcheck()
        eatcheck()
        title(debug_active)
        timer(plr_key_active_timer)
        plrupdate()
        dispupdate()
 
 
wndactive()
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.12.2022, 17:36
Помогаю со студенческими работами здесь

Приоритет процесса: я неправильно его изменяю или неправильно считываю?
Вот участок кода этой крошечной программы DWORD WINAPI t1(LPVOID); DWORD WINAPI t2(LPVOID); DWORD WINAPI t3(LPVOID); DWORD...

Проверьте задачку по циклам, неправильно работает. [думаю что неправильно]
Спасибо что решили зайти. Задание выгладит так: http://*******/PW95p А результат выплнения: http://*******/KwhuS #include...

Неправильно работает цикл for, и функции работают неправильно
1) Неправильно работает цикл for(k=0...). Входит только 1 раз, дальше вылетает. Делал пошаговую отладку на проверку значения k. Выдаёт...

Oracle неправильно выполняет запрос или я неправильно принимаю Oracle
Неправильно отрабатывает автоматически сгенерированный NHibernate запрос. select s.*, rownum from( select t2.BOOLEAN_VALUE as...

змейка с++
ребят,вот наработки,не могу придумать нормальный алгоритм перемещения змейки,точнее перемещение,когда она будет увеличиваться... ведь ей...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru