python - Python: pygame - 尝试使用 python 将图像导入 pygame
问题描述
所以,我已经在我的第一个游戏上工作了一段时间,但我一直卡在同一个地方,试图向蛇应该收集的苹果添加一个图像,但它不起作用。它给了我这个错误:TypeError:参数 1 必须是 pygame.Surface,而不是列表。我的代码在下面,因为这是我的第一个游戏,所以很乱,请不要判断。
import pygame
import sys
import time
import random
import collections
import itertools
import os
import pygame.mixer
pygame.init()
pygame.mixer.init()
apple = [pygame.image.load('New Piskel.png')]
#colect_1 = pygame.mixer.Sound("Beep_Short.mp3")
def main():
"""Snake v 1.59"""
score = 0 # Initial score
speed = pygame.time.Clock()
direction = "R" # Initial direction
snake_position = collections.deque([100, 50]) # Initial snake position
snake_body = collections.deque([[100, 50], [90, 50], [100, 50]]) # Initial snake body
# It places the food randomly, excluding the border
food_position = [random.randrange(1, 72) * 10, random.randrange(1, 46) * 10]
food_spawn = True
# Will define the colors
white = pygame.Color("white")
red = pygame.Color("red")
green = pygame.Color("green")
black = pygame.Color("black")
orange = pygame.Color("red")
grey = pygame.Color("light grey")
# Game surface
player_screen = pygame.display.set_mode((720, 460)) # Set screen size
pygame.display.set_caption("Snake v.1.38") # Set screen title and version
def initializer():
""" Checks the mistakes, and closes the program if it does while
printing on the console how many bugs it has, also initializes
the mixers, and game """
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.mixer.init()
bugs = pygame.init()
if bugs[1] > 0:
print("There are", bugs[1], "bugs! quiting.....")
time.sleep(3)
sys.exit("Closing program")
else:
print("The game was initialized")
def game_sound(s):
""" Include the game sfx and music"""
if s == 0:
directory = os.path.dirname(os.path.realpath(sys.argv[0]))
full_path = os.path.join(directory, "background.ogg")
pygame.mixer.music.play(-1)
elif s == 1:
directory = os.path.dirname(os.path.realpath(sys.argv[0]))
full_path = os.path.join(directory, "eating.wav")
elif s == 2:
directory = os.path.dirname(os.path.realpath(sys.argv[0]))
full_path = os.path.join(directory, "game-over.wav")
def start_screen():
""" The beggining screen that you see at the beginning of the game
and the ene if you die"""
player_screen.fill(white)
start1_font1 = pygame.font.SysFont("times new roman", 44)
start2_font2 = pygame.font.SysFont("times new roman", 20)
start1_surface = start1_font1.render("Welcome To Snake! (A pygame remake.)", True, black)
start2_surface = start2_font2.render("Press 'space' to start", True, black)
start1_position = start1_surface.get_rect()
start1_position.midtop = (360, 100)
start2_position = start2_surface.get_rect()
start2_position.midtop = (360, 150)
player_screen.blit(start1_surface, start1_position)
player_screen.blit(start2_surface, start2_position)
pygame.display.flip()
def you_lose():
""" When the players loses, it will show a red message in times new
roman font with 44 px size in a rectangle box"""
font_game_over = pygame.font.SysFont("times new roman", 44)
start2_font2 = pygame.font.SysFont("times new roman", 20)
game_over_surface = font_game_over.render("Game Over!", True, red)
start2_surface = start2_font2.render("Press 'o' to restart", True, black)
game_over_position = game_over_surface.get_rect()
game_over_position.midtop = (360, 15)
start2_position = start2_surface.get_rect()
start2_position.midtop = (360, 150)
player_screen.blit(game_over_surface, game_over_position)
player_screen.blit(start2_surface, start2_position)
scoring()
pygame.display.flip() # Updates the screen, so it doesnt freeze
def pause_menu():
"""It displays the pause menu"""
player_screen.fill(white)
pause1_font1 = pygame.font.SysFont("times new roman", 44)
pause2_font2 = pygame.font.SysFont("times new roman", 20)
pause3_font3 = pygame.font.SysFont("times new roman", 20)
pause1_surface = pause1_font1.render("Paused!", True, black)
pause2_surface = pause2_font2.render("Press 'space' to unpause!", True, black)
pause3_surface = pause3_font3.render("press 'o' to restart", True, black)
pause1_position = pause1_surface.get_rect()
pause1_position.midtop = (360, 90)
pause2_position = pause2_surface.get_rect()
pause2_position.midtop = (360, 170)
pause3_position = pause3_surface.get_rect()
pause3_position.midtop = (360, 220)
player_screen.blit(pause1_surface, pause1_position)
player_screen.blit(pause2_surface, pause2_position)
player_screen.blit(pause3_surface, pause3_position)
pygame.display.flip()
def quiting():
""" When this function is called, it will wait 3 seconds and exit"""
time.sleep(1)
pygame.quit()
sys.exit()
def scoring():
""" It will shows the score after the game over in times new
roman font with 16px size and black color in a rectangle box"""
score_font = pygame.font.SysFont("times new roman", 16)
score_surface = score_font.render("Score : {}".format(score), True, black)
score_position = score_surface.get_rect()
score_position.midtop = (360, 80)
player_screen.blit(score_surface, score_position)
def ingame_scoring():
""" It will shows the score after the game over in times new
roman font with 16px size and black color in a rectangle box"""
iscore_font = pygame.font.SysFont("times new roman", 16)
iscore_surface = iscore_font.render("Score : {}".format(score), True, black)
iscore_position = iscore_surface.get_rect()
iscore_position.midtop = (360, 15)
player_screen.blit(iscore_surface, iscore_position)
initializer()
pygame.display.flip()
paused = False
run = True
if run == True:
start_screen()
paused = not paused
#if run == True:
#pygame.mixer.Sound.play(bg_music)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quiting()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing/ unpausing
paused = not paused
if paused:
pygame.mixer.music.pause()
pause_menu()
else:
pygame.mixer.music.unpause()
# Choose direction by user input, block opposite directions
key_right = event.key in (pygame.K_RIGHT, pygame.K_d)
key_left = event.key in (pygame.K_LEFT, pygame.K_a)
key_down = event.key in (pygame.K_DOWN, pygame.K_s)
key_up = event.key in (pygame.K_UP, pygame.K_w)
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
paused = not paused
if paused:
pygame.mixer.music.pause()
pause_menu()
if keys[pygame.K_o]:
main()
if key_right and direction != "L":
direction = "R"
elif key_left and direction != "R":
direction = "L"
elif key_down and direction != "U":
direction = "D"
elif key_up and direction != "D":
direction = "U"
elif event.key == pygame.K_ESCAPE:
quiting() # It will quit when esc is pressed
# Simulates the snake movement(together with snake_body_pop)
if not paused:
if direction == "R":
snake_position[0] += 10
elif direction == "L":
snake_position[0] -= 10
elif direction == "D":
snake_position[1] += 10
elif direction == "U":
snake_position[1] -= 10
# Body mechanics
snake_body.appendleft(list(snake_position))
if snake_position == collections.deque(food_position):
score += 1 # Every food taken will raise the score by 1
food_spawn = False # It removes the food from the board
else:
# If the food is taken it will not remove the last body piece(raising snakes size)
snake_body.pop()
if food_spawn is False: # When a food is taken it will respawn randomly
food_position = [random.randrange(1, 72) * 10, random.randrange(1, 46) * 10]
food_spawn = True # It will set the food to True again, to keep the cycle
# Drawing
player_screen.fill(grey) # Set the background to grey
for position in snake_body: # Snake representation on the screen
pygame.draw.rect(player_screen, green, pygame.Rect(position[0], position[1], 10, 10))
# Food representation on the screen
player_screen.blit(apple,(food_position[0], food_position[1], 10, 10))
if snake_position[0] not in range(0, 711) or snake_position[1] not in range(0, 451):
you_lose()
paused = True # Game over when the Snake hit a wall
for block in itertools.islice(snake_body, 1, None):
if snake_position == collections.deque(block):
you_lose()
paused = True # Game over when the Snake hits itself
pygame.display.flip() # It constantly updates the screen
speed.tick(10) # It sets the speed to a playable value
if __name__ == "__main__":
main()
解决方案
apple = []
生成一个空列表并apple = [pygame.image.load('New Piskel.png')]
生成一个包含一个元素的列表。
当你想要blit
苹果时,你必须得到列表的第一个元素(apple[0]
):
player_screen.blit(apple[0], (food_position[0], food_position[1], 10, 10))
无论如何,您似乎根本不需要列表。Ifapple
是一个实例pygame.Surface
而不是一个列表:
apple = pygame.image.load('New Piskel.png')
然后apply
可以blit
直接:
player_screen.blit(apple, (food_position[0], food_position[1], 10, 10))
推荐阅读
- php - 如何从 Google 云上的 Bitnami 服务器 Debian 10 发送带有 PHP 脚本的电子邮件?
- selenium - 我应该怎么办?我收到一个错误,即“未找到元素名称=密码 - 硒”
- python - 熊猫在每个月计算不同的天数,ID 出现
- javascript - 有没有办法使用网络蓝牙打印条码?
- delphi - 将 C# 代码(字符串)迁移到 Delphi 10
- javascript - 给定证书,我如何确定哪些算法和格式可用于公钥?
- reactjs - 警告:从 submitForm() 捕获到未处理的错误错误:
- http - 使用范围请求下载内容损坏
- python - Python Django - 带有查看请求的问题
- r - 使用 ggplot2 在分组条形图中添加来自不同列的误差线