我創建了一個使用 pygame 定義和創建蛇的類。當我創建蛇類的一個實體時,將正確創建一條蛇,但是當我嘗試創建兩個實體時,我的代碼不會創建第二條蛇。我不確定這是因為我錯誤地使用了 pygame,還是因為我在課堂上做錯了什么。
這是我的代碼;它有點長,但我已經包括了它,因為我不知道問題出在哪里。我很確定我正確處理了所有變數和引數,并且處理按鍵也是正確的。如果您將此代碼復制并粘貼到解釋器中,如果您說想要一條蛇,它可以正常作業,但當您想要創建兩條蛇時它不起作用。
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"; import pygame
import random
import time
import copy
black = pygame.Color(0, 0, 0)
class Snake():
def __init__(self, game_window, controls, color, position, speed, window_specs,can_touch=True,respawn=True):
self.game_window = game_window
self.color = color
self.window_x = window_specs[0]
self.window_y = window_specs[1]
self.can_touch = can_touch
self.respawn = respawn
self.snake_position = position.copy()
self.snake_body = [position.copy()]
self.speed = speed
self.controls = controls.copy()
self.direction = 'RIGHT'
self.change_to = self.direction
self.moving = True
self.fps = pygame.time.Clock()
self.start_moving()
def start_moving(self):
#Handles the controls and movement. Control first snake with 'wasd'. Control second snake with arrow keys.
while self.moving == True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == self.controls[0]:
self.change_to = 'UP'
if event.key == self.controls[1]:
self.change_to = 'LEFT'
if event.key == self.controls[2]:
self.change_to = 'DOWN'
if event.key == self.controls[3]:
self.change_to = 'RIGHT'
if self.change_to == 'UP' and self.direction != 'DOWN':
self.direction = 'UP'
if self.change_to == 'DOWN' and self.direction != 'UP':
self.direction = 'DOWN'
if self.change_to == 'LEFT' and self.direction != 'RIGHT':
self.direction = 'LEFT'
if self.change_to == 'RIGHT' and self.direction != 'LEFT':
self.direction = 'RIGHT'
if self.direction == 'UP':
self.snake_position[1] -= 10
if self.direction == 'LEFT':
self.snake_position[0] -= 10
if self.direction == 'DOWN':
self.snake_position[1] = 10
if self.direction == 'RIGHT':
self.snake_position[0] = 10
self.snake_body.insert(0, list(self.snake_position))
self.snake_body.pop()
self.game_window.fill(black)
for pos in self.snake_body:
pygame.draw.rect(self.game_window,self.color,pygame.Rect(pos[0],pos[1],10,10))
#Toggles whether snake will die if touching itself
if self.can_touch == False:
for block in self.snake_body[1:]:
if self.snake_position[0] == block[0] and self.snake_position[1] == block[1]:
self.die()
#Kills snake if snake touches the edge of the window
if self.snake_position[0] < 0 or self.snake_position[0] > (self.window_x - 10):
self.die()
if self.snake_position[1] < 0 or self.snake_position[1] > (self.window_y - 10):
self.die()
pygame.display.update()
self.fps.tick(self.speed)
def die(self):
#Reset the snake
self.moving = False
self.game_window.fill(black)
self.snake_body = []
self.position = []
pygame.display.update()
time.sleep(1)
#Makes the snake respawn in a random location
if self.respawn == True:
self.direction = 'RIGHT'
self.change_to = self.direction
self.snake_position = [random.randrange(1, (self.window_x//100)) * 10,
random.randrange(1, (self.window_y//100)) * 10]
self.snake_body = [self.snake_position.copy()]
self.moving = True
self.start_moving()
class App():
def __init__(self,num_players,can_touch=True,respawn=True):
self.controls = [[pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d],
[pygame.K_UP,pygame.K_LEFT,pygame.K_DOWN,pygame.K_RIGHT]]
self.starting_positions = [[100,50], [200, 100]]
self.speed = 15
self.window_specs = [720,480]
self.num_players = num_players
self.can_touch = can_touch
self.respawn = respawn
self.players = {}
#Start up pygame
pygame.init()
pygame.display.set_caption('Snake Game')
self.game_window = pygame.display.set_mode((self.window_specs[0], self.window_specs[1]))
self.get_players()
def get_players(self):
#Let the players choose what color they want
player_color = []
for i in range(self.num_players):
player_color.append(input(f'Player {i 1}, what color do you want your snake to be? '))
if player_color[i] == 'red':
player_color[i] = pygame.Color(255,0,0)
elif player_color[i] == 'green':
player_color[i] = pygame.Color(0,255,0)
elif player_color[i] == 'blue':
player_color[i] = pygame.Color(0,0,255)
else:
player_color[i] = pygame.Color(255,255,255)
#Create the Snakes, this is the bit that does not work.
for i in range(self.num_players):
self.players[f'player{i 1}'] = Snake(self.game_window,self.controls[i],player_color[i],self.starting_positions[i],self.speed,self.window_specs)
if __name__ == "__main__":
num_players = int(input('1 or 2 players: '))
App(num_players)
uj5u.com熱心網友回復:
您需要為整個應用程式創建一個應用程式回圈,而不是為每個蛇創建一個單獨的應用程式。從類中洗掉應用程式回圈Snake:
class Snake():
def __init__(self, game_window, controls, color, position, window_specs,can_touch=True,respawn=True):
self.game_window = game_window
self.color = color
self.window_x = window_specs[0]
self.window_y = window_specs[1]
self.can_touch = can_touch
self.respawn = respawn
self.snake_position = position.copy()
self.snake_body = [position.copy()]
self.controls = controls.copy()
self.direction = (1, 0)
def move(self, event_list):
#Handles the controls and movement. Control first snake with 'wasd'. Control second snake with arrow keys.
for event in event_list:
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == self.controls[0] and self.direction[1] <= 0:
self.direction = (0, -1)
if event.key == self.controls[1] and self.direction[0] <= 0:
self.direction = (-1, 0)
if event.key == self.controls[2] and self.direction[1] >= 0:
self.direction = (0, 1)
if event.key == self.controls[3] and self.direction[0] >= 0:
self.direction = (1, 0)
self.snake_position[0] = self.direction[0] * 10
self.snake_position[1] = self.direction[1] * 10
self.snake_body.insert(0, list(self.snake_position))
self.snake_body.pop()
for pos in self.snake_body:
pygame.draw.rect(self.game_window,self.color,pygame.Rect(pos[0],pos[1],10,10))
#Toggles whether snake will die if touching itself
if self.can_touch == False:
for block in self.snake_body[1:]:
if self.snake_position[0] == block[0] and self.snake_position[1] == block[1]:
self.die()
#Kills snake if snake touches the edge of the window
if self.snake_position[0] < 0 or self.snake_position[0] > (self.window_x - 10):
self.die()
if self.snake_position[1] < 0 or self.snake_position[1] > (self.window_y - 10):
self.die()
def die(self):
self.snake_body = []
self.position = []
#Makes the snake respawn in a random location
if self.respawn == True:
self.direction = (1, 0)
self.snake_position = [random.randrange(1, (self.window_x//100)) * 10,
random.randrange(1, (self.window_y//100)) * 10]
self.snake_body = [self.snake_position.copy()]
但是在以下位置添加一個應用程式回圈App:
class App():
# [...]
def get_players(self):
#Let the players choose what color they want
player_color = []
color_dict = {'red': (255, 0, 0), 'green': (0, 255, 0), 'blue': (0, 0, 255)}
for i in range(self.num_players):
color = input(f'Player {i 1}, what color do you want your snake to be? ')
player_color.append(color_dict[color] if color in color_dict else (255, 255, 255))
#Create the Snakes, this is the bit that does not work.
for i in range(self.num_players):
self.players[f'player{i 1}'] = Snake(self.game_window,self.controls[i],player_color[i],self.starting_positions[i],self.window_specs)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(self.speed)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
self.game_window.fill(black)
for key in self.players:
self.players[key].move(event_list)
pygame.display.update()
pygame.quit()

uj5u.com熱心網友回復:
這里的問題是您沒有為此游戲設定專用的游戲回圈。您的游戲的“游戲回圈”現在位于單個蛇物件中。你的 Snake.start_moving 函式是持續運行的東西,你看到你的蛇在哪里移動等等。在你創建一條蛇的情況下,你正在運行的是蛇的 start_moving 函式,所以表面上看起來一切都很好。
如果你用 2 條蛇運行,第一條蛇的 start_moving 函式會被呼叫,你會被困在那里。第二條蛇還沒有被創造出來。為了說服自己,嘗試添加一個 if event.key is q, return out of the function。然后你會看到,當你要兩條蛇時,第一條蛇會跑,然后你按q,第一條蛇會消失,第二條蛇會出現。
解決您的問題的方法是在您的專案中創建一個專門的游戲回圈,并將您的所有游戲更新委托給那里。有幾種不同的方法可以做到這一點,所以我將把它留給你設計。但總的來說,這是我在偽代碼中推薦的:
snakes = [Snake() for _ in range(numplayers)]
while True:
for event in pg.events():
if event is keypress:
for snake in snakes:
snake.handle_keys(event.key)
for snake in snakes:
snake.update(dt)
for snake in snakes:
snake.draw(display)
display.flip()
tick() # or calculate dt
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/446020.html
標籤:python-3.x 班级 游戏
上一篇:如何過早退出__enter__并跳過Python中的with塊?
下一篇:C#類初始化和設定資料和串列資訊
